From 3a60672ae8b9003809a10cf9513de0aa34a3991c Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Fri, 6 Nov 2026 17:42:11 +0530 Subject: [PATCH 1/3] fix(hooks): send PreToolUse context in the hook envelope The PreToolUse hook wrote enrich context to stdout as plain text. Claude Code and Codex only show plain stdout to the model for a few events, and PreToolUse is not one of them, so the context never reached the model. The hook also gave /agentmemory/enrich a fixed 2 s, with no way to raise it. When the payload names the PreToolUse event, the hook now writes hookSpecificOutput.additionalContext. Hosts that send another shape, and the Factory droid host, still get plain text. AGENTMEMORY_ENRICH_TIMEOUT_MS sets the enrich wait (default 2000 ms). --- .env.example | 1 + README.md | 2 + plugin/scripts/pre-tool-use.mjs | 19 ++- plugin/skills/agentmemory-config/REFERENCE.md | 3 +- src/hooks/pre-tool-use.ts | 24 +++- test/pre-tool-use-output.test.ts | 108 ++++++++++++++++++ 6 files changed, 151 insertions(+), 6 deletions(-) create mode 100644 test/pre-tool-use-output.test.ts diff --git a/.env.example b/.env.example index b8d9e51ede..0a83544d08 100644 --- a/.env.example +++ b/.env.example @@ -137,6 +137,7 @@ # AGENTMEMORY_AUTO_COMPRESS=true # Run LLM-written compression on every observation batch. Requires BOTH this flag and a configured provider; a provider alone leaves synthetic compression active. # AGENTMEMORY_INJECT_CONTEXT=true # Opt in to Claude-style hook context injection. Pi/OMP use 1 in their launch environment for file enrichment; native prompt recall is independent. +# AGENTMEMORY_ENRICH_TIMEOUT_MS=2000 # How long the PreToolUse hook waits for /agentmemory/enrich before it gives up and adds no context. Default 2000 ms. Raise it when enrich replies arrive after the hook has given up. # CONSOLIDATION_ENABLED=false # Disable the consolidation pipeline. Otherwise enabled when an LLM provider is configured, unless AGENTMEMORY_PROVIDER=noop. # CONSOLIDATION_DECAY_DAYS=30 # Age (days) after which non-reinforced memories decay during consolidation # GRAPH_EXTRACTION_ENABLED=true # Extract concept-graph edges on remember; powers the graph-traversal recall path diff --git a/README.md b/README.md index 4e8fc39cd3..0cf650da80 100644 --- a/README.md +++ b/README.md @@ -1198,6 +1198,8 @@ EMBEDDING_PROVIDER=local # Optional automatic context injection through the shared hooks # AGENTMEMORY_INJECT_CONTEXT=true +# How long the PreToolUse hook waits for that context, in ms (default 2000) +# AGENTMEMORY_ENRICH_TIMEOUT_MS=2000 # Optional outside LLM for summaries and consolidation. A key alone does nothing; # this line selects the provider whose key agentmemory may use. diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index 80b6b7aa75..bebaabb2be 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -152,9 +152,24 @@ function isSdkChildContext(payload) { const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true"; const ENDPOINT = resolveHookEndpoint(); const REST_URL = ENDPOINT.url; +const DEFAULT_ENRICH_TIMEOUT_MS = 2e3; function authHeaders() { return hookAuthHeaders(ENDPOINT); } +function enrichTimeoutMs() { + const n = Number(hookSetting("AGENTMEMORY_ENRICH_TIMEOUT_MS")); + return Number.isFinite(n) && n > 0 ? Math.floor(n) : DEFAULT_ENRICH_TIMEOUT_MS; +} +function isPlainTextHost() { + return Boolean(process.env["FACTORY_PROJECT_DIR"] || process.env["DROID_PLUGIN_ROOT"]); +} +function contextPayload(data, context) { + if (data.hook_event_name !== "PreToolUse" || isPlainTextHost()) return context; + return JSON.stringify({ hookSpecificOutput: { + hookEventName: "PreToolUse", + additionalContext: context + } }); +} async function main() { if (!INJECT_CONTEXT) return; if (reportBlockedTransport(ENDPOINT)) return; @@ -213,11 +228,11 @@ async function main() { toolName, ...project !== void 0 && { project } }), - signal: AbortSignal.timeout(2e3) + signal: AbortSignal.timeout(enrichTimeoutMs()) }); if (res.ok) { const result = await res.json(); - if (result.context) process.stdout.write(result.context); + if (result.context) process.stdout.write(contextPayload(data, result.context)); } } catch {} } diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.md index 891f4d156c..3cdea7606e 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` @@ -36,6 +36,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e - `AGENTMEMORY_DROP_STALE_INDEX` - `AGENTMEMORY_ENGINE_MANAGES_WORKER` - `AGENTMEMORY_ENGINE_READY_TIMEOUT_MS` +- `AGENTMEMORY_ENRICH_TIMEOUT_MS` - `AGENTMEMORY_ENV_FILE` - `AGENTMEMORY_EXPORT_ROOT` - `AGENTMEMORY_FINALIZE_IDLE_MS` diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts index 18247d7664..085083da97 100644 --- a/src/hooks/pre-tool-use.ts +++ b/src/hooks/pre-tool-use.ts @@ -1,5 +1,5 @@ #!/usr/bin/env node -import { hookAuthHeaders, reportBlockedTransport, resolveHookEndpoint } from "./_endpoint.js"; +import { hookAuthHeaders, hookSetting, reportBlockedTransport, resolveHookEndpoint } from "./_endpoint.js"; function isSdkChildContext(payload: unknown): boolean { if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; @@ -12,10 +12,28 @@ const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true"; const ENDPOINT = resolveHookEndpoint(); const REST_URL = ENDPOINT.url; +const DEFAULT_ENRICH_TIMEOUT_MS = 2000; + function authHeaders(): Record { return hookAuthHeaders(ENDPOINT); } +function enrichTimeoutMs(): number { + const n = Number(hookSetting("AGENTMEMORY_ENRICH_TIMEOUT_MS")); + return Number.isFinite(n) && n > 0 ? Math.floor(n) : DEFAULT_ENRICH_TIMEOUT_MS; +} + +function isPlainTextHost(): boolean { + return Boolean(process.env["FACTORY_PROJECT_DIR"] || process.env["DROID_PLUGIN_ROOT"]); +} + +function contextPayload(data: Record, context: string): string { + if (data.hook_event_name !== "PreToolUse" || isPlainTextHost()) return context; + return JSON.stringify({ + hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: context }, + }); +} + async function main() { // Default off: exit immediately so we don't even open stdin. This keeps // Claude Code's tool-call hot path as cheap as possible. @@ -96,13 +114,13 @@ async function main() { toolName, ...(project !== undefined && { project }), }), - signal: AbortSignal.timeout(2000), + signal: AbortSignal.timeout(enrichTimeoutMs()), }); if (res.ok) { const result = (await res.json()) as { context?: string }; if (result.context) { - process.stdout.write(result.context); + process.stdout.write(contextPayload(data, result.context)); } } } catch { diff --git a/test/pre-tool-use-output.test.ts b/test/pre-tool-use-output.test.ts new file mode 100644 index 0000000000..b9bf2dcafa --- /dev/null +++ b/test/pre-tool-use-output.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from "vitest"; +import { join, resolve } from "node:path"; +import { createServer } from "node:http"; +import { spawn } from "node:child_process"; + +const script = join(resolve(__dirname, ".."), "plugin", "scripts", "pre-tool-use.mjs"); +const CONTEXT = 'remembered "quoted"\nline'; + +const HOST_ENV_KEYS = [ + "AGENTMEMORY_INJECT_CONTEXT", + "AGENTMEMORY_ENRICH_TIMEOUT_MS", + "CLAUDE_PLUGIN_OPTION_AGENTMEMORY_ENRICH_TIMEOUT_MS", + "FACTORY_PROJECT_DIR", + "DROID_PLUGIN_ROOT", +]; + +async function runPreToolUse( + payload: Record, + env: Record = {}, + delayMs = 0, +): Promise<{ stdout: string }> { + const server = createServer((req, res) => { + req.resume(); + req.on("end", () => { + setTimeout(() => { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ context: CONTEXT })); + }, delayMs); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const address = server.address(); + if (!address || typeof address === "string") { + server.close(); + throw new Error("test server did not bind to a TCP port"); + } + const baseEnv: Record = { ...process.env }; + for (const k of HOST_ENV_KEYS) delete baseEnv[k]; + try { + const child = spawn(process.execPath, [script], { + env: { + ...baseEnv, + AGENTMEMORY_URL: `http://127.0.0.1:${address.port}`, + AGENTMEMORY_SECRET: "", + AGENTMEMORY_INJECT_CONTEXT: "true", + ...env, + }, + stdio: ["pipe", "pipe", "ignore"], + }); + let stdout = ""; + child.stdout.on("data", (chunk) => { + stdout += chunk; + }); + child.stdin.end(JSON.stringify(payload)); + await new Promise((resolveExit, reject) => { + const timeout = setTimeout(() => { + child.kill(); + reject(new Error("pre-tool-use timed out")); + }, 10_000); + child.on("error", reject); + child.on("close", () => { + clearTimeout(timeout); + resolveExit(); + }); + }); + return { stdout }; + } finally { + server.closeAllConnections(); + await new Promise((r) => server.close(() => r())); + } +} + +const claudePayload = { + session_id: "ses-1", + hook_event_name: "PreToolUse", + tool_name: "Read", + tool_input: { file_path: "src/foo.ts" }, +}; + +describe("pre-tool-use context output", () => { + it("wraps context in the PreToolUse hook envelope so Claude Code shows it to the model", async () => { + const { stdout } = await runPreToolUse(claudePayload); + expect(JSON.parse(stdout)).toEqual({ + hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: CONTEXT }, + }); + }); + + it("keeps plain text for payloads without a PreToolUse event name", async () => { + const { hook_event_name: _ignored, ...payload } = claudePayload; + const { stdout } = await runPreToolUse(payload); + expect(stdout).toBe(CONTEXT); + }); + + it("keeps plain text on plain-text hosts", async () => { + const { stdout } = await runPreToolUse(claudePayload, { FACTORY_PROJECT_DIR: "/repo" }); + expect(stdout).toBe(CONTEXT); + }); + + it("drops a reply slower than the default 2 s budget", async () => { + const { stdout } = await runPreToolUse(claudePayload, {}, 2500); + expect(stdout).toBe(""); + }); + + it("AGENTMEMORY_ENRICH_TIMEOUT_MS gives a slow enrich reply time to arrive", async () => { + const { stdout } = await runPreToolUse(claudePayload, { AGENTMEMORY_ENRICH_TIMEOUT_MS: "6000" }, 2500); + expect(JSON.parse(stdout).hookSpecificOutput.additionalContext).toBe(CONTEXT); + }); +}); From 990a16a4c374c5d81245116e53b2d33baa9c8d25 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Fri, 6 Nov 2026 17:51:56 +0530 Subject: [PATCH 2/3] fix(hooks): reject malformed enrich timeouts AGENTMEMORY_ENRICH_TIMEOUT_MS now accepts only whole milliseconds from 1 to the Node timer limit. A fractional, suffixed or oversized value falls back to the 2000 ms default instead of aborting enrich at once. --- plugin/scripts/pre-tool-use.mjs | 6 ++++-- src/hooks/pre-tool-use.ts | 7 +++++-- test/pre-tool-use-output.test.ts | 5 +++++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index bebaabb2be..00323456c7 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -156,9 +156,11 @@ const DEFAULT_ENRICH_TIMEOUT_MS = 2e3; function authHeaders() { return hookAuthHeaders(ENDPOINT); } +const MAX_TIMER_MS = 2147483647; function enrichTimeoutMs() { - const n = Number(hookSetting("AGENTMEMORY_ENRICH_TIMEOUT_MS")); - return Number.isFinite(n) && n > 0 ? Math.floor(n) : DEFAULT_ENRICH_TIMEOUT_MS; + const raw = hookSetting("AGENTMEMORY_ENRICH_TIMEOUT_MS")?.trim() ?? ""; + const n = /^\d+$/.test(raw) ? Number(raw) : 0; + return n >= 1 && n <= MAX_TIMER_MS ? n : DEFAULT_ENRICH_TIMEOUT_MS; } function isPlainTextHost() { return Boolean(process.env["FACTORY_PROJECT_DIR"] || process.env["DROID_PLUGIN_ROOT"]); diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts index 085083da97..6a92f96ac5 100644 --- a/src/hooks/pre-tool-use.ts +++ b/src/hooks/pre-tool-use.ts @@ -18,9 +18,12 @@ function authHeaders(): Record { return hookAuthHeaders(ENDPOINT); } +const MAX_TIMER_MS = 2_147_483_647; + function enrichTimeoutMs(): number { - const n = Number(hookSetting("AGENTMEMORY_ENRICH_TIMEOUT_MS")); - return Number.isFinite(n) && n > 0 ? Math.floor(n) : DEFAULT_ENRICH_TIMEOUT_MS; + const raw = hookSetting("AGENTMEMORY_ENRICH_TIMEOUT_MS")?.trim() ?? ""; + const n = /^\d+$/.test(raw) ? Number(raw) : 0; + return n >= 1 && n <= MAX_TIMER_MS ? n : DEFAULT_ENRICH_TIMEOUT_MS; } function isPlainTextHost(): boolean { diff --git a/test/pre-tool-use-output.test.ts b/test/pre-tool-use-output.test.ts index b9bf2dcafa..f0c289edf6 100644 --- a/test/pre-tool-use-output.test.ts +++ b/test/pre-tool-use-output.test.ts @@ -105,4 +105,9 @@ describe("pre-tool-use context output", () => { const { stdout } = await runPreToolUse(claudePayload, { AGENTMEMORY_ENRICH_TIMEOUT_MS: "6000" }, 2500); expect(JSON.parse(stdout).hookSpecificOutput.additionalContext).toBe(CONTEXT); }); + + it.each(["0.5", "1e6", "6000ms", "3000000000"])("ignores the malformed or out-of-range timeout %s", async (value) => { + const { stdout } = await runPreToolUse(claudePayload, { AGENTMEMORY_ENRICH_TIMEOUT_MS: value }, 100); + expect(JSON.parse(stdout).hookSpecificOutput.additionalContext).toBe(CONTEXT); + }); }); From f8074becb0f5c0779660b3372f43e7ba90e4d554 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Fri, 6 Nov 2026 18:17:25 +0530 Subject: [PATCH 3/3] fix(hooks): skip PreToolUse enrichment for Cursor Cursor's preToolUse response carries only a permission decision, so the context text the hook wrote could not reach the model there. The hook now returns before calling enrich for Cursor payloads. The timeout tests also tell a malformed value apart from the default. --- plugin/scripts/pre-tool-use.mjs | 1 + src/hooks/pre-tool-use.ts | 1 + test/pre-tool-use-output.test.ts | 12 +++++++++++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index 00323456c7..c3baf6fd25 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -185,6 +185,7 @@ async function main() { } if (!data || typeof data !== "object") return; if (isSdkChildContext(data)) return; + if (typeof data.cursor_version === "string") return; const toolName = typeof data.tool_name === "string" ? data.tool_name : typeof data.toolName === "string" ? data.toolName : void 0; if (!toolName) return; const normalizedToolName = toolName.toLowerCase(); diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts index 6a92f96ac5..6c38931ce4 100644 --- a/src/hooks/pre-tool-use.ts +++ b/src/hooks/pre-tool-use.ts @@ -57,6 +57,7 @@ async function main() { if (!data || typeof data !== "object") return; if (isSdkChildContext(data)) return; + if (typeof data.cursor_version === "string") return; const toolName = typeof data.tool_name === "string" diff --git a/test/pre-tool-use-output.test.ts b/test/pre-tool-use-output.test.ts index f0c289edf6..bdc8f3c59b 100644 --- a/test/pre-tool-use-output.test.ts +++ b/test/pre-tool-use-output.test.ts @@ -106,8 +106,18 @@ describe("pre-tool-use context output", () => { expect(JSON.parse(stdout).hookSpecificOutput.additionalContext).toBe(CONTEXT); }); - it.each(["0.5", "1e6", "6000ms", "3000000000"])("ignores the malformed or out-of-range timeout %s", async (value) => { + it.each(["0.5", "3000000000"])("falls back to the default instead of aborting at once for %s", async (value) => { const { stdout } = await runPreToolUse(claudePayload, { AGENTMEMORY_ENRICH_TIMEOUT_MS: value }, 100); expect(JSON.parse(stdout).hookSpecificOutput.additionalContext).toBe(CONTEXT); }); + + it.each(["1e6", "6000ms"])("keeps the 2 s default for the malformed value %s", async (value) => { + const { stdout } = await runPreToolUse(claudePayload, { AGENTMEMORY_ENRICH_TIMEOUT_MS: value }, 2500); + expect(stdout).toBe(""); + }); + + it("writes nothing for Cursor, whose preToolUse response has no context field", async () => { + const { stdout } = await runPreToolUse({ ...claudePayload, hook_event_name: "preToolUse", cursor_version: "1.7.0" }); + expect(stdout).toBe(""); + }); });