# Why Claude Code Loses Context After /compact (And How Bi-Temporal Graph Memory + AST Drift Locks Fix It)

> Source: <https://dev.to/bennialencar/why-claude-code-loses-context-after-compact-and-how-bi-temporal-graph-memory-ast-drift-locks-5fpb>
> Published: 2026-11-22 06:03:03+00:00

**Recommendation:** 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.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

*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.
