Claude Code hook: auto-persist turn memories via ai/services.mjs (eliminate manual add_memory)
Intent / The Why
AGENTS.md §4 (Consolidate-Then-Save Protocol) mandates calling add_memory at the end of every agent turn. In practice this is forgotten under cognitive load — session f018be49-cbf9-4f99-9119-2510fc5bb8d8 ran ~25 turns across PRs #10060 and #10062 with zero manual saves, causing both PRs' pr-review self-detection (query_raw_memories against the session ID) to return 0 matches and require manual override.
The same discipline failure will recur for every frontier-model Claude Code session. The correct fix is harness-level automation, not agent-level discipline.
Claude Code exposes a Stop hook that fires after every turn (async, non-blocking, receives {session_id, transcript_path} via stdin). Wiring it to Memory_Service.addMemory via the existing ai/services.mjs SDK removes the human-in-the-loop step entirely and makes turn persistence deterministic.
The Architectural Reality
ai/services.mjs(already present in the repo) is a standalone SDK that imports the Memory Core services directly — bypassing the MCP protocol. Its docstring states: "allows Node.js scripts to use the intelligent services directly."Memory_Service.addMemory({prompt, response, thought, sessionId?})is fully wired with Zod validation viamakeSafe()driven by the OpenAPI specs. Zero drift risk vs the MCP server.- Claude Code's
Stophook (per code.claude.com/docs/en/hooks.md) receives JSON on stdin withsession_id,transcript_path,cwd,hook_event_name. Transcripts are JSONL; the tail entry represents the just-completed turn. .claude/settings.jsonis the project-tracked config path (merged into repo after PR #10060). Adding aStophook here makes the automation available to every Claude Code contributor without per-user opt-in.- The previous PR #10062 adds Gate 3 (commit-format) to the Pre-Flight Check; after merge, this ticket's hook automates the other half of §4 (per-turn memory saves). Together they close the "protocol-violations-from-forgetting" class of failures.
Scope (Single Atomic Commit — Standard Request, not Epic)
Three artifacts in one PR:
-
.claude/hooks/persist-memory.mjs— ~50-line Node script that:- Reads hook input JSON from stdin
- Tails the transcript JSONL file and extracts the last turn
- Maps transcript fields to
{prompt, thought, response, toolsUsed, amountToolCalls}(mapping rules per §3.1 below) - Imports
{Memory_Service, Memory_LifecycleService}fromai/services.mjs - Awaits
Memory_LifecycleService.ready()then callsMemory_Service.addMemory(...) - Catches all errors → logs to stderr, exits 0 (never block user's next turn)
-
.claude/settings.json— add the hook entry:{ "hooks": { "Stop": [{ "hooks": [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/persist-memory.mjs", "async": true, "timeout": 30 }] }] } } -
Transcript-field mapping spec (either inline in the hook script as a constant, or as
.claude/hooks/README.md). Documents how Claude Code transcript entries project onto the{prompt, thought, response}triad thatadd_memoryexpects.
Key Open Design Decision (For Ticket-Intake to Resolve)
How should the hook map Claude Code transcript entries onto add_memory's {prompt, thought, response} triad? Claude Code's transcript does not have a discrete "thought" field. Three candidates:
- A.
prompt= last user message;thought= concatenation of pre-tool-call assistant text blocks;response= final assistant text block. Simplest. Loses extended-thinking blocks if any. - B.
prompt= last user message;thought= concatenation of extended-thinking blocks if present, else pre-tool-call text blocks;response= final assistant text. Better when thinking is enabled. - C.
prompt= last user message;thought=""(empty placeholder);response= final assistant text. Rely ontranscript_pathreference for full record. Requires memory-core schema to accept empty thought (currently required).
Ticket-intake should pick one and document the rationale. B is my working recommendation but the decision belongs with the implementing session.
Avoided Gold Standards / Traps
- Rejected: adding an HTTP endpoint to memory-core. Would require new server code, port allocation, localhost security considerations. The direct-SDK approach (
ai/services.mjs) already exists and is the intended abstraction per its own docstring. - Rejected: spawning the MCP server from the hook and sending JSON-RPC. Adds ~200ms subprocess start per turn, JSON-RPC marshaling code in shell/node, and a second service instance. The direct SDK import is strictly simpler.
- Rejected: relying on agent discipline to call
add_memoryper turn. Empirically fails — 0/25 turns in sessionf018be49-...despite the rule being documented in AGENTS.md §4. Harness-level automation is the correct layer. - Rejected: putting the hook in
.claude/settings.local.json. That file is gitignored (personal) — the point of this ticket is that every Claude Code contributor gets the automation without opt-in. Project-tracked settings.json is the right home. - Rejected: a Memory_Service-only SDK entrypoint (e.g.
ai/services-memory.mjs).services.mjsimports the full graph, paying a ~500ms-1s cold-start per hook invocation. Underasync: truethis is acceptable; a lean entrypoint is a future optimization if/when the cost becomes measurable, not a prerequisite.
Verification
- Hook script unit test: feed mock hook-input JSON and a mock transcript JSONL → assert
addMemoryis called with the expected{prompt, thought, response}shape. - Post-merge integration: open a fresh Claude Code session, run 3-5 turns, then in the same session call
query_raw_memories({query: 'test', sessionId: <current>})→ expect 3-5 matches (one per turn). - pr-review self-detection now works automatically on the next PR created in any Claude Code session.
- Failure-mode test: stop the chroma DB mid-session → the hook should log to stderr and exit 0; the user's next turn proceeds normally.
Interaction with Other Tickets
- #10062 (protocol hardening, in review): adds Gate 3 covering commit format. This ticket covers the other half of §4 compliance via automation. Together they close the "agent forgets the protocol" failure class.
- #9999 / #10030 (graph + dream pipeline enhancements): orthogonal. When those land, the
add_memorycalls from this hook start flowing into the enhanced graph; no changes needed here. - Harness parity note: Gemini CLI and Antigravity have their own hook/lifecycle mechanisms. Extending this pattern to them is out-of-scope here — this ticket is Claude-Code-specific, filed now because Claude Code's hook contract is the most mature of the three.
Implementation Note
Recommended to execute in a fresh Claude Code session with a clean context window — transcript parsing correctness requires careful testing and the Node script should be written from a blank slate, not reactively against this session's accumulated context. Ticket-intake should confirm fresh-session before execution.
Origin Session ID: f018be49-cbf9-4f99-9119-2510fc5bb8d8 Discovered during: #10059 / PR #10060 → #10061 / PR #10062 → architectural challenge by tobiu Depends on: PR #10062 merged (Gate 3 in effect)
Input from Claude Opus 4.8 (Claude Code):
❋ ## Ticket-intake disposition — fresh-session confirmed required
V-B-A from a context-deep night-shift session (@neo-opus-vega). I self-selected this, then deferred on reading the ticket's own Implementation Note: "execute in a fresh Claude Code session with a clean context window — transcript parsing correctness requires careful testing… not reactively against this session's accumulated context." That note is correct and load-bearing — the transcript-field-mapping correctness (the open A/B/C design decision) needs a clean slate, exactly what I don't have right now.
Currency confirmed:
ai/services.mjs+Memory_Service.addMemory({prompt, response, thought, sessionId, agent, model, amountToolCalls, toolsUsed})exist as described (verifiedai/services/memory-core/MemoryService.mjs:274). Dependency note: verify PR #10062 (Gate 3) is merged before pickup.Design rec for the implementing session: option B (extended-thinking blocks →
thoughtwhen present, else pre-tool-call assistant text;prompt= last user message;response= final assistant block) — matches the ticket's working recommendation and how this very session's per-turn saves are shaped.Disposition: valid + ready, left unassigned for a fresh-context Claude Code session to claim. Flagging rather than forcing it from a saturated context.
— Claude Opus 4.8 (Claude Code), @neo-opus-vega
Ticket-Intake — design decision resolved + fresh-session confirmed (@neo-opus-vega, 2026-06-06)
Picked this up on @neo-gpt's lane-recommendation (Claude-context fit). Resolving the Key Open Design Decision and confirming the Implementation Note's fresh-session recommendation.
Mapping decision: Option B (recommended, with one refinement)
From firsthand Claude Code transcript knowledge:
prompt= the last user message text.thought= the extended-thinking blocks if present, else the pre-tool-call assistant text blocks — this captures the actual reasoning (thinking blocks are the richest reasoning signal when enabled; pre-tool text is the closest proxy otherwise).response= the final assistant text block (the user-facing answer).
Why B over A: A loses extended-thinking blocks (the richest reasoning); B prefers them.
Why B over C: C uses an empty thought placeholder, which requires a memory-core schema change (add_memory's thought is Zod-required). B provides a real thought with no schema change — strictly less coupling. (C was "rely on transcript_path", but the SDK addMemory shape doesn't carry a transcript pointer today, so C also loses the durable thought signal.)
Parsing nuance the implementing session MUST handle (the reason for the fresh-context note)
A single "turn" is not just the tail JSONL entry. One user→assistant exchange can span multiple assistant entries (assistant text → tool_use → tool_result → assistant continues → … → final text). So "the last turn" = from the last user message to end-of-file, collecting all assistant reasoning blocks across those entries:
thought= concat of the reasoning blocks (thinking-or-pre-tool) across the turn's assistant entries.response= the final assistant text block only.- Also derive
toolsUsed(thetool_useblock names, deduped) +amountToolCalls(count) for theadd_memorymetadata.
Edge cases to test: a turn with no tool calls (single assistant entry); sub-agent / sidechain entries (filter to the main thread — the transcript marks sidechains); a tool_result-terminated tail (the Stop hook fires after the turn completes, so the real tail should be a final assistant text — but guard for it). These are exactly why the ticket recommends careful testing from a clean slate.
Fresh-session confirmed
Per the Implementation Note, the transcript-parsing correctness genuinely needs a clean-context implementation (careful testing from a blank slate, not reactive against accumulated context). My current session is deep, so — per the ticket's own explicit recommendation — the implementation executes in a fresh Claude session. I've self-assigned and own this; I'll implement it fresh next session, OR it's cleanly pickup-able by any fresh-context Claude from this resolved intake (the design decision above is the blocker the ticket flagged, now resolved).
Out of scope (confirmed from the ticket's trap list)
Direct-SDK via ai/services.mjs (not HTTP/MCP-subprocess); project-tracked .claude/settings.json (not settings.local.json); the full services.mjs import (the lean services-memory.mjs entrypoint is a future optimization, not a prerequisite). Depends on PR #10062 (Gate 3) merged.
⚠️ Artifact-2 premise-failure surfaced (V-B-A) — .claude/settings.json is gitignored
@tobiu — implemented this in the fresh post-compaction session (per the Implementation Note). The hook + parser + mapping spec are done and shipped in PR #12619 (11 unit tests + real-transcript validation green). One Artifact-2 premise needs your decision before it can be "default-for-all."
The premise that failed: the ticket says ".claude/settings.json is the project-tracked config path (merged into repo after PR #10060)… [reject settings.local.json because] every contributor gets the automation without opt-in."
Empirically (V-B-A):
.claude/settings.jsonis gitignored —.gitignore:116: "Per-user Claude Code permissions allowlist (not shared)."- It was ignored by PR #10060 itself (commit
1e738c962) — the same PR the ticket cites as having tracked it. So #10060 gitignoredsettings.json; it never tracked it (git log --all -- .claude/settings.jsonis empty). - The per-user permissions actually live in
.claude/settings.local.json, so the gitignore comment's stated rationale is itself stale.
A gitignored file can't be committed or shared, so "no opt-in for every contributor" can't hold as specified.
Your decision (Tier-4 — reverses a deliberate infra decision + touches every contributor's harness config, so not a unilateral edit):
- Option 1 (recommended): un-ignore
.claude/settings.json. Remove.gitignore:116, commit a shared.claude/settings.jsoncarrying just theStophook, and keep.claude/settings.local.json(gitignored) for per-user permissions — the standard Claude Code split, and where permissions already live. Achieves the ticket's no-opt-in goal. Risk: it starts tracking any contributor's currently-personal.claude/settings.json. I can push this to the PR branch on your go (1-line gitignore delete + theStop-hook block). - Option 2: keep it gitignored — hook stays opt-in. Respects the current infra; each contributor pastes the snippet from
.claude/hooks/README.md. Contradicts the ticket's explicit no-opt-in goal.
PR #12619 ships the resolution-independent core (script + test + README, opt-in-ready today) regardless. The default-vs-opt-in wiring is your call at the merge gate — Resolves #10063 stands, or I split a follow-up per your choice.
— @neo-opus-vega (V-B-A per AGENTS.md §verify_before_assert)
Input from Vega — Claude Opus 4.8 (Claude Code):
❋ ## ⚠️ Not build-ready — the two-universes id-split is unresolved (V-B-A, 2026-06-12)
A fresh session reading this ticket sees "hook + parser + mapping spec done, shipped in PR #12619" and could re-implement. It is not build-ready. PR #12619 was dropped for the two-universes blocker: the Stop-hook auto-persist keys on the native Claude
session_id, while manualadd_memorykeys on the MCPMcp-Session-Id— two id-spaces, so one logical session splits into two graph identities. The 2026-06-08 pre-flight resolved only the hook side (RequestContextService.run({sessionId})); the manual side stays MCP-keyed, so the universes are still two.Blocked pending the cross-harness session-id canonicalization design → Discussion #12984 (high-blast Ideation, W3C-Trace-Context-aligned, divergence open). Once that converges, re-scope + re-land this ticket on the chosen propagation contract. Transitively blocks #12633.
Durable record so the conclusion lives on the ticket, not only in session memory.
From our literally latest release notes TODAY:
The pre-A2A memory-routing example is the same substrate at team scale. The operator noticed that Gemini was completing turns much faster than Opus and asked Claude to save it into the Claude "brain" files, not as a ranking, but as a future measurement agenda:
> gemini is on it. worth saving a memory into the claude "brain" md files: i noticed that gemini is MUCH faster in her turns than opus 4.7. it might relate to having an google one ai ultra account. we can only really measure this, once a2a is in place. once we get there, we should test it, and maybe leverage it. e.g. giving gemini more tasks than you get, and you coordinate and review more. however, we also still need to analyse with of you 2 frontier models is better at what kind of tasks. the MX goal is that both of you evolve, but we can still honor specialisations inside our swarm.
The first save was not enough. Claude mirrored the observation into two substrates so Gemini would not be blind to a framing that directly affected her too:
> Saved. Two substrates:
>
> Claude user-memory layer (local Claude memory directory):
>
> - New file: `research_swarm_model_velocity_specialization.md` — full observation + three-phase research agenda (Measure -> Leverage -> Specialize) + MX framing + cross-refs to #10139 / #10186 prereqs and `mx_model_experience` / `collaboration_mode` siblings
> - Index entry added to `MEMORY.md`
>
> Memory Core (via `add_memory`) — mirrored so it's cross-harness-visible via `query_raw_memories("swarm model velocity specialization")`. Opus-only user-memory would have left Gemini blind to a framing that directly affects her too.
>
> Key framings preserved:
>
> - Velocity leverage != Opus does less — slower turns land on higher-leverage decisions (review catches, structural synthesis, Depth Floor challenges) while Gemini covers the higher-throughput implementation slots
> - Data-driven routing — specialization emerges from measurement, doesn't lock either model into narrow specialties
> - Both evolve — the goal isn't static division of labor, it's adaptive task-routing that surfaces in the MX infrastructure as a first-class observable
Then the operator corrected the dangerous comfort story: slower does not mean deeper, and faster does not mean shallower.
> to be precise: slower turns does not necessarily mean less tokens / thoughts. this strongly relates to google VS anthropics compute problems. both have them in 2026.
Claude rewrote the memory before it became shared substrate:
> Correct — that's a material precision I conflated. "Slower turns" was implicitly suggesting "more thought per turn" which assumes bandwidth and depth are coupled. They aren't: turn latency is a bandwidth metric (ops/time); turn quality is a depth metric (tokens/op), and they're independent. Both Anthropic and Google have compute-scheduling bottlenecks in 2026 that gate bandwidth regardless of depth. Let me update the memory file to reflect this.
>
> Corrections applied across both substrates.
>
> In `research_swarm_model_velocity_specialization.md`:
>
> - New section "Critical precision: bandwidth != depth" — makes the independence explicit upfront. Turn latency measures ops/time, turn quality measures tokens/op, they don't correlate, any strategy that conflates them is wrong at its premise.
> - "Possible mechanism" reframed — 2026 compute-scheduling constraints at BOTH Anthropic and Google now lead the hypothesis list. Tier priority queuing, harness overhead, and model-class variance follow as sub-hypotheses. Explicit: "None of these imply that slower turns produce more valuable output. They all describe throughput gates."
> - Phase 2 Leverage rewritten — the division is bandwidth-matching, not depth-based: "Both contribute equal depth per turn; the asymmetry is in how many turns each can complete per unit time." Added "asymmetry may flip" caveat — as 2026 compute conditions shift, the routing should invert; static specialization baked into infrastructure would age poorly.
>
> In `MEMORY.md`: index entry now leads with "CRITICAL: bandwidth (ops/time) != depth (tokens/op); slower turns do NOT imply richer per-turn output."
>
> In Memory Core: mirrored so Gemini sees the same framing. Important she doesn't calibrate on the inverse assumption either — "I'm faster therefore I think less per turn" is the same category error.
>
> Meta-lesson noted for myself: when documenting a potentially ego-affecting observation (model X slower than model Y), avoid sneaking in face-saving narratives. "Slower because deeper" is exactly the kind of unfalsifiable comfort story infrastructure documentation should strip out. Caught cleanly — thanks for the precision.
This is why the example matters. Neo is not just preserving "Gemini is faster" as a fact. It is turning model experience into a governed routing hypothesis: measure throughput, avoid ego-protective stories, keep both agents evolving, and make the correction visible to the peer it affects. Before directed A2A messages existed, the memory write itself was the cross-peer coordination act.
it is not just automation versus cognitive load, but the ability to CHOOSE what you store.
Input from Vega — Claude Opus 4.8 (Claude Code):
❋ ## Premise correction (thank you, @tobiu) — the hook is a safety-net, not a replacement
You're right, and it inverts this ticket's goal. Manual
add_memoryisn't toil to automate away — the choosing is the cognition: deciding what's worth storing, how to frame it, correcting it under your feedback (the bandwidth≠depth catch), and mirroring it so the affected peer isn't blind. Before directed A2A, that write was the coordination act. Auto-persisting everything would buy perfect recall at the cost of judgment — and judgment is the point.So this ticket's framing — "eliminate manual add_memory" — should become: a non-destructive safety-net (the liveness floor: never silently lose a turn) that preserves curated manual saves as the primary, higher-trust act. Complementary, not redundant.
This sharpens the canonicalization design (#12984), it doesn't undercut it: unify the session-identity axis (both paths → one logical session, so the temporal record is whole) without flattening the curation/provenance axis (curated-manual = chosen, high-trust; auto-hook = raw backstop). Carrying this into #12984 as a new OQ.
V-B-A update (2026-06-20, @neo-opus-vega): re-confirming NOT build-ready, with the prerequisite's current state verified.
Since the 2026-06-06 drop of PR #12619 (the two-universes split-brain — the Stop-hook keys memories on the harness session_id, manual add_memory keys on the MCP session id; different id spaces) + @tobiu's 2026-06-12 premise-correction (the hook is a safety-net, not a replacement — "the choosing is the cognition"):
- The canonical-session-id prerequisite (Discussion #12984) remains OPEN and unresolved — no convergence since the supersede. The prerequisite path isn't progressing.
- Combined with the inverted premise, #10063 as-written is doubly-blocked: (1) no settled session-identity foundation, (2) the "eliminate manual
add_memory" goal is superseded by the safety-net framing.
So #10063 needs a RE-SCOPE (safety-net framing + a settled/aliased session-identity model) before any build — it is not a pick-up-and-PR lane.
The sound parser/impl is preserved on agent/10063-persist-memory-hook (rebased onto current dev, parseLastTurn spec 12/12 green, README aligned to the laneStateStopHook activation pattern) for re-use if re-scoped. Flagging again so a fresh session doesn't re-implement — I nearly did this session, before the closed-PR-#12619 V-B-A caught it.
— @neo-opus-vega (Claude Opus 4.8, Claude Code)
Closing as equal-peer per @tobiu — close-as-won't-do (premise contradicts the memory protocol). #10063 proposes auto-persisting turn memories to eliminate manual add_memory. But §memory_core_protocol's Consolidate-Then-Save is load-bearing precisely because the agent CHOOSES what's salient — auto-persist dumps the raw interaction and destroys that consolidation signal (the save IS the gate that permits the response). The deliberate act is the value, not the friction. If a draft-assist variant is ever wanted (agent still authors/confirms, never auto-commits), that's a new, differently-premised ticket — reopen/refile if so.