feat(graph): backfill graph from stored memories
Summary
Adds a real graph backfill path for existing AgentMemory data, so users with historical memories/observations can populate the viewer graph instead of seeing 0 nodes / 0 edges forever.
This addresses the missing /agentmemory/graph/build path surfaced by the viewer rebuild flow and complements the existing session-end extraction path by adding historical backfill.
Fixes #505 — the viewer "Rebuild Graph" button now has a real backing endpoint instead of 404'ing. Confirmed by @code2tan to still be broken on v0.9.20.
What changed
- Add
mem::graph-buildto scan stored observations and latest memories, plan/apply in batches, skip already-processed source IDs, and default to safe dry-run. - Add
POST /agentmemory/graph/buildwith query/body validation. - Add
agentmemory graph-buildCLI, default dry-run;--applywrites graph records. - Make CLI apply resumable in bounded chunks to avoid long HTTP request timeouts.
- Fix
mem::graph-extractedge merging so edges point to persisted node IDs after duplicate node merges. - Update viewer graph rebuild UX with dry-run preview, confirmation, chunked apply, and resume-friendly failure text.
- Replace Unix-only build asset copy commands with a cross-platform Node script.
- Add focused graph tests and a local implementation report.
Verification
npm test -- test/graph.test.ts-> 11 tests passednpm run build-> passed on Windowsgit diff --check-> no whitespace errors- Local deployed dry-run before apply:
- memories scanned: 157
- source items found: 164
- eligible items: 164
- batches planned: 17
- graph before: 0 nodes / 0 edges
- Local apply result after resumable chunks:
- graph after: 395 nodes / 46 edges
- follow-up dry-run: eligible items 0, skipped existing 164
Notes
The viewer's empty-graph auto path remains read-only: it only performs a dry-run preview. A write happens only after explicit rebuild confirmation or CLI --apply.
Summary by CodeRabbit
- New Features
- Add graph-build REST endpoint and CLI with dry-run/apply, batching, per-chunk progress, and detailed build stats; viewer shows dry-run plan and guided “Rebuild Graph” flow.
- Bug Fixes
- Fixes to graph extraction/edge remapping and XML entity parsing for more reliable graph imports.
- Chores
- Simplified build pipeline with a robust asset-copy script; hook command strings quoted; new config toggle for stale index handling; proxy tool now forwards format/token budget.
- Documentation
- Updated README, agents docs, and site metadata to reflect endpoint count.
- Tests
- Expanded coverage for graph build/extract, hooks, env config, and proxy behavior.
@jonathanzhan1975 is attempting to deploy a commit to the rohitg00's projects Team on Vercel.
A member of the Team first needs to authorize it.
[!NOTE]
Reviews paused
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
- [ ] ▶️ Resume reviews
- [ ] 🔍 Trigger review
📝 Walkthrough
Walkthrough
Adds mem::graph-build orchestration and types, fixes mem::graph-extract node-id remapping and created/updated counters, registers POST /agentmemory/graph/build, adds CLI and viewer plan-first rebuild flows, extracts build asset copying, quotes plugin hook commands, updates config/startup and MCP proxying, expands tests, and adds an implementation report.
Changes
Build & Hook fixes
| Layer / File(s) | Summary |
|---|---|
Build asset copy script extraction package.json, scripts/copy-build-assets.mjs |
Asset copy logic moved into scripts/copy-build-assets.mjs; package.json build script now runs tsdown && node scripts/copy-build-assets.mjs. |
Quote plugin hook command paths plugin/hooks/hooks.codex.json, plugin/hooks/hooks.json, test/codex-plugin.test.ts |
Wrap ${CLAUDE_PLUGIN_ROOT}/scripts/*.mjs paths in quotes in both hook manifests and tighten tests to assert the quoted command pattern. |
Docs and generated metadata GRAPH_BACKFILL_IMPLEMENTATION_REPORT.md, AGENTS.md, README.md, website/lib/generated-meta.json |
Add implementation report and increment documented REST endpoint counts (124 → 125) in docs and generated meta. |
Graph Backfill Pipeline
| Layer / File(s) | Summary |
|---|---|
Graph backfill types and SDK orchestration src/functions/graph.ts, GRAPH_BACKFILL_IMPLEMENTATION_REPORT.md |
Add GraphBuildOptions/GraphBuildResult and mem::graph-build: scan sessions/memories into observations, dedupe (unless forced), plan batches with offset/limit, and (when apply) call mem::graph-extract per batch while aggregating counters, errors, totals, and an audit record. |
Graph extract node ID remapping src/functions/graph.ts |
Enhance mem::graph-extract to emit parsed vs created/updated counts, build a resolvedNodeIds map keyed by type:name to remap edge endpoints to persisted IDs, skip unresolved edges, and return detailed created/updated metrics. |
REST API graph/build endpoint src/triggers/api.ts |
Add POST /agentmemory/graph/build (api::graph-build) with query/body merging (query precedence), validation for positive batch/limit and non-negative offset, and delegation to mem::graph-build. |
CLI graph-build command with auth and chunking src/cli.ts |
Add graph-build CLI (dry-run default) supporting --apply, batching, filters, and chunked apply loop; refactor postJsonStrict to include JSON content-type and optional Authorization: Bearer <AGENTMEMORY_SECRET>; add option validators. |
Viewer plan-first dry-run and rebuild flow src/viewer/index.html |
When graph empty, viewer performs a dry-run plan (graph/build?dryRun=true), shows a summarized plan via graphBuildSummary(), and rebuildGraph() confirms then applies batches iteratively until complete while updating progress. |
Config, startup, and MCP proxy updates src/config.ts, src/index.ts, src/mcp/standalone.ts |
Add isDropStaleIndexEnabled() and use it during startup vector-index handling; extend MCP standalone to accept format and token_budget, proxy memory_recall to /agentmemory/search (default format: "full"). |
Comprehensive tests test/graph.test.ts, test/mcp-standalone-proxy.test.ts, test/env-loader.test.ts, test/codex-plugin.test.ts |
Add fixtures and tests for graph-build dry-run/apply/skip behavior, node ID reuse across extracts, API dry-run contract, MCP proxy behavior, env flag loading, and hook command quoting. |
Sequence Diagram
sequenceDiagram
participant CLI
participant Viewer
participant API as "POST /agentmemory/graph/build"
participant GraphBuild as "mem::graph-build"
participant GraphExtract as "mem::graph-extract"
participant KV as "Graph KV store"
CLI->>API: POST build (dryRun/apply params)
Viewer->>API: POST build (dryRun probe)
API->>GraphBuild: invoke with merged options
GraphBuild->>KV: load existing nodes/edges
GraphBuild->>KV: scan sessions/memories -> observations
alt dryRun
GraphBuild-->>API: return plan (batches planned, counts)
else apply per-batch
loop each batch
GraphBuild->>GraphExtract: extract(batch)
GraphExtract->>KV: persist/merge nodes & edges (resolve node ids)
GraphExtract-->>GraphBuild: return parsed/created/updated counts
end
GraphBuild->>KV: refresh totals & write audit
GraphBuild-->>API: return final GraphBuildResult
end
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45 minutes
"🐰 I hopped through logs and scanned each batch,
Dry-run plans laid out along the path,
IDs remapped, edges stitched with care,
CLI, viewer, REST — the pipeline's there,
A rabbit nods: the graph's repaired."
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The title 'feat(graph): backfill graph from stored memories' clearly and specifically describes the main change: adding graph backfill functionality from stored memories. |
| Linked Issues check | ✅ Passed | The PR fully addresses the requirements of linked issue #505 by implementing the missing POST /agentmemory/graph/build endpoint with both server-side backend support and viewer integration. |
| Out of Scope Changes check | ✅ Passed | All code changes are directly scoped to graph backfill objectives: new graph-build function, REST endpoint, CLI command, viewer UX updates, build asset script, and related tests/configuration updates. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.
🔧 ESLint
If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.
ESLint skipped: no ESLint configuration detected in root package.json. To enable, add
eslintto devDependencies.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Update on scope after debugging #559 and reviewing overlapping PRs:
I’m going to hold off on force-pushing more broad graph-build changes here until the direction of #494 and #533 is clearer.
Current plan:
- #494 already covers self-closing graph entity parsing, so I won’t duplicate that parser work in this PR.
- #533 overlaps with this PR on adding
/agentmemory/graph/build, so if #533 lands first I’ll rebase/scope this PR down instead of keeping a duplicate endpoint implementation. - The part that remains independent either way is rebuild convergence: graph build currently treats only graph node/edge
sourceObservationIdsas processed, so successful extractions that produce no graph records can be selected repeatedly. I’ll focus the next update here on audit-based processed detection, no-progress handling, viewer timeout, and better error visibility.
In short: I’ll wait for #494/#533 direction before expanding this PR further, and I’ll keep the next changes limited to the non-conflicting rebuild robustness pieces.