cd /news/ai-agents/inside-claude-code-s-precompact-and-… · home › topics › ai-agents › article
[ARTICLE · art-177492] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

Inside Claude Code's PreCompact and SessionStart Hooks: Deterministic Memory Injection Without RAG Noise

A developer built claude-code-memory, an agent memory system that uses Claude Code's native SessionStart, PreCompact and Stop lifecycle hooks to inject a deterministic, bounded slice of a SQLite-backed bitemporal knowledge graph and AST-compacted source files instead of vector RAG. The SessionStart handler builds a query hint from the hook payload and retrieves a subgraph at depth=2 and limit=15, while PreCompact pairs graph facts with ASTCompactor summaries of up to six files, all truncated to a 6000-character budget and returned via Claude Code's hookSpecificOutput contract. The approach separates valid time from transaction time and tags critical constraints as invariants, so stale design docs are not resurfaced after a migration.

recommendation

Replace top-k vector retrieval with lifecycle-hook injection of a bounded bitemporal graph slice and AST-compacted signatures, capped at 6000 characters, to keep agent memory deterministic and current.

more in playbook: Designing agent systems
by read3 min views3 publishedNov 27, 2026

Most agent memory systems fail for the same reason: they treat every context window problem as a vector search problem. When an agent starts a session or hits a context compaction boundary, dumping top-k cosine similarity chunks into the prompt introduces stale architectural assumptions, partial code snippets, and high token overhead.

In claude-code-memory, we took a different route. Instead of embedding chunks and hoping retrieval ranks the right paragraph, the system uses Claude Code's native lifecycle hooks (SessionStart, PreCompact, and Stop) to inject a deterministic, bounded slice of a SQLite-backed bitemporal knowledge graph and AST-compacted source files.

Vector RAG is probabilistic and stateless with respect to time. If a team migrates from REST to gRPC on Tuesday, a semantic search on Wednesday will still surface Monday's REST design docs because the wording matches the query.

A bitemporal graph separates valid time (when a fact is true in the codebase) from transaction time (when the database recorded it), and marks critical constraints as invariants. Combining that graph with lifecycle hooks gives three concrete properties:

SessionStart) or right before the conversation history is summarized ( PreCompact). max_chars = 6000 by default) so memory never crowds out the active task..claude/memory.db. When Claude Code fires a SessionStart hook, handle_hook in claude_code_memory/hooks.py reads the incoming JSON payload and constructs a query_hint by joining non-empty values from four payload keys: prompt, query, custom_instructions, and reason.

It then opens BitemporalGraph at .claude/memory.db and calls retrieve_subgraph(query_hint, depth=2, limit=15). The returned edges are serialized inside a <bitemporal-memory> XML block, preserving invariant tags, optional source_file annotations, and confidence scores:

with BitemporalGraph(db_path) as graph:
    if event == "SessionStart":
        subgraph = graph.retrieve_subgraph(query_hint, depth=2, limit=15)
        context = _format_edges_context(subgraph["edges"], max_items=15)
        return {
            "hookSpecificOutput": {
                "hookEventName": "SessionStart",
                "additionalContext": context[:max_chars],
            }
        }

The output conforms directly to Claude Code's hookSpecificOutput contract:

{
  "hookSpecificOutput": {
    "hookEventName": "SessionStart",
    "additionalContext": "<bitemporal-memory>\n- AuthService --[uses]--> JWT [INVARIANT] (auth.py) (conf=1.00)\n</bitemporal-memory>"
  }
}

Because the graph traversal is bounded to depth=2 and limit=15, the startup injection stays fast and predictable.

Long coding sessions inevitably trigger context compaction. Without intervention, compaction summarizes away exact function signatures, file paths, and invariants that were discussed thirty turns ago.

The PreCompact handler in hooks.py expands the graph budget slightly (depth=2, limit=20) and pairs those facts with structural code summaries produced by ASTCompactor.

files list, ASTCompactor.compact_file processes up to 6 specified files, stripping function bodies while keeping signatures, imports, and types._compact_workspace_context scans cwd (defaulting to up to 6 files within max_chars // 2, or 3000 characters) and wraps the output in <compacted-ast-context>.# filename (-X% tokens)), and the combined graph facts and AST blocks are joined and truncated to max_chars (6000) under hookEventName: "PreCompact".

{
  "hookSpecificOutput": {
    "hookEventName": "PreCompact",
    "additionalContext": "<bitemporal-memory>\n...\n</bitemporal-memory>\n\n<compacted-ast-context>\n# server.py (-68% tokens)\n...\n</compacted-ast-context>"
  }
}

When Stop fires at the end of a turn, the hook inspects data.get("facts") for triples containing source, relation, and target, allowing the session to persist newly discovered relationships without manual tool calls.

Hooks handle automatic context injection, while the stdio JSON-RPC 2.0 MCP server (claude_code_memory/mcp_server.py, protocol version 2024-11-05) exposes four explicit tools to the model:

memory_assert: Records a directed typed edge ( source, relation, target) with optional source_type, target_type, valid_from, confidence (default 1.0), source_file, and is_invariant (default false). memory_query: Searches the graph by entity, query_text, with bitemporal filters as_of, tx_as_of, include_invalidated (default limit (default 25). memory_invalidate: Marks active facts as no longer valid by edge_id or triple (valid_to, force) without deleting historical records. memory_compact: Runs deterministic AST compaction on Python or TypeScript/JavaScript source via path or inline language. Separating passive lifecycle hooks from active MCP tools keeps the agent's baseline context clean while giving it full read/write control over bitemporal facts whenever architecture or requirements shift.

Repository: https://github.com/Benni-OS/claude-code-memory

Project site: https://benni-os.net

── more in #ai-agents 4 stories · sorted by recency
── more on @claude code 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/inside-claude-code-s…] indexed:0 read:3min 2026-11-27 · —