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

> Source: <https://dev.to/bennialencar/inside-claude-codes-precompact-and-sessionstart-hooks-deterministic-memory-injection-without-rag-5apm>
> Published: 2026-11-27 22:10:23+00:00

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

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](https://github.com/Benni-OS/claude-code-memory)

Project site: [https://benni-os.net](https://benni-os.net)
