agentmemory icon indicating copy to clipboard operation
agentmemory copied to clipboard

backfill observation.concepts during graph-extract to unblock legacy consolidate under AUTO_COMPRESS=false

Open vincentyang2026 opened this issue 4 months ago • 1 comments

Under the default AGENTMEMORY_AUTO_COMPRESS=false, observations are stored via buildSyntheticCompression which hardcodes concepts: [] (see
src/functions/compress-synthetic.ts). This means:

- Every observation has empty concepts
- Legacy mem::consolidate groups observations by concept (requires ≥3 observations sharing a concept)
- Grouping never happens → mem::consolidate returns {"consolidated": 0, "totalObservations": N} no matter how many observations exist
- Downstream episodic memories never form → semantic/reflect tiers starve

Current workarounds have significant costs

1. AUTO_COMPRESS=true — per-observation LLM call. For tool-heavy sessions this multiplies API cost dramatically (already flagged by the boot log warning re #138).
2. Manual concept authoring — requires callers to fill concepts at write time; most Hermes/opencode integrations don't.
3. External backfill script — separate LLM pass adds cost and complexity.

Proposed solution

mem::graph-extract already runs one LLM call per session-end (via event::session::stopped) to extract graph nodes and edges. We can extend that same call to also emit
per-observation concepts, then write them back to KV.observations.

Zero extra LLM calls. Same prompt, same response, extra output section.

Sketch

1. In src/prompts/graph-extraction.ts, extend GRAPH_EXTRACTION_SYSTEM to also request an <observations_concepts> block:

    xml
    <observations_concepts>
      <obs index="1"><concept>topic-a</concept><concept>topic-b</concept></obs>
      <obs index="2"><concept>topic-c</concept></obs>
    </observations_concepts>
    

    Observations are already numbered [1] [2] ... in the current prompt, so the index mapping is trivial.

2. Add parseObservationConcepts(xml) in src/functions/graph.ts — returns { [index]: string[] }. Uses indexOf (no regex, robust to LLM whitespace/formatting variance).

3. In mem::graph-extract, after parseGraphXml, backfill:

    typescript
    const obsConceptMap = parseObservationConcepts(response);
    for (const [idxStr, concepts] of Object.entries(obsConceptMap)) {
      const idx = parseInt(idxStr, 10) - 1;
      const obs = data.observations[idx];
      if (!obs || !concepts?.length) continue;
      if (obs.concepts?.length > 0) continue;              // idempotent
      const sid = data.sessionId || obs.sessionId;
      if (!sid) continue;
      await kv.set(KV.observations(sid), obs.id, { ...obs, concepts });
    }
    

4. Ensure event::session::stopped and api::graph-build pass sessionId in the payload so the KV write can locate the correct KV.observations(sid) scope.

Empirical result (local prototype)

Prototyped on top of v0.9.27 (patched the dist bundle directly). Results on a live install running Hermes + opencode sharing the same daemon:

| Metric                              | Before          | After                                                  |
|-------------------------------------|-----------------|--------------------------------------------------------|
| Hermes observations with concepts   | ~0%             | 88%                                                    |
| Opencode observations with concepts | 0%              | 64% (rest are current-session obs pending session-end) |
| Graph nodes                         | 22              | 167                                                    |
| mem::consolidate output             | consolidated: 0 | consolidated: 10 (produces episodic memories)          |
| Extra LLM calls per session         | +0              | +0                                                     |

Idempotency & safety

- Only writes when obs.concepts is currently empty — repeated runs never overwrite existing values
- No schema change — concepts field already exists on Observation
- No new function registrations — just extends mem::graph-extract behavior
- If prompt parsing fails (LLM omits the block), graph extraction still succeeds; observations just remain empty (same as today)

Questions before I send a PR

1. Is the maintainer open to this approach, or is there a preferred alternative direction (e.g. a separate concept-only trigger, or waiting for a different consolidate path)?
2. Should the concept output be opt-in via env flag (e.g. GRAPH_EXTRACT_BACKFILL_CONCEPTS) for safety, or on by default?
3. Any concerns about additional prompt tokens? (Adds ~5 lines to the system prompt and per-obs XML tags in output; my measured overhead is ~5-8% of the graph-extract response
length.)

Happy to submit a PR against the TypeScript source (src/prompts/graph-extraction.ts, src/functions/graph.ts, and the two trigger sites in event::session::stopped /
api::graph-build) with tests once you confirm direction.

Environment:
- agentmemory 0.9.27
- Node 24.x on Arch Linux
- Running as REST daemon on 127.0.0.1:3111, consumed by Hermes plugin and opencode

vincentyang2026 avatar Jul 14 '26 09:07 vincentyang2026

Data point that may widen the scope of this issue: I see the same empty-concepts behavior with AGENTMEMORY_AUTO_COMPRESS=true, not false. If that reproduces for others, the trigger isn't only the default-off path.

No credentials, hostnames, or request contents included.

Environment: agentmemory 0.9.28, iii 0.11.2, Docker, EMBEDDING_PROVIDER=local, CONSOLIDATION_ENABLED=true, GRAPH_EXTRACTION_ENABLED=true.

Measured:

  • AGENTMEMORY_AUTO_COMPRESS=true confirmed in the running container's environment (docker exec … env), not merely in the compose file.
  • Every observation sampled has concepts: [] and facts: []:
    • 3 sessions by hand: 462 / 462 empty
    • the 5 most recently started sessions: 2,480 / 2,480 empty
  • The observations are otherwise intact — GET /agentmemory/observations?sessionId=… returns full narrative text. Only the extracted fields are empty.

I checked the obvious confound. My first thought was that these rows simply predate the flag being turned on. They don't — AGENTMEMORY_AUTO_COMPRESS=true is present in every compose backup on disk going back to 2026-05-17, which covers the entire lifetime of every observation sampled (the newest are from two days ago).

Downstream effect, consistent with your description:

  • consolidation over 905 session summaries produced only 7 new semantic facts
  • POST /agentmemory/search, MCP memory_recall, and MCP memory_smart_search all return only hand-saved memory_save entries — no observation or summary ever surfaces, for queries whose terms appear in thousands of observations
  • smart_search scores cluster at 0.0087–0.0094, i.e. a flat keyword floor

Ruling out embeddings, since that was my first (wrong) hypothesis: I ran @xenova/transformers inside the container directly — pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2') returns a valid 384-dim vector in ~8s, and @xenova/transformers, @huggingface and onnxruntime-node are all installed. So on this deployment the embedding path is healthy and #931 does not apply; the corpus simply has no extracted concepts to index or group on.

I have not read the source path that writes these rows, so I can't say whether buildSyntheticCompression is being reached despite the flag, or whether something else short-circuits compression before it. Happy to run a targeted check if you can point at the branch you'd want instrumented.

Your proposed fix — emitting per-observation concepts from the existing mem::graph-extract call — would resolve this for me either way, since it doesn't depend on which compression path ran.

tr3lane avatar Jul 26 '26 23:07 tr3lane