{"slug": "inside-claude-code-s-precompact-and-sessionstart-hooks-deterministic-memory-rag", "title": "Inside Claude Code's PreCompact and SessionStart Hooks: Deterministic Memory Injection Without RAG Noise", "summary": "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.", "body_md": "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.\n\nIn `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.\n\nVector 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.\n\nA 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:\n\n`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`.\nWhen 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`.\n\nIt 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:\n\n```\nwith BitemporalGraph(db_path) as graph:\n    if event == \"SessionStart\":\n        subgraph = graph.retrieve_subgraph(query_hint, depth=2, limit=15)\n        context = _format_edges_context(subgraph[\"edges\"], max_items=15)\n        return {\n            \"hookSpecificOutput\": {\n                \"hookEventName\": \"SessionStart\",\n                \"additionalContext\": context[:max_chars],\n            }\n        }\n```\n\nThe output conforms directly to Claude Code's `hookSpecificOutput` contract:\n\n```\n{\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"SessionStart\",\n    \"additionalContext\": \"<bitemporal-memory>\\n- AuthService --[uses]--> JWT [INVARIANT] (auth.py) (conf=1.00)\\n</bitemporal-memory>\"\n  }\n}\n```\n\nBecause the graph traversal is bounded to `depth=2` and `limit=15`, the startup injection stays fast and predictable.\n\nLong coding sessions inevitably trigger context compaction. Without intervention, compaction summarizes away exact function signatures, file paths, and invariants that were discussed thirty turns ago.\n\nThe `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`.\n\n`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\"`.\n\n```\n{\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"PreCompact\",\n    \"additionalContext\": \"<bitemporal-memory>\\n...\\n</bitemporal-memory>\\n\\n<compacted-ast-context>\\n# server.py (-68% tokens)\\n...\\n</compacted-ast-context>\"\n  }\n}\n```\n\nWhen `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.\n\nHooks 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:\n\n`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`.\nSeparating 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.\n\nRepository: [https://github.com/Benni-OS/claude-code-memory](https://github.com/Benni-OS/claude-code-memory)\n\nProject site: [https://benni-os.net](https://benni-os.net)", "url": "https://wpnews.pro/news/inside-claude-code-s-precompact-and-sessionstart-hooks-deterministic-memory-rag", "canonical_source": "https://dev.to/bennialencar/inside-claude-codes-precompact-and-sessionstart-hooks-deterministic-memory-injection-without-rag-5apm", "published_at": "2026-11-27 22:10:23+00:00", "updated_at": "2026-11-27 22:14:07.221652+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "large-language-models", "ai-safety"], "entities": ["Claude Code", "claude-code-memory", "SQLite", "ASTCompactor", "BitemporalGraph"], "also_reported_by": [], "takeaway": "Injecting a bounded bitemporal graph slice (depth=2, limit=15) plus AST-compacted signatures at SessionStart and PreCompact, capped at 6000 characters, avoids the stale-chunk and token overhead of vector RAG.", "recommendation": {"advice": "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.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/inside-claude-code-s-precompact-and-sessionstart-hooks-deterministic-memory-rag", "markdown": "https://wpnews.pro/news/inside-claude-code-s-precompact-and-sessionstart-hooks-deterministic-memory-rag.md", "text": "https://wpnews.pro/news/inside-claude-code-s-precompact-and-sessionstart-hooks-deterministic-memory-rag.txt", "jsonld": "https://wpnews.pro/news/inside-claude-code-s-precompact-and-sessionstart-hooks-deterministic-memory-rag.jsonld"}}