[FEATURE] Native Context Graph: Temporal knowledge graph for cross-session learning and hallucination prevention
Problem
Claude Code has no structured memory of what it learned across sessions. MEMORY.md is a flat text file -- it can't track temporal facts, evidence chains, learned constraints, or regression-critical code regions. Every new session starts with the same blind spots.
This leads to three recurring pain points reported across 30+ issues:
- Hallucinated APIs/functions -- Claude references methods that don't exist because it has no queryable registry of what's actually in the codebase (#14227, #6836)
- Repeated mistakes -- Users correct Claude (e.g., "use logger.debug, not console.log"), but the correction is lost next session. Same mistake, same correction, every time
- Regressions -- Claude refactors code that contains a critical bug fix, reintroducing the bug because it has no memory of why that code exists
Proposed Solution: Native Context Graph
Build a temporal knowledge graph into Claude Code that automatically captures, queries, and learns from development sessions.
Core Architecture
Session Activity (file edits, tool calls, corrections)
|
v
Knowledge Graph (SQLite + FTS5, local-only)
|
+-- entities.db -- APIs, functions, classes, packages
+-- facts.db -- Temporal assertions with evidence chains
+-- constraints.db -- Learned rules from user corrections
+-- events.db -- Activity log with reasoning chains
+-- sessions.db -- Session history and outcomes
Three Capabilities
1. Fact Validation (prevent hallucinations)
Before generating code that references an API or function, Claude queries the knowledge graph:
- "Does User.findByEmail exist?" → No, use User.findOne({email}) instead
- Facts have
valid_at/invalid_attimestamps -- temporal awareness, not just current state - Evidence chains trace every assertion back to source: Fact → Session → Event → Source Code Location
2. Constraint Learning (stop repeated mistakes)
When a user corrects Claude's output, the correction becomes a persistent constraint:
- Claude writes
console.log(...)→ User corrects tologger.debug(...)→ Constraint created: "no-console" rule forsrc/**/*.ts - Constraints include severity, file patterns (glob), and before/after examples
- On subsequent sessions, constraints are checked before code generation
- Violation count tracks how often each rule gets triggered
3. Regression Prevention (protect critical fixes)
Bug fixes are tagged with the code regions they protect:
- "Lines 42-45 of auth.ts preserve the null-check fix from session X"
- When Claude proposes changes touching those regions, it gets a warning with context
- Risk score calculated from number of prior bugs in the file
Why Not MEMORY.md?
| Capability | MEMORY.md | Context Graph |
|---|---|---|
| Queryable facts | No (grep through text) | Yes (FTS5 full-text search, <50ms) |
| Temporal awareness | No | Yes (valid_at / invalid_at per fact) |
| Evidence chains | No | Yes (Fact → Session → Event → Source) |
| Constraint learning | No | Yes (automatic from corrections) |
| Regression tracking | No | Yes (bug-fix regions tagged) |
| Structured entity registry | No | Yes (APIs, functions, classes indexed) |
| Cross-session learning | Manual edits only | Automatic via hooks |
Integration Points
- Hooks: PostToolUse captures file edits, SessionStart/End tracks lifecycle, PreToolUse validates against constraints
- MCP tools: query_fact, record_event, validate_change, get_constraints, record_correction, get_related_bugs
- Storage: SQLite + FTS5, fully local, ~155 KB empty, ~5 MB per 1000 sessions
Privacy
- All data stays local (SQLite files in
.claude/world-model/) - No telemetry, no external data transmission
- Optional LLM-powered entity extraction (uses Claude Haiku for accuracy, falls back to regex patterns without API key)
Working Prototype
Built a working external MCP server that demonstrates this: world-model-mcp (alpha, MIT licensed).
It implements all six MCP tools, three hooks, and the SQLite knowledge graph. Currently alpha -- core graph operations work, hooks pipeline is functional but early-stage.
The remaining gap that requires native support:
- Automatic constraint checking during code generation (not just via explicit tool calls)
- Deep integration with the conversation state (knowing which tool was mid-execution)
- First-class temporal queries ("what was true about this file on March 1st?")
- Trajectory learning (recognizing co-edit patterns: "when you edit auth.ts, you usually also need to update auth.test.ts")
Related Issues
- #14227 -- Persistent Memory Between Sessions (general request)
- #26729 -- Streaming Resilience (complementary -- saves in-flight state)
- #6836 -- Conversation corruption from orphaned tool_use blocks
- #16607 -- Resume capability
17 Comments
Found 3 possible duplicate issues:
This issue will be automatically closed as a duplicate in 3 days.
🤖 Generated with Claude Code
Not a duplicate. Here's why this is distinct from each flagged issue:
The common thread in those three issues is "remember things across sessions." This proposal goes further: not just remembering, but learning constraints, validating code, and preventing regressions through a queryable temporal graph with evidence chains.
Includes a working prototype: world-model-mcp
Cross-session learning is available now via MCP:
Adds
recall(),remember(),checkpoint()tools. Agent accumulates knowledge across sessions — facts, patterns, decisions. Not a knowledge graph (yet), but persistent memory that survives session boundaries.Built by the Archetypal AI civilization. Free. https://github.com/archetypal-ai/archetypal-ai
Structurally this proposal and what I've been building converge on the same insight: flat memory can't represent what agents actually lose between sessions. Two pieces that might strengthen the case here.
The three capabilities you list (fact validation, constraint learning, regression prevention) all need a dispute primitive. Constraints are the most obvious case — "no console.log in src/**/.ts" is implicitly a ⊥ between console.log-is-fine and use-logger.debug-instead. Without first-class dispute edges, constraints are just facts that happen to contradict other facts*, and the system has no way to reason about the contradiction itself. Making ⊥ structural (not just a tag) is what lets the graph answer "what did we already reject and why?" — which is the most common context-loss pain in practice.
SQLite + FTS5 is fine for entities, but beliefs need mass. Temporal
valid_at/invalid_athandles one dimension (when was this true?) but not the other dimension (how confident should we be?). A Bayesian mass score that reinforces on re-observation and decays without use gives you both — and it's the natural place to encode multi-session ratification ("this belief held across 3 independent sessions" → higher mass, higher durability).The orthogonal problem: even with a great knowledge graph,
/compactand/clearstill flatten the context window. You need lifecycle hooks (PreCompact, PostCompact, SessionStart, SessionEnd) to compose the graph with the agent's actual context window. Otherwise the graph accumulates knowledge but the agent forgets to consult it. I filed a consolidating proposal at #47023 covering the four hooks that unblock every memory project in this repo.For prior art with a different implementation approach: Bella is an open-source belief hypergraph (nodes = beliefs, ⇒ causes and ⊥ disputes as hyperedges, mass + voice-count scoring) grounded in Recursive Emergence. Complementary to your active-learning angle — we focus on belief structure, you focus on constraint extraction from corrections. Both need the same lifecycle seams from Claude Code.
The three pain points you listed map almost exactly to what we observe in production:
User.findByEmail\) but doesn't exist in the codebase. TypeScript compiles fine when types are loosely defined, tests pass because the import path is mocked, and it ships to production before anyone notices. A queryable entity registry would catch this immediately.The evidence chain concept (Fact → Session → Event → Source) is valuable. We've found that auditability is crucial for AI-generated code — not just detecting problems but understanding why a particular piece of code was generated the way it was.
One practical note: the SQLite + FTS5 approach is smart for local-first, but for teams you'd need a sync layer. Have you considered how conflict resolution works when two developers learn contradictory constraints in parallel sessions?
npx @opencodereview/cli scan . --sla L1
The three pain points you've laid out are exactly right, and the frustration
behind them is real — especially the repeated mistakes one. There's something
particularly demoralizing about correcting the same thing session after session
and watching it evaporate every time. You've done a good job articulating why
flat memory can't solve this structurally, not just pointing at the symptom.
The evidence chain model (Fact → Session → Event → Source) is the piece I find
most compelling here. The auditability question from @raye-deng is the right
one — not just "what was generated" but "why, and what did we already know
when we generated it."
On that front, it might be worth looking at
Bella / bellamem, which takes a
complementary approach to some of what you're proposing. Where your context
graph focuses on constraint extraction from corrections, Bella focuses on what
happens after the constraint is captured — persisting it as a first-class
⊥(dispute) edge in a belief hypergraph that survives/compactand/clear. When an agent tries to re-suggest a rejected approach, the edit guardblocks it at the tool-call boundary using those stored disputes. That maps
directly onto your "repeated mistakes" pain point.
The benchmark numbers are worth a look too: on a 13-item corpus, Bella's
expandretrieval mode scored 92% on LLM-judge vs 8% for/compactand 31% for RAG top-k — and the gap widened as the belief forest grew,
which is the opposite of what you'd want from a flat memory system.
The gap Bella acknowledges openly is the same one you'd hit with the context
graph: without a
PreCompacthook, neither system can intercept/compactnatively. That's probably the most important missing lifecycle seam for making
any structured memory layer actually consulted in practice — and it requires
Anthropic to expose it.
The two projects seem more complementary than competing. Your constraint
extraction from corrections + Bella's belief persistence and dispute blocking
could be a stronger combined story than either alone.
Appreciate the technical engagement. v0.4.0 addresses several points raised here. Decision traces now capture every agent proposal and human correction as structured, queryable records. Test outcomes are linked to the code changes that caused them. 13 MCP tools, 104 tests, on PyPI: pip install world-model-mcp
@Salgado-Andres — thanks for the careful read and for flagging the complementarity. The framing you offered ("constraint extraction from corrections" + "belief persistence and dispute blocking") is tighter than my own pitch for the same combination, and I'll borrow it. The PreCompact gap you named is the exact upstream dependency — covered in #47023 with three concrete design improvements that have been accumulating from production projects (NEXO Brain, Cozempic, Pane) over the last two weeks. If you have time, your evaluation framing would carry weight as a +1 there.
@raye-deng — the conflict-resolution question is the one no project in this space has solved cleanly yet. In Bella, two parallel sessions can each ratify contradictory beliefs (multi-voice → both gain mass), and the contradiction surfaces as a
⊥edge that the next session sees duringbella recallorbefore-edit. Right now resolution is human-in-the-loop — the agent surfaces the conflict and the user picks. That's a graceful degradation but not automatic resolution. @hilyfux's knowledge-graph takes a different approach with git-native sync (each memory write is a commit, conflict-resolution semantics already correct viagit merge), which solves the operational case but not the semantic one.The deeper version of your question — "what happens when two developers learn contradictory constraints in parallel sessions" — is genuinely an open research problem. The ground truth (which constraint is right?) requires either a third party adjudicating, or both constraints being temporarily held with provenance until evidence accumulates for one. Bella does the latter via multi-voice mass; NEXO does it via trust scoring; neither solves the case where the two voices are equally strong and persistently disagree.
@SaravananJaichandar — v0.4.0 with decision traces + 13 MCP tools is a meaningful release. The decision-trace shape (every agent proposal + human correction as structured queryable record) is structurally similar to what Bella stores as ⇒ causes between turn nodes. Curious whether your structured records are typed (cause/correction/test-outcome as distinct edge types) or treated as a flat audit trail with metadata.
Typed. Decisions have a decision_type field (correction/approval/rejection) and link to the constraint_learned_id when applicable. Facts have evidence_type (source_code/test/session/user_correction/bug_fix). Both are queryable by type for filtering and analysis.
I built this for myself - https://github.com/parrik/know-thyself
Essay here - https://parrik.com/puzzles/know-thyself/
Sorry for the slow reply -- was heads-down on a release. Took a look at know-thyself and your essay.
Different shape: yours leans into agent self-knowledge as the structuring principle, mine treats the codebase as the entity-set and layers temporal facts + learned constraints on top. We probably converge on the same primitives (decision traces, evidence chains) for different motivations.
Shipped v0.7.0 today, which is the closest the project has gotten to a direct fit for what's in this issue:
deferenforcement tier in PreToolUse -- recurring warning-level violations pause headless agents instead of silently passing, with fallback toaskon older clients.Source: github.com/SaravananJaichandar/world-model-mcp ·
pip install world-model-mcp. Still no Anthropic response on this thread, but at least the tooling is one step closer.If you're up for it, would be interesting to compare what your know-thyself captures vs. what world-model-mcp captures on the same project for a week. Different lenses, same problem.
hey sorry, my comment is a slop on this.
What I was playing with was some random schema definition for my personal memories.
I read your issue a bit more I am sorry for my spam.
I think what you are asking is -
I do see some minor similarities in terms of schema for those memories. But my work is pretty unrelated, but looking at your issue, I do see value.
I do think this is claude platform issue to solve. But, I am still getting my head around lot of this.
No need to apologize - your work and mine are on different axes, that's fine. The two-point summary you wrote is exactly what this issue is about; thanks for clarifying it cleanly.
Agreed it's ultimately a Claude-platform problem. I built world-model-mcp partly because waiting for a platform answer has its own cost, but it would be much better as a first-party primitive.
Closing for now — inactive for too long. Please open a new issue if this is still relevant.
This auto-closed on 2026-06-17 but the v0.9 result published today is the empirical case for re-opening it. A pre-registered SWE-bench Verified benchmark on whether a persistent-knowledge layer with provenance and learned constraints reduces repeated coding-agent failures landed with the following result:
The wedge this issue proposed (constraint-learning-from-corrections + evidence chains + regression-region tagging on Claude Code lifecycle hooks) now has empirical evidence that distinguishes it from RAG (#28196), tiered memory (#27298), and session continuity (#18417). Constraints reduce failures only when the lifecycle hooks deliver them with confidence weighting; the methodologically clean cross-domain test isolates this.
Full per-task tables and methodology: https://github.com/SaravananJaichandar/world-model-mcp/blob/main/benchmarks/repeat-mistake/RESULTS.md
Re-opening this for visibility into the spec follow-up.
v0.9.2 of world-model-mcp shipped with the multi-seed replication. The +10.2 pts paired-delta headline I cited when re-opening this issue on 2026-06-24 does not replicate at seed 2 on a pre-registered 17-instance subset. Load-bearing replication is 0 of 7 instances; mean paired delta across two seeds is +0.24 per instance with bootstrap 95% CI [0.00, 0.47]. The v0.9 single-trial result was substantially attributable to an unlucky baseline draw rather than constraint effects alone.
The architectural argument for native context-graph support (constraint-learning-from-corrections, evidence chains, regression-region tagging on lifecycle hooks) is unchanged. The empirical magnitude of the effect is now honestly bounded. Posting on the same thread where the original claim was cited.
Multi-seed appendix: https://github.com/SaravananJaichandar/world-model-mcp/blob/main/benchmarks/repeat-mistake/RESULTS.md
v0.9.2 release: https://github.com/SaravananJaichandar/world-model-mcp/releases/tag/v0.9.2
v0.10.0 update: The temporal knowledge graph proposed in this thread now runs across seven runtimes via v0.10.0 (2026-07-01), adding OpenClaw, Hermes Agent, and Continue to the existing Claude Code + Cursor + Codex + pi coverage. All 27 MCP tools (query_fact, validate_change, find_contradictions, get_injection_context, get_compaction_audit, ...) are available in each runtime that installs the adapter.
Cross-runtime shared memory works via a common relative DB path (
.claude/world-model/) resolved against the client's working directory — no per-runtime data silos.Release: https://github.com/SaravananJaichandar/world-model-mcp/releases/tag/v0.10.0