From eb04056f7babb2a57fdd2c273379b2569ec4052e Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Fri, 6 Nov 2026 17:34:42 +0530 Subject: [PATCH 1/3] fix(hooks): give the Claude Code SessionEnd hook time to finish Claude Code allows a SessionEnd hook 1.5 s unless the hook sets a timeout. The agentmemory SessionEnd hook back-fills transcript prompts with a 3 s client budget and then waits up to 1.5 s for the session end request, so Claude Code cancelled it and printed "Hook cancelled" on exit. The SessionEnd entry in the Claude Code hook manifest now sets a 10 s timeout. connect claude-code --with-hooks copies the field through. --- plugin/hooks/hooks.json | 3 ++- test/claude-code-with-hooks.test.ts | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/plugin/hooks/hooks.json b/plugin/hooks/hooks.json index 4c7aa13abf..345afd5f8e 100644 --- a/plugin/hooks/hooks.json +++ b/plugin/hooks/hooks.json @@ -128,7 +128,8 @@ { "type": "command", "command": "node", - "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/session-end.mjs"] + "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/session-end.mjs"], + "timeout": 10 } ] } diff --git a/test/claude-code-with-hooks.test.ts b/test/claude-code-with-hooks.test.ts index e3d35af552..4955131c1e 100644 --- a/test/claude-code-with-hooks.test.ts +++ b/test/claude-code-with-hooks.test.ts @@ -41,6 +41,13 @@ describe("buildMergedHooks against plugin/hooks/hooks.json (Claude Code)", () => ).toBe(true); }); + it("gives SessionEnd more time than Claude Code's 1.5 s default so the transcript back-fill and exit timer can finish", () => { + const merged = buildMergedHooks(null, PLUGIN_ROOT, "hooks.json"); + const handler = merged.hooks["SessionEnd"]![0]!.hooks[0]!; + expect(handler.args![0]).toContain("session-end.mjs"); + expect(handler.timeout).toBeGreaterThanOrEqual(10); + }); + it("appends to existing user hooks without dropping them", () => { const existing: HookManifest = { hooks: { From 261fa43fb1877f4865e75bfb6245d2f2a004a7df Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Fri, 6 Nov 2026 18:25:27 +0530 Subject: [PATCH 2/3] fix(hooks): finish SessionEnd work in a detached worker Claude Code does not let a plugin hook timeout raise its shared 1.5 s SessionEnd budget, so the timeout added to the manifest only helps hooks installed into settings. For a Claude Code SessionEnd payload the hook now passes its input to a detached copy of itself and exits at once. The worker back-fills transcript prompts and then ends the session, in the same order as before. Other hosts keep running inline. --- plugin/scripts/session-end.mjs | 29 +++++++++++- plugin/skills/agentmemory-config/REFERENCE.md | 3 +- src/hooks/session-end.ts | 23 ++++++++++ test/session-end-transcript.test.ts | 44 +++++++++++++++++-- 4 files changed, 94 insertions(+), 5 deletions(-) diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjs index d64c0b2797..85fe2f6318 100755 --- a/plugin/scripts/session-end.mjs +++ b/plugin/scripts/session-end.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node +import { execSync, spawn } from "node:child_process"; import { readFileSync, realpathSync } from "node:fs"; -import { execSync } from "node:child_process"; import { basename, dirname, resolve } from "node:path"; import { REST_URL, authHeaders, captureObservation, isDrainChild, runDrainChild, transportBlocked, withEventId } from "./_capture.mjs"; //#region src/hooks/_capture-filter.ts @@ -110,6 +110,32 @@ function extractTranscriptPrompts(data) { } return prompts; } +const WORKER_ENV = "AGENTMEMORY_SESSION_END_WORKER"; +function handOff(input) { + if (process.env[WORKER_ENV] === "1" || !process.argv[1]) return false; + try { + const child = spawn(process.execPath, [process.argv[1]], { + detached: true, + stdio: [ + "pipe", + "ignore", + "ignore" + ], + windowsHide: true, + env: { + ...process.env, + [WORKER_ENV]: "1" + } + }); + child.on("error", () => {}); + child.stdin.on("error", () => {}); + child.stdin.end(input); + child.unref(); + return true; + } catch { + return false; + } +} async function main() { if (isDrainChild()) return runDrainChild(); let input = ""; @@ -122,6 +148,7 @@ async function main() { } if (!data || typeof data !== "object") return; if (isSdkChildContext(data)) return; + if (data.hook_event_name === "SessionEnd" && handOff(input)) return; const sessionId = data.session_id || data.sessionId || data.conversation_id || "unknown"; const transcriptPrompts = extractTranscriptPrompts(data); if (transcriptPrompts.length > 0) { diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.md index 891f4d156c..996ab0a86d 100644 --- a/plugin/skills/agentmemory-config/REFERENCE.md +++ b/plugin/skills/agentmemory-config/REFERENCE.md @@ -3,7 +3,7 @@ Generated by scanning `src/` for `AGENTMEMORY_*` usage. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing a variable. Internal markers ending in two underscores are excluded. -Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 76 recognized variables: +Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 77 recognized variables: - `AGENTMEMORY_AGENT_SCOPE` - `AGENTMEMORY_ALLOW_AGENT_SDK` @@ -64,6 +64,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e - `AGENTMEMORY_RUNTIME_DIR` - `AGENTMEMORY_SDK_CHILD` - `AGENTMEMORY_SECRET` +- `AGENTMEMORY_SESSION_END_WORKER` - `AGENTMEMORY_SESSION_ID` - `AGENTMEMORY_SESSION_SWEEP_ENABLED` - `AGENTMEMORY_SESSION_SWEEP_STALE_HOURS` diff --git a/src/hooks/session-end.ts b/src/hooks/session-end.ts index d5e682f91e..ce001fdf02 100644 --- a/src/hooks/session-end.ts +++ b/src/hooks/session-end.ts @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { spawn } from "node:child_process"; import { readFileSync } from "node:fs"; import { truncateText } from "./_capture-filter.js"; import { resolveProject, hookCwd } from "./_project.js"; @@ -91,6 +92,27 @@ function extractTranscriptPrompts(data: Record): TranscriptProm return prompts; } +const WORKER_ENV = "AGENTMEMORY_SESSION_END_WORKER"; + +function handOff(input: string): boolean { + if (process.env[WORKER_ENV] === "1" || !process.argv[1]) return false; + try { + const child = spawn(process.execPath, [process.argv[1]], { + detached: true, + stdio: ["pipe", "ignore", "ignore"], + windowsHide: true, + env: { ...process.env, [WORKER_ENV]: "1" }, + }); + child.on("error", () => {}); + child.stdin.on("error", () => {}); + child.stdin.end(input); + child.unref(); + return true; + } catch { + return false; + } +} + async function main() { if (isDrainChild()) return runDrainChild(); let input = ""; @@ -107,6 +129,7 @@ async function main() { if (!data || typeof data !== "object") return; if (isSdkChildContext(data)) return; + if (data.hook_event_name === "SessionEnd" && handOff(input)) return; const sessionId = ((data.session_id || data.sessionId || data.conversation_id) as string) || "unknown"; diff --git a/test/session-end-transcript.test.ts b/test/session-end-transcript.test.ts index c9f452e8b0..e0d8cc0ec6 100644 --- a/test/session-end-transcript.test.ts +++ b/test/session-end-transcript.test.ts @@ -8,14 +8,16 @@ import { join } from "node:path"; let server: Server; let port: number; const posts: Array<{ path: string; body: Record }> = []; +let observeDelayMs = 0; function runHook( payload: Record, script = "plugin/scripts/session-end.mjs", + extraEnv: Record = {}, ): Promise { return new Promise((resolve) => { const child = spawn("node", [script], { - env: { ...process.env, AGENTMEMORY_URL: `http://127.0.0.1:${port}` }, + env: { ...process.env, AGENTMEMORY_URL: `http://127.0.0.1:${port}`, ...extraEnv }, }); child.on("exit", (code) => resolve(code ?? 1)); child.stdin.write(JSON.stringify(payload)); @@ -37,8 +39,10 @@ describe("session-end transcript prompt backfill", () => { } catch { posts.push({ path: req.url ?? "", body: {} }); } - res.writeHead(200, { "Content-Type": "application/json" }); - res.end("{}"); + setTimeout(() => { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end("{}"); + }, (req.url ?? "").includes("/observe") ? observeDelayMs : 0); }); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); @@ -107,6 +111,40 @@ describe("session-end transcript prompt backfill", () => { } }); + it("hands the work to a detached worker so the hook exits inside the 1.5 s SessionEnd budget", async () => { + posts.length = 0; + const transcript = join(dir, "handoff.jsonl"); + writeFileSync(transcript, JSON.stringify({ type: "user", message: { role: "user", content: "handoff prompt" } }) + "\n"); + observeDelayMs = 2500; + const started = Date.now(); + const code = await runHook({ session_id: "ses_handoff", hook_event_name: "SessionEnd", transcript_path: transcript }); + observeDelayMs = 0; + expect(code).toBe(0); + expect(Date.now() - started).toBeLessThan(1500); + const deadline = Date.now() + 10_000; + while (!posts.some((p) => p.path.includes("/session/end")) && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 50)); + } + const prompts = posts.filter((p) => p.path.includes("/observe")).map((p) => (p.body.data as { prompt: string }).prompt); + expect(prompts).toEqual(["handoff prompt"]); + const end = posts.find((p) => p.path.includes("/session/end")); + expect(end?.body).toMatchObject({ sessionId: "ses_handoff", final: true }); + }); + + it("runs the Claude Code SessionEnd work inline inside the detached worker", async () => { + posts.length = 0; + const transcript = join(dir, "worker.jsonl"); + writeFileSync(transcript, JSON.stringify({ type: "user", message: { role: "user", content: "worker prompt" } }) + "\n"); + const code = await runHook( + { session_id: "ses_worker", hook_event_name: "SessionEnd", transcript_path: transcript }, + undefined, + { AGENTMEMORY_SESSION_END_WORKER: "1" }, + ); + expect(code).toBe(0); + expect(posts.filter((p) => p.path.includes("/observe")).map((p) => (p.body.data as { prompt: string }).prompt)).toEqual(["worker prompt"]); + expect(posts.some((p) => p.path.includes("/session/end"))).toBe(true); + }); + it("posts prompts from a Claude Code transcript, skipping tool results", async () => { posts.length = 0; const transcript = join(dir, "t-cc.jsonl"); From 4e900e6f0c3cb129bd1ec5e16c4303d91f80fd83 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Fri, 6 Nov 2026 18:49:27 +0530 Subject: [PATCH 3/3] fix(hooks): run SessionEnd inline when the worker cannot start Node reports a failed spawn through an asynchronous error event, so the hand-off could report success for a worker that never started and the session would not be ended. The hook now waits for the worker to spawn and receive its input, and runs inline when either step fails. The hand-off test also keeps the slow observe reply until the worker posts. --- plugin/scripts/session-end.mjs | 53 ++++++++++++++++------------- src/hooks/session-end.ts | 41 ++++++++++++---------- test/session-end-transcript.test.ts | 4 +-- 3 files changed, 54 insertions(+), 44 deletions(-) diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjs index 85fe2f6318..4792b18cfb 100755 --- a/plugin/scripts/session-end.mjs +++ b/plugin/scripts/session-end.mjs @@ -112,29 +112,34 @@ function extractTranscriptPrompts(data) { } const WORKER_ENV = "AGENTMEMORY_SESSION_END_WORKER"; function handOff(input) { - if (process.env[WORKER_ENV] === "1" || !process.argv[1]) return false; - try { - const child = spawn(process.execPath, [process.argv[1]], { - detached: true, - stdio: [ - "pipe", - "ignore", - "ignore" - ], - windowsHide: true, - env: { - ...process.env, - [WORKER_ENV]: "1" - } - }); - child.on("error", () => {}); - child.stdin.on("error", () => {}); - child.stdin.end(input); - child.unref(); - return true; - } catch { - return false; - } + if (process.env[WORKER_ENV] === "1" || !process.argv[1]) return Promise.resolve(false); + return new Promise((resolve) => { + try { + const child = spawn(process.execPath, [process.argv[1]], { + detached: true, + stdio: [ + "pipe", + "ignore", + "ignore" + ], + windowsHide: true, + env: { + ...process.env, + [WORKER_ENV]: "1" + } + }); + child.on("error", () => resolve(false)); + child.stdin.on("error", () => resolve(false)); + child.once("spawn", () => { + child.stdin.end(input, () => { + child.unref(); + resolve(true); + }); + }); + } catch { + resolve(false); + } + }); } async function main() { if (isDrainChild()) return runDrainChild(); @@ -148,7 +153,7 @@ async function main() { } if (!data || typeof data !== "object") return; if (isSdkChildContext(data)) return; - if (data.hook_event_name === "SessionEnd" && handOff(input)) return; + if (data.hook_event_name === "SessionEnd" && await handOff(input)) return; const sessionId = data.session_id || data.sessionId || data.conversation_id || "unknown"; const transcriptPrompts = extractTranscriptPrompts(data); if (transcriptPrompts.length > 0) { diff --git a/src/hooks/session-end.ts b/src/hooks/session-end.ts index ce001fdf02..27632e1533 100644 --- a/src/hooks/session-end.ts +++ b/src/hooks/session-end.ts @@ -94,23 +94,28 @@ function extractTranscriptPrompts(data: Record): TranscriptProm const WORKER_ENV = "AGENTMEMORY_SESSION_END_WORKER"; -function handOff(input: string): boolean { - if (process.env[WORKER_ENV] === "1" || !process.argv[1]) return false; - try { - const child = spawn(process.execPath, [process.argv[1]], { - detached: true, - stdio: ["pipe", "ignore", "ignore"], - windowsHide: true, - env: { ...process.env, [WORKER_ENV]: "1" }, - }); - child.on("error", () => {}); - child.stdin.on("error", () => {}); - child.stdin.end(input); - child.unref(); - return true; - } catch { - return false; - } +function handOff(input: string): Promise { + if (process.env[WORKER_ENV] === "1" || !process.argv[1]) return Promise.resolve(false); + return new Promise((resolve) => { + try { + const child = spawn(process.execPath, [process.argv[1]], { + detached: true, + stdio: ["pipe", "ignore", "ignore"], + windowsHide: true, + env: { ...process.env, [WORKER_ENV]: "1" }, + }); + child.on("error", () => resolve(false)); + child.stdin.on("error", () => resolve(false)); + child.once("spawn", () => { + child.stdin.end(input, () => { + child.unref(); + resolve(true); + }); + }); + } catch { + resolve(false); + } + }); } async function main() { @@ -129,7 +134,7 @@ async function main() { if (!data || typeof data !== "object") return; if (isSdkChildContext(data)) return; - if (data.hook_event_name === "SessionEnd" && handOff(input)) return; + if (data.hook_event_name === "SessionEnd" && (await handOff(input))) return; const sessionId = ((data.session_id || data.sessionId || data.conversation_id) as string) || "unknown"; diff --git a/test/session-end-transcript.test.ts b/test/session-end-transcript.test.ts index e0d8cc0ec6..4ed260733a 100644 --- a/test/session-end-transcript.test.ts +++ b/test/session-end-transcript.test.ts @@ -118,18 +118,18 @@ describe("session-end transcript prompt backfill", () => { observeDelayMs = 2500; const started = Date.now(); const code = await runHook({ session_id: "ses_handoff", hook_event_name: "SessionEnd", transcript_path: transcript }); - observeDelayMs = 0; expect(code).toBe(0); expect(Date.now() - started).toBeLessThan(1500); const deadline = Date.now() + 10_000; while (!posts.some((p) => p.path.includes("/session/end")) && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 50)); } + observeDelayMs = 0; const prompts = posts.filter((p) => p.path.includes("/observe")).map((p) => (p.body.data as { prompt: string }).prompt); expect(prompts).toEqual(["handoff prompt"]); const end = posts.find((p) => p.path.includes("/session/end")); expect(end?.body).toMatchObject({ sessionId: "ses_handoff", final: true }); - }); + }, 20_000); it("runs the Claude Code SessionEnd work inline inside the detached worker", async () => { posts.length = 0;