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/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjs index d64c0b2797..4792b18cfb 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,37 @@ 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 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(); let input = ""; @@ -122,6 +153,7 @@ async function main() { } if (!data || typeof data !== "object") return; if (isSdkChildContext(data)) 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/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..27632e1533 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,32 @@ function extractTranscriptPrompts(data: Record): TranscriptProm return prompts; } +const WORKER_ENV = "AGENTMEMORY_SESSION_END_WORKER"; + +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() { if (isDrainChild()) return runDrainChild(); let input = ""; @@ -107,6 +134,7 @@ async function main() { if (!data || typeof data !== "object") return; if (isSdkChildContext(data)) 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/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: { diff --git a/test/session-end-transcript.test.ts b/test/session-end-transcript.test.ts index c9f452e8b0..4ed260733a 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 }); + 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; + 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");