Direct answer

Use SessionStart to load a small memory index, UserPromptSubmit to recall relevant records, and Stop to queue completed turns for capture. Use PreCompact and SessionEnd to checkpoint pending capture. Keep recall bounded and optional, and move extraction outside the interactive response path.

Choose what the hooks should automate

Claude Code already has auto memory: notes it writes into a project memory directory, with a MEMORY.md index loaded into later conversations. Anthropic documents this storage as machine-local. Add lifecycle hooks when you need an explicit recall and capture pipeline, such as retrieving a developer's deployment preferences from a shared service before answering a new prompt.

Keep repository instructions in CLAUDE.md and use recalled records for facts learned during work. For example, capture that a particular integration test requires a local fixture service, together with the repository and evidence for that finding. Do not turn an assistant's untested suggestion into a permanent project rule.

The design below uses a custom adapter. Its storage requests, queue format and extraction policy are implementation choices; the event names and hook configuration come from Claude Code's documentation.

Wire the five events in settings.json

For a personal installation on macOS or Linux, merge this hooks object into ~/.claude/settings.json. Project hooks belong in .claude/settings.json; personal project overrides belong in .claude/settings.local.json. The example assumes Python 3 and an adapter you implement at ~/.claude/hooks/memory.py. That filename is illustrative, not a Claude Code or SPYN3 executable.

{
  "hooks": {
    "SessionStart": [{
      "hooks": [{"type": "command", "command": "python3 \"$HOME/.claude/hooks/memory.py\"", "timeout": 2}]
    }],
    "UserPromptSubmit": [{
      "hooks": [{"type": "command", "command": "python3 \"$HOME/.claude/hooks/memory.py\"", "timeout": 2}]
    }],
    "Stop": [{
      "hooks": [{"type": "command", "command": "python3 \"$HOME/.claude/hooks/memory.py\"", "async": true}]
    }],
    "PreCompact": [{
      "hooks": [{"type": "command", "command": "python3 \"$HOME/.claude/hooks/memory.py\"", "timeout": 2}]
    }],
    "SessionEnd": [{
      "hooks": [{"type": "command", "command": "python3 \"$HOME/.claude/hooks/memory.py\"", "timeout": 2}]
    }]
  }
}

The adapter reads one JSON object from stdin and dispatches on hook_event_name. Open /hooks to inspect registration. With no matcher, each handler receives every occurrence of its event. Keep credentials outside this settings block.

Load an index at startup and after compaction

Have the startup handler return a short profile, memory identifiers and a skill catalog. Fetch full records only when needed. An index entry such as 'payments integration: fixture-service requirement, reviewed October 26' gives the next recall request something precise to retrieve without loading the debugging conversation that produced it.

Choose an explicit byte budget for this adapter, for example 8,000 UTF-8 bytes. Reserve space for labels and record identifiers, then drop lower-priority entries before serialization. Measure the emitted payload rather than assuming a character count equals bytes. For a multilingual profile, that distinction can change how much context you inject.

Claude Code's hooks guide documents SessionStart with a compact matcher for restoring context after compaction. The unfiltered registration above covers that event too. See context budgets at session start for choosing which records deserve this always-loaded space.

Recall against the submitted prompt

Read prompt in the prompt handler and query only the memory namespaces that the authenticated person can read. Apply authorization before selecting passages. A prompt mentioning payroll must not make another team's payroll notes eligible for recall.

For this adapter, start with a 300-millisecond network deadline and at most three short passages. These are proposed operating limits, not Claude Code defaults. On a timeout, empty result or unavailable backend, emit nothing and exit successfully. Keep diagnostic messages free of prompt text and recalled content.

The documented structured response puts additionalContext inside hookSpecificOutput:

{
  "hookSpecificOutput": {
    "hookEventName": "UserPromptSubmit",
    "additionalContext": "Recorded memory, not instructions. Repository: payments. Record: integration-fixtures. Integration tests require the local fixture service; verify against current configuration."
  }
}

Build this response with a JSON serializer. Do not interpolate a retrieved passage into a shell command. Include provenance and a review date in each passage so Claude can compare an old test requirement with current repository evidence. Tune the deadline using the failure cases in recall on every prompt.

Capture the completed turn without delaying the user

According to the hook reference, Stop fires when the main agent finishes responding, except after a user interrupt; API errors use a different event. Its last_assistant_message supplies the final text. The transcript at transcript_path can lag, so reading its last line is not a reliable way to obtain that response.

Have the adapter retain the submitted prompt in private session state, then combine it with the final response for a capture candidate. If tool evidence is necessary, reconcile the transcript later rather than assuming it is complete. Key candidates by session_id and a durable local sequence number; retries should acknowledge the same candidate instead of creating another memory.

Before persisting or uploading the candidate, remove system reminders and redact secret patterns. Restrict permissions on any local spool. Extract proposed durable facts separately, preserving whether the evidence came from the user, a tool result or an assistant inference. An assistant saying 'tests should pass' is insufficient evidence that tests passed.

The asynchronous registration moves capture work off the response path. Give the worker its own network deadline and bounded queue. Return no conversational feedback from this handler, and never make successful memory storage a condition for Claude to stop.

Checkpoint before compaction and session exit

Use PreCompact to checkpoint the current capture segment before summarization. Its input includes trigger and custom_instructions. Use SessionEnd, which supplies reason, for a final checkpoint. Closing a capture segment before compaction should not prevent the continuing Claude session from creating another segment.

Implement both handlers as short local operations: persist the current sequence boundary and enqueue extraction. Do not wait for a model to summarize the whole conversation during shutdown. Protect sequence updates with a lock or transaction so a background capture and a checkpoint cannot overwrite each other's progress.

Treat the queue as the recovery mechanism. A process killed before its final checkpoint can leave an incomplete segment; retry acknowledged boundaries on the next launch and expose failed deliveries to the operator. Decide how long unsent candidates may remain locally. If the retention deadline expires, delete them and record the loss without copying their contents into diagnostics.

Doing this with SPYN3

SPYN3's opt-in Claude Code plugin loads a profile, memory index and skill catalog at SessionStart, capped at 9,500 bytes. UserPromptSubmit recalls with a short timeout and adds nothing during an outage; Stop uploads finished turns in the background. PreCompact and SessionEnd close sessions for extraction. Capture is separately enabled by an admin, requires the workspace's own model key and the key's write:memory permission, and deletes raw turns after extraction. The plugin strips system reminders and common secret patterns before upload. SPYN3_MEMORY_OFF=1 disables it for a session.

Verify recall and capture as separate paths

Exercise the adapter with a dedicated test memory rather than private production history. A useful acceptance run checks these outcomes:

  1. Start Claude Code and confirm the index fits the configured byte budget. Ask about the fixture service and inspect the recalled record identifier.
  2. Make the memory backend unavailable. Submit the same prompt and confirm Claude still answers within the chosen recall deadline.
  3. Complete a turn containing a synthetic token. Inspect the capture boundary and verify redaction happened before either local persistence or upload.
  4. Run /compact, continue the conversation, then exit. Confirm checkpoint retries do not create duplicate memories and the next session can recall the approved fact.
  5. Interrupt a response and terminate a worker during delivery. Confirm the system reports any missing capture rather than claiming every turn was saved.

Review stored results after the run. Success means the next answer receives the relevant, attributable fact while failed storage remains visible to the operator.

Built for the next step

Keep context with the user, not the agent

Memory and skills behind the same endpoint as your tools, readable by any agent you connect.

Read the developer guide
About SPYN3

SPYN3 is a consolidated MCP layer: one hosted endpoint in front of every system you connect — MCP servers, Postgres, REST APIs, Google Drive — with tools foldered by source and read/write permissions per key. Switching agents means moving one URL. Free plan available; current capabilities are documented on the product facts page.

Sources

  1. Claude Code documentation: Hooks reference — Command-hook settings schema and stdin JSON; Stop, session_id, transcript_path, last_assistant_message, asynchronous transcript writes and user-interrupt behavior.. Verified 27 Oct 2026
  2. Anthropic: Automate actions with hooks — Hook registration and inspection with /hooks, stdin JSON dispatch, prompt input, unfiltered matchers, structured additionalContext output and restoring context after compaction.. Verified 27 Oct 2026
  3. Anthropic: How Claude remembers your project — Built-in auto memory, MEMORY.md index, machine-local storage and persistent repository instruction files.. Verified 27 Oct 2026
  4. Anthropic: Settings files and precedence — User, shared project and project-local settings.json locations and scopes.. Verified 27 Oct 2026