{"slug": "why-claude-code-loses-context-after-compact-and-how-bi-temporal-graph-memory-ast", "title": "Why Claude Code Loses Context After /compact (And How Bi-Temporal Graph Memory + AST Drift Locks Fix It)", "summary": "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.", "body_md": "*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).*\n\nEvery 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.\n\nThis is not a model intelligence problem. It is a **lossy compression and state-representation problem**:\n\n`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.\n**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.\n\n```\n**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**.\n```\n\nTo 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`.\n\n``` php\nflowchart LR\n    A[\"Claude Code Turn\\n(/compact or /clear)\"] -->|\"PreCompact / SessionStart Hook\"| B[\"MCP Memory Server\\n(SQLite Bi-Temporal Graph)\"]\n    B -->|\"Query: valid_until IS NULL\\n(< 1.2ms local)\"| C[\"Active Invariants + Rejected Alts\\nInjected as Compact Context\"]\n    C --> D[\"Code Generation\\n(Edits & Tool Calls)\"]\n    D -->|\"Turn End\"| E[\"Stop Hook: AST Reality Lock\\n(Tree-sitter / Python ast)\"]\n    E -->|\"0 Drift Violations\"| F[\"Turn Accepted\\n(Commit / Next Step)\"]\n    E -->|\"Contract Violation\"| G[\"Block Stop & Return\\nExact AST Diff to Agent\"]\n```\n\nNotice 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.\n\nMost \"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.\n\nA bi-temporal schema solves this deterministically:\n\n`valid_from`:` valid_until`:` NULL` while the constraint is active; populated the instant a new decision supersedes it (never deleted).`recorded_at`:\n\n``` python\nimport sqlite3\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import List, Optional\n\n@dataclass(frozen=True)\nclass TemporalFact:\n    subject: str\n    predicate: str  # e.g. \"MUST_USE\", \"FORBIDS\", \"REJECTED_ALT\", \"SCHEMA_LOCK\"\n    object_val: str\n    rationale: str\n    valid_from: str\n    valid_until: Optional[str]\n    recorded_at: str\n\nclass BiTemporalGraphStore:\n    \"\"\"Local SQLite bi-temporal graph exposed to Claude Code over stdio MCP.\"\"\"\n\n    def __init__(self, db_path: str = \".sovereign/memory.db\"):\n        self.conn = sqlite3.connect(db_path)\n        self.conn.execute(\"\"\"\n            CREATE TABLE IF NOT EXISTS graph_facts (\n                id INTEGER PRIMARY KEY AUTOINCREMENT,\n                subject TEXT NOT NULL,\n                predicate TEXT NOT NULL,\n                object_val TEXT NOT NULL,\n                rationale TEXT NOT NULL,\n                valid_from TEXT NOT NULL,\n                valid_until TEXT DEFAULT NULL,\n                recorded_at TEXT NOT NULL\n            )\n        \"\"\")\n        self.conn.execute(\n            \"CREATE INDEX IF NOT EXISTS idx_active ON graph_facts(subject, valid_until)\"\n        )\n        self.conn.commit()\n\n    def assert_fact(\n        self,\n        subject: str,\n        predicate: str,\n        object_val: str,\n        rationale: str,\n        supersedes_predicate: Optional[str] = None,\n    ) -> None:\n        now = datetime.now(timezone.utc).isoformat()\n        with self.conn:\n            if supersedes_predicate:\n                self.conn.execute(\n                    \"\"\"\n                    UPDATE graph_facts\n                    SET valid_until = ?\n                    WHERE subject = ? AND predicate = ? AND valid_until IS NULL\n                    \"\"\",\n                    (now, subject, supersedes_predicate),\n                )\n            self.conn.execute(\n                \"\"\"\n                INSERT INTO graph_facts\n                (subject, predicate, object_val, rationale, valid_from, valid_until, recorded_at)\n                VALUES (?, ?, ?, ?, ?, NULL, ?)\n                \"\"\",\n                (subject, predicate, object_val, rationale, now, now),\n            )\n\n    def query_active_invariants(self, subject_prefix: str = \"\") -> List[TemporalFact]:\n        \"\"\"Returns only currently valid constraints (< 1.2ms) for post-/compact injection.\"\"\"\n        cur = self.conn.execute(\n            \"\"\"\n            SELECT subject, predicate, object_val, rationale,\n                   valid_from, valid_until, recorded_at\n            FROM graph_facts\n            WHERE valid_until IS NULL AND subject LIKE ?\n            ORDER BY recorded_at ASC\n            \"\"\",\n            (f\"{subject_prefix}%\",),\n        )\n        return [TemporalFact(*row) for row in cur.fetchall()]\n```\n\nNotice 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.\n\nMemory 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.\n\nUnlike 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:\n\n``` python\nimport ast\nimport json\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom typing import Dict, List\n\ndef get_modified_python_files() -> List[Path]:\n    res = subprocess.run(\n        [\"git\", \"diff\", \"--name-only\", \"HEAD\"],\n        capture_output=True,\n        text=True,\n        check=False,\n    )\n    return [Path(p) for p in res.stdout.splitlines() if p.endswith(\".py\") and Path(p).exists()]\n\ndef verify_ast_contracts(files: List[Path], forbidden_imports: Dict[str, str]) -> List[str]:\n    violations: List[str] = []\n    for path in files:\n        tree = ast.parse(path.read_text(encoding=\"utf-8\"), filename=str(path))\n        for node in ast.walk(tree):\n            if isinstance(node, ast.Import):\n                for alias in node.names:\n                    if alias.name in forbidden_imports:\n                        violations.append(\n                            f\"{path}:{node.lineno} imports forbidden module '{alias.name}' \"\n                            f\"({forbidden_imports[alias.name]})\"\n                        )\n            elif isinstance(node, ast.ImportFrom) and node.module:\n                root_mod = node.module.split(\".\")[0]\n                if root_mod in forbidden_imports:\n                    violations.append(\n                        f\"{path}:{node.lineno} imports from forbidden module '{root_mod}' \"\n                        f\"({forbidden_imports[root_mod]})\"\n                    )\n    return violations\n\nif __name__ == \"__main__\":\n    # In production, loaded dynamically from BiTemporalGraphStore (predicate='FORBIDS')\n    active_bans = {\n        \"sqlalchemy\": \"REJECTED_ALT #12: Project uses raw asyncpg + typed SQL contracts.\",\n        \"pickle\": \"SECURITY_LOCK #04: Untrusted deserialization banned across all services.\",\n    }\n    drift = verify_ast_contracts(get_modified_python_files(), active_bans)\n    if drift:\n        # Claude Code Stop hook contract: exit code 2 blocks stop and feeds stderr back to model\n        print(json.dumps({\"decision\": \"block\", \"reason\": \"\\n\".join(drift)}), file=sys.stderr)\n        sys.exit(2)\n```\n\nWhen 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.\n\n| Dimension | Default `/compact` | Flat `CLAUDE.md` + Vector RAG | Benni-OS/claude-code-sovereign | \n|---|---|---|---|\n| **Negative Constraints & Rejected Alts** | Pruned during prose summarization | Lost in chunk noise / stale rankings | **Pinned via Typed Graph Edges (`REJECTED_ALT`)** | \n| **Temporal Superseding** | None (chronological blur) | Manual edits; old & new chunks collide | **Bi-Temporal (`valid_from`, `valid_until`, `recorded_at`)** | \n| **Post-`/clear` Recovery** | 0% session memory retained | Requires manual prompt re-seeding | **Automatic MCP Subgraph Re-Hydration (< 2 ms)** | \n| **Drift Enforcement** | Prompt-only (advisory) | Prompt-only (advisory) | **Deterministic `Stop`-Hook AST Reality Lock** | \n| **Infrastructure & Privacy** | Cloud session state | Often requires cloud embeddings/vector DB | **100% Local SQLite + stdio MCP (Zero Cloud Cost)** | \n\nIntegrating 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:\n\n```\n{\n  \"mcpServers\": {\n    \"sovereign-memory\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"claude_code_sovereign.mcp_server\", \"--db\", \".sovereign/memory.db\"]\n    }\n  },\n  \"hooks\": {\n    \"PreCompact\": [\n      {\n        \"matcher\": \"\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"python -m claude_code_sovereign.hooks.snapshot_invariants\"\n          }\n        ]\n      }\n    ],\n    \"Stop\": [\n      {\n        \"matcher\": \"\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"python -m claude_code_sovereign.hooks.ast_reality_lock\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\nWith 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.\n\nClone **Benni-OS/claude-code-sovereign**, attach the local SQLite bi-temporal MCP server, and enforce deterministic AST Reality Locks on every turn.\n\n```\n    Explore Benni-OS/claude-code-sovereign on GitHub →\nWhy does Claude Code forget architectural decisions right after /compact?\n      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.\n\n  What makes a knowledge graph bi-temporal (valid_from, valid_until, recorded_at)?\n  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.\n\n  How does the Stop-hook AST Reality Lock prevent architectural drift?\n  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.\n\n  Does claude-code-sovereign require an external cloud vector database?\n  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.\n```\n\nThe `/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.\n\nA 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.\n\nBefore 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.\n\nNo. `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.", "url": "https://wpnews.pro/news/why-claude-code-loses-context-after-compact-and-how-bi-temporal-graph-memory-ast", "canonical_source": "https://dev.to/bennialencar/why-claude-code-loses-context-after-compact-and-how-bi-temporal-graph-memory-ast-drift-locks-5fpb", "published_at": "2026-11-22 06:03:03+00:00", "updated_at": "2026-11-22 06:12:54.344655+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "large-language-models", "agent-protocols"], "entities": ["Benni Alencar", "Benni OS", "Claude Code", "claude-code-sovereign", "MCP", "SQLite", "Tree-sitter"], "also_reported_by": [], "takeaway": "Storing coding invariants in a bi-temporal graph keyed on valid_until IS NULL and gating each turn with a Stop-hook AST check keeps constraints alive across /compact and /clear for about 350–600 tokens instead of 40,000.", "recommendation": {"advice": "Store architectural invariants in a bi-temporal store and re-inject only facts with valid_until IS NULL after compaction, then block turn completion on an AST diff against those contracts.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/why-claude-code-loses-context-after-compact-and-how-bi-temporal-graph-memory-ast", "markdown": "https://wpnews.pro/news/why-claude-code-loses-context-after-compact-and-how-bi-temporal-graph-memory-ast.md", "text": "https://wpnews.pro/news/why-claude-code-loses-context-after-compact-and-how-bi-temporal-graph-memory-ast.txt", "jsonld": "https://wpnews.pro/news/why-claude-code-loses-context-after-compact-and-how-bi-temporal-graph-memory-ast.jsonld"}}