Why Claude Code Loses Context After /compact (And How Bi-Temporal Graph Memory + AST Drift Locks Fix It) Benni Alencar, Chief AI Systems Architect at Benni OS, built claude-code-sovereign, an open tool that pairs a local bi-temporal SQLite knowledge graph served over MCP with a Stop-hook AST Reality Lock to keep Claude Code from losing architectural constraints after /compact or /clear. The system stores invariants, schema contracts and rejected alternatives with valid_from, valid_until and recorded_at timestamps, re-hydrating only currently valid facts in under 1.2 ms (roughly 350–600 tokens instead of 40,000 tokens of chat history), then checks every modified file against the contract before a turn is accepted. Alencar argues vector-similarity memory retrieves superseded rules alongside active ones, whereas the bi-temporal schema resolves which constraint still applies deterministically. By Benni Alencar — Chief AI Systems Architect at Benni OS https://benni-os.net . Canonical article & interactive benchmarks at benni-os.net https://benni-os.net/blog/en/why-claude-code-loses-context-after-compact-bitemporal-memory.html . Every engineer running long refactoring or feature-build sessions in Claude Code hits the exact same cliff around turn 40. The context meter climbs past 85%, you run /compact or auto-compaction triggers , and for the next three turns everything looks fine—until the agent silently re-introduces an ORM pattern you explicitly banned 25 minutes ago, mutates a frozen API response schema, or re-attempts a Redis locking strategy you already proved deadlocks under load. This is not a model intelligence problem. It is a lossy compression and state-representation problem : CLAUDE.md or flat scratchpads lacks temporal validity. An invariant from Tuesday's prototype sits beside Thursday's production override with no way to distinguish active truth from superseded history. No Structural Enforcement at Turn Boundaries: Even if a constraint survives in the system prompt, nothing verifies the actual code emitted on disk against the architectural contract before the turn completes. Core Thesis: Compaction should compress conversational prose, never architectural truth. Benni-OS/claude-code-sovereign decouples working memory from structural memory by storing invariants, schema contracts, and rejected alternatives in a local bi-temporal knowledge graph exposed via MCP, paired with a deterministic Stop -hook AST Reality Lock . To survive both /compact and /clear without token bloat, claude-code-sovereign separates what is currently true in the codebase from when the agent observed or superseded it . Every architectural decision is stored as a typed edge or node with three timestamps: valid from , valid until , and recorded at . php flowchart LR A "Claude Code Turn\n /compact or /clear " -- |"PreCompact / SessionStart Hook"| B "MCP Memory Server\n SQLite Bi-Temporal Graph " B -- |"Query: valid until IS NULL\n < 1.2ms local "| C "Active Invariants + Rejected Alts\nInjected as Compact Context" C -- D "Code Generation\n Edits & Tool Calls " D -- |"Turn End"| E "Stop Hook: AST Reality Lock\n Tree-sitter / Python ast " E -- |"0 Drift Violations"| F "Turn Accepted\n Commit / Next Step " E -- |"Contract Violation"| G "Block Stop & Return\nExact AST Diff to Agent" Notice the closed feedback loop. Even after a hard /clear , the MCP server re-hydrates only the currently valid subgraph valid until IS NULL in under 1.2 ms —roughly 350–600 tokens of high-density structural facts instead of 40,000 tokens of stale chat history. Then, before Claude Code hands control back to you, the Stop hook runs an AST Reality Lock over every modified file. Most "agent memory" plugins use vector similarity search over unstructured text chunks. Vector search is fundamentally broken for coding constraints: if you ask for "auth middleware", cosine similarity retrieves both the deprecated JWT-in-cookie rule and the current mTLS-header rule, letting the LLM guess which one still applies. A bi-temporal schema solves this deterministically: valid from : valid until : NULL while the constraint is active; populated the instant a new decision supersedes it never deleted . recorded at : python import sqlite3 from dataclasses import dataclass from datetime import datetime, timezone from typing import List, Optional @dataclass frozen=True class TemporalFact: subject: str predicate: str e.g. "MUST USE", "FORBIDS", "REJECTED ALT", "SCHEMA LOCK" object val: str rationale: str valid from: str valid until: Optional str recorded at: str class BiTemporalGraphStore: """Local SQLite bi-temporal graph exposed to Claude Code over stdio MCP.""" def init self, db path: str = ".sovereign/memory.db" : self.conn = sqlite3.connect db path self.conn.execute """ CREATE TABLE IF NOT EXISTS graph facts id INTEGER PRIMARY KEY AUTOINCREMENT, subject TEXT NOT NULL, predicate TEXT NOT NULL, object val TEXT NOT NULL, rationale TEXT NOT NULL, valid from TEXT NOT NULL, valid until TEXT DEFAULT NULL, recorded at TEXT NOT NULL """ self.conn.execute "CREATE INDEX IF NOT EXISTS idx active ON graph facts subject, valid until " self.conn.commit def assert fact self, subject: str, predicate: str, object val: str, rationale: str, supersedes predicate: Optional str = None, - None: now = datetime.now timezone.utc .isoformat with self.conn: if supersedes predicate: self.conn.execute """ UPDATE graph facts SET valid until = ? WHERE subject = ? AND predicate = ? AND valid until IS NULL """, now, subject, supersedes predicate , self.conn.execute """ INSERT INTO graph facts subject, predicate, object val, rationale, valid from, valid until, recorded at VALUES ?, ?, ?, ?, ?, NULL, ? """, subject, predicate, object val, rationale, now, now , def query active invariants self, subject prefix: str = "" - List TemporalFact : """Returns only currently valid constraints < 1.2ms for post-/compact injection.""" cur = self.conn.execute """ SELECT subject, predicate, object val, rationale, valid from, valid until, recorded at FROM graph facts WHERE valid until IS NULL AND subject LIKE ? ORDER BY recorded at ASC """, f"{subject prefix}%", , return TemporalFact row for row in cur.fetchall Notice how REJECTED ALT facts stay active valid until IS NULL across the lifetime of the feature. When Claude Code runs /compact , the PreCompact or SessionStart hook queries query active invariants and pins every FORBIDS and REJECTED ALT edge into the fresh context window—preventing the agent from wasting 10 turns rediscovering why a design was rejected. Memory injection alone is advisory; models can still overlook a constraint during a complex multi-file edit. That is why claude-code-sovereign pairs the MCP graph with a deterministic Stop hook that inspects the actual Abstract Syntax Tree of modified files before a turn is allowed to complete. Unlike regex linters, an AST Reality Lock understands imports, function signatures, class inheritance, and schema fields. Below is a minimal Python AST Reality Lock enforced on Claude Code's Stop lifecycle event: python import ast import json import subprocess import sys from pathlib import Path from typing import Dict, List def get modified python files - List Path : res = subprocess.run "git", "diff", "--name-only", "HEAD" , capture output=True, text=True, check=False, return Path p for p in res.stdout.splitlines if p.endswith ".py" and Path p .exists def verify ast contracts files: List Path , forbidden imports: Dict str, str - List str : violations: List str = for path in files: tree = ast.parse path.read text encoding="utf-8" , filename=str path for node in ast.walk tree : if isinstance node, ast.Import : for alias in node.names: if alias.name in forbidden imports: violations.append f"{path}:{node.lineno} imports forbidden module '{alias.name}' " f" {forbidden imports alias.name } " elif isinstance node, ast.ImportFrom and node.module: root mod = node.module.split "." 0 if root mod in forbidden imports: violations.append f"{path}:{node.lineno} imports from forbidden module '{root mod}' " f" {forbidden imports root mod } " return violations if name == " main ": In production, loaded dynamically from BiTemporalGraphStore predicate='FORBIDS' active bans = { "sqlalchemy": "REJECTED ALT 12: Project uses raw asyncpg + typed SQL contracts.", "pickle": "SECURITY LOCK 04: Untrusted deserialization banned across all services.", } drift = verify ast contracts get modified python files , active bans if drift: Claude Code Stop hook contract: exit code 2 blocks stop and feeds stderr back to model print json.dumps {"decision": "block", "reason": "\n".join drift } , file=sys.stderr sys.exit 2 When Claude Code attempts to finish a turn after accidentally importing sqlalchemy post-compaction, the Stop hook exits with code 2 , surfaces the exact file, line number, and bi-temporal rationale REJECTED ALT 12 , and forces the agent to self-correct immediately before the human operator even sees the diff. | Dimension | Default /compact | Flat CLAUDE.md + Vector RAG | Benni-OS/claude-code-sovereign | |---|---|---|---| | Negative Constraints & Rejected Alts | Pruned during prose summarization | Lost in chunk noise / stale rankings | Pinned via Typed Graph Edges REJECTED ALT | | Temporal Superseding | None chronological blur | Manual edits; old & new chunks collide | Bi-Temporal valid from , valid until , recorded at | | Post- /clear Recovery | 0% session memory retained | Requires manual prompt re-seeding | Automatic MCP Subgraph Re-Hydration < 2 ms | | Drift Enforcement | Prompt-only advisory | Prompt-only advisory | Deterministic Stop -Hook AST Reality Lock | | Infrastructure & Privacy | Cloud session state | Often requires cloud embeddings/vector DB | 100% Local SQLite + stdio MCP Zero Cloud Cost | Integrating the bi-temporal MCP server and the Stop -hook AST Reality Lock requires zero changes to Claude Code's binary. You wire both into your repository's .claude/settings.json and MCP configuration: { "mcpServers": { "sovereign-memory": { "command": "python", "args": "-m", "claude code sovereign.mcp server", "--db", ".sovereign/memory.db" } }, "hooks": { "PreCompact": { "matcher": "", "hooks": { "type": "command", "command": "python -m claude code sovereign.hooks.snapshot invariants" } } , "Stop": { "matcher": "", "hooks": { "type": "command", "command": "python -m claude code sovereign.hooks.ast reality lock" } } } } With this configuration active, every /compact snapshots active decisions, every fresh session queries only non-superseded invariants, and every completed turn is structurally verified against the repository's AST contracts. Clone Benni-OS/claude-code-sovereign , attach the local SQLite bi-temporal MCP server, and enforce deterministic AST Reality Locks on every turn. Explore Benni-OS/claude-code-sovereign on GitHub → Why does Claude Code forget architectural decisions right after /compact? The /compact command replaces raw conversation turns with a lossy prose summary to reclaim context window space. While high-level task goals survive, negative constraints, rejected alternatives, and exact schema contracts are compressed away, causing the model to re-propose discarded designs or silently violate invariants. What makes a knowledge graph bi-temporal valid from, valid until, recorded at ? A bi-temporal graph tracks two independent timelines: valid time valid from and valid until , representing when a fact or constraint is true in the codebase and transaction time recorded at , representing when the agent learned or superseded it . This prevents stale rules from leaking into current prompts while preserving a full audit trail of rejected alternatives. How does the Stop-hook AST Reality Lock prevent architectural drift? Before Claude Code finishes a turn, the Stop hook parses modified files into an Abstract Syntax Tree AST and compares exported symbols, type signatures, and forbidden imports against active constraints in the bi-temporal graph. If drift is detected, the hook blocks completion and feeds the exact structural violation back to the agent. Does claude-code-sovereign require an external cloud vector database? No. Benni-OS/claude-code-sovereign runs 100% locally over SQLite and stdio MCP, with zero external API calls, zero cloud lock-in, and sub-millisecond graph queries across /compact and /clear boundaries. The /compact command replaces raw conversation turns with a lossy prose summary to reclaim context window space. While high-level task goals survive, negative constraints, rejected alternatives, and exact schema contracts are compressed away, causing the model to re-propose discarded designs or silently violate invariants. A bi-temporal graph tracks two independent timelines: valid time valid from and valid until , representing when a fact or constraint is true in the codebase and transaction time recorded at , representing when the agent learned or superseded it . This prevents stale rules from leaking into current prompts while preserving a full audit trail of rejected alternatives. Before Claude Code finishes a turn, the Stop hook parses modified files into an Abstract Syntax Tree AST and compares exported symbols, type signatures, and forbidden imports against active constraints in the bi-temporal graph. If drift is detected, the hook blocks completion and feeds the exact structural violation back to the agent. No. Benni-OS/claude-code-sovereign runs 100% locally over SQLite and stdio MCP, with zero external API calls, zero cloud lock-in, and sub-millisecond graph queries across /compact and /clear boundaries.