DEV Community

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

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.

Why Hook-Driven Injection Beats Ad-Hoc RAG

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:

  • Context is injected only at the exact moments Claude Code needs it: when a session boots (SessionStart) or right before the conversation history is summarized (PreCompact).
  • The injected payload is strictly capped by a character budget (max_chars = 6000 by default) so memory never crowds out the active task.
  • No background embedding pipeline or external vector database is required. Everything runs locally against .claude/memory.db.

How SessionStart Primes the Agent

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.

Surviving Compaction with PreCompact

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.

  • If the hook payload includes a non-empty files list, ASTCompactor.compact_file processes up to 6 specified files, stripping function bodies while keeping signatures, imports, and types.
  • If no files list is provided, _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>.
  • Each file header records the measured reduction percentage (# 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.

The Stdio MCP Server for Explicit Memory Operations

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, relation, target, or query_text, with bitemporal filters as_of, tx_as_of, include_invalidated (default false), and limit (default 25).
  • memory_invalidate: Marks active facts as no longer valid by edge_id or triple (source, relation, target, valid_to, force) without deleting historical records.
  • memory_compact: Runs deterministic AST compaction on Python or TypeScript/JavaScript source via path or inline source and 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

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.