Bitemporal Knowledge Graphs for Claude Code: Stopping Context Rot Across 50-Turn Sessions
Bitemporal Knowledge Graphs for Claude Code: Stopping Context Rot Across 50-Turn Sessions
Tags: claude, ai, python, architecture
Canonical repo: https://github.com/Benni-OS/claude-code-memory
Long coding sessions with Claude Code break down in a predictable way. Around turn 25, after a few rounds of refactoring and file edits, the model starts forgetting architectural constraints established in turn 3. By turn 50, context compaction has flattened earlier decisions into vague summaries, or worse, left contradictory facts sitting in CLAUDE.md with no record of which one is still true.
Flat markdown memory files cannot tell the difference between a decision that is currently active, a decision that was superseded an hour ago, and an invariant that must never be overwritten. When you delete a line from a markdown file to update it, you lose the audit trail. When you append a new line without retiring the old one, the agent reads both and hallucinates a hybrid architecture.
To solve this, claude-code-memory replaces flat append-only notes with a SQLite WAL-backed bitemporal knowledge graph implemented in BitemporalGraph.
Why Bitemporal Time Matters for Agent Memory
A standard database table stores only the latest state. A bitemporal model tracks two independent timelines for every fact:
- Valid time (
valid_fromandvalid_to), which records when a fact was actually true in the codebase. - Transaction time (
tx_time), which records when the agent wrote that fact into memory.
In claude_code_memory/graph.py, every relationship between two Entity nodes is stored as a frozen Edge dataclass (@dataclass(frozen=True, slots=True)). When an architectural decision changes, invalidate_fact() does not run a DELETE. Instead, it sets valid_to to the current UTC ISO-8601 timestamp (utc_now_iso()). Active edges simply have valid_to IS NULL, exposed via the Edge.is_active property.
This separation gives you two capabilities that flat files cannot provide. First, active queries see only the current truth without being polluted by retired decisions. Second, point-in-time queries using as_of and tx_as_of let you reconstruct exactly what the agent knew at any earlier turn in a 50-turn session.
The SQLite WAL Schema
Running an agent memory store inside a local CLI workflow requires zero external services, fast reads, and safe concurrent access when hooks or subagents read while another process writes. BitemporalGraph opens .claude/memory.db with check_same_thread=False, enables Write-Ahead Logging, and creates two indexed tables in _init_schema():
PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON; CREATE TABLE IF NOT EXISTS entities ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE, entity_type TEXT NOT NULL DEFAULT 'concept', metadata_json TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS edges ( id INTEGER PRIMARY KEY AUTOINCREMENT, source_id INTEGER NOT NULL REFERENCES entities(id) ON DELETE CASCADE, relation TEXT NOT NULL, target_id INTEGER NOT NULL REFERENCES entities(id) ON DELETE CASCADE, valid_from TEXT NOT NULL, valid_to TEXT, tx_time TEXT NOT NULL, confidence REAL NOT NULL DEFAULT 1.0, source_file TEXT, is_invariant INTEGER NOT NULL DEFAULT 0, metadata_json TEXT NOT NULL DEFAULT '{}' ); CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name); CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_id, relation); CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_id, relation); CREATE INDEX IF NOT EXISTS idx_edges_bitemporal ON edges(valid_from, valid_to, tx_time); Setting journal_mode=WAL with synchronous=NORMAL keeps writes fast while allowing concurrent readers to inspect the graph without blocking on a write lock. The composite index idx_edges_bitemporal on (valid_from, valid_to, tx_time) ensures point-in-time lookups stay fast as the graph grows across dozens of sessions.
Protecting Invariants and Retiring Stale Facts
One of the subtle failure modes in long agent runs is accidental drift on core constraints. In BitemporalGraph, edges carry an is_invariant flag. When invalidate_fact() is called without force=True, it appends e.is_invariant = 0 to the WHERE clause, protecting non-negotiable architectural rules from being silently retired during routine updates.
Here is how assert_fact(), invalidate_fact(), and query() work together in Python:
from claude_code_memory.graph import BitemporalGraph with BitemporalGraph(".claude/memory.db") as graph: # Record an architectural invariant that should survive refactoring graph.assert_fact( "session_store", "uses_backend", "sqlite_wal", source_type="module", target_type="storage", is_invariant=True, source_file="claude_code_memory/graph.py", ) # Record a mutable implementation detail at turn 4 graph.assert_fact( "auth_middleware", "validates_with", "hs256_jwt", confidence=0.95, valid_from="2026-11-27T10:00:00Z", ) # At turn 32, the team switches to EdDSA; retire the old fact without deleting history retired = graph.invalidate_fact( source="auth_middleware", relation="validates_with", target="hs256_jwt", valid_to="2026-11-27T11:15:00Z", ) graph.assert_fact( "auth_middleware", "validates_with", "eddsa_jwt", valid_from="2026-11-27T11:15:00Z", ) # Current query returns only eddsa_jwt active_edges = graph.query(entity="auth_middleware") # Point-in-time query reconstructs what was true at 10:30 UTC past_edges = graph.query( entity="auth_middleware", as_of="2026-11-27T10:30:00Z", ) Notice how query() orders results by e.is_invariant DESC, e.confidence DESC, e.id DESC. Invariants always surface first, followed by high-confidence facts and recent assertions. When a user prompt or hook needs to search the graph with free-form text, tokenize_query() strips common stopwords and short tokens so lookups stay focused on actual symbols, filenames, and concepts.
Verification
In the claude-code-memory test suite, the bitemporal graph, invalidation guards, timestamp normalization (normalize_timestamp()), and point-in-time queries pass 29/29 tests in 0.68s. Because everything runs against local SQLite with zero network hops, memory reads and writes stay sub-millisecond inside Claude Code hooks.
Explore the full implementation and schema in the repository at https://github.com/Benni-OS/claude-code-memory and learn more about the broader ecosystem at https://benni-os.net.