#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix(hooks): skip agentmemory's own tools and make capture configurable (carries #994) (#1452)
Rohit Ghumaree950d5838daf
diff --git a/.env.example b/.env.exampleindex b43aeca8..607e326f 100644--- a/.env.example+++ b/.env.example@@ -25,6 +25,10 @@# but LLM-backed summarisation / reflection / consolidation are disabled.# A provider key alone does not enable LLM-written observation compression;# that path also requires AGENTMEMORY_AUTO_COMPRESS=true.+# AGENTMEMORY_CAPTURE_ALLOW= # Comma/space list of tool names or globs to capture; when set, only these are captured+# AGENTMEMORY_CAPTURE_DENY= # Extra tool names or globs to skip, added to the defaults (memory_*, toolsearch, listmcpresources, fetchmcpresource)+# AGENTMEMORY_CAPTURE_OUTPUT_MAX=8000 # Max characters of tool output stored per captured observation+# AGENTMEMORY_PRE_COMPACT_BUDGET=1500 # Token budget for context injected by the PreCompact hook; 0 disables it# The detection order is OPENAI_API_KEY → MINIMAX_API_KEY → ANTHROPIC_API_KEY# → GEMINI_API_KEY → OPENROUTER_API_KEY → noop.diff --git a/plugin/scripts/post-tool-failure.mjs b/plugin/scripts/post-tool-failure.mjsindex 0af94e7c..a33f5c1b 100755--- a/plugin/scripts/post-tool-failure.mjs+++ b/plugin/scripts/post-tool-failure.mjs@@ -1,6 +1,47 @@#!/usr/bin/env nodeimport { execSync } from "node:child_process";import { basename } from "node:path";+//#region src/hooks/_capture-filter.ts+const DEFAULT_DENY_PATTERNS = [+ "memory_*",+ "toolsearch",+ "listmcpresources",+ "fetchmcpresource"+];+function parseEnvList(raw) {+ if (!raw?.trim()) return void 0;+ return raw.split(/[,\s]+/).map((part) => part.trim()).filter(Boolean);+}+function bareToolName(toolName) {+ const trimmed = toolName.trim();+ if (/^mcp__/i.test(trimmed)) {+ const parts = trimmed.split("__");+ if (parts.length >= 3) return parts[parts.length - 1];+ }+ return trimmed;+}+function normalizePattern(pattern) {+ return pattern.trim().toLowerCase();+}+function matchesPattern(toolName, pattern) {+ const bare = bareToolName(toolName).toLowerCase();+ const full = toolName.trim().toLowerCase();+ const pat = normalizePattern(pattern);+ if (!pat.includes("*")) return bare === pat || full === pat;+ const escaped = pat.replace(/[.+?^${}()|[\]\\]/g, "\\$&");+ const re = new RegExp(`^${escaped.replace(/\*/g, ".*")}$`);+ return re.test(bare) || re.test(full);+}+function matchesAny(toolName, patterns) {+ return patterns.some((pattern) => matchesPattern(toolName, pattern));+}+function shouldCaptureTool(toolName) {+ if (typeof toolName !== "string" || !toolName.trim()) return true;+ const allow = parseEnvList(process.env["AGENTMEMORY_CAPTURE_ALLOW"]);+ if (allow) return matchesAny(toolName, allow);+ return !matchesAny(toolName, [...DEFAULT_DENY_PATTERNS, ...parseEnvList(process.env["AGENTMEMORY_CAPTURE_DENY"]) ?? []]);+}+//#endregion//#region src/hooks/_project.tsfunction resolveProject(cwd) {const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];@@ -58,6 +99,7 @@ async function main() {if (data.is_interrupt || data.isInterrupt) return;const sessionId = data.session_id || data.sessionId || data.conversation_id || "unknown";const toolName = data.tool_name ?? data.toolName;+ if (!shouldCaptureTool(toolName)) return;const toolInput = data.tool_input ?? data.toolArgs;const error = data.error ?? data.errorMessage;const cwd = hookCwd(data) || process.cwd();diff --git a/plugin/scripts/post-tool-use.mjs b/plugin/scripts/post-tool-use.mjsindex 1189e35f..8345354c 100755--- a/plugin/scripts/post-tool-use.mjs+++ b/plugin/scripts/post-tool-use.mjs@@ -1,6 +1,68 @@#!/usr/bin/env nodeimport { execSync } from "node:child_process";import { basename } from "node:path";+//#region src/hooks/_capture-filter.ts+const DEFAULT_DENY_PATTERNS = [+ "memory_*",+ "toolsearch",+ "listmcpresources",+ "fetchmcpresource"+];+function parseEnvList(raw) {+ if (!raw?.trim()) return void 0;+ return raw.split(/[,\s]+/).map((part) => part.trim()).filter(Boolean);+}+function bareToolName(toolName) {+ const trimmed = toolName.trim();+ if (/^mcp__/i.test(trimmed)) {+ const parts = trimmed.split("__");+ if (parts.length >= 3) return parts[parts.length - 1];+ }+ return trimmed;+}+function normalizePattern(pattern) {+ return pattern.trim().toLowerCase();+}+function matchesPattern(toolName, pattern) {+ const bare = bareToolName(toolName).toLowerCase();+ const full = toolName.trim().toLowerCase();+ const pat = normalizePattern(pattern);+ if (!pat.includes("*")) return bare === pat || full === pat;+ const escaped = pat.replace(/[.+?^${}()|[\]\\]/g, "\\$&");+ const re = new RegExp(`^${escaped.replace(/\*/g, ".*")}$`);+ return re.test(bare) || re.test(full);+}+function matchesAny(toolName, patterns) {+ return patterns.some((pattern) => matchesPattern(toolName, pattern));+}+function shouldCaptureTool(toolName) {+ if (typeof toolName !== "string" || !toolName.trim()) return true;+ const allow = parseEnvList(process.env["AGENTMEMORY_CAPTURE_ALLOW"]);+ if (allow) return matchesAny(toolName, allow);+ return !matchesAny(toolName, [...DEFAULT_DENY_PATTERNS, ...parseEnvList(process.env["AGENTMEMORY_CAPTURE_DENY"]) ?? []]);+}+function captureOutputMax() {+ const raw = process.env["AGENTMEMORY_CAPTURE_OUTPUT_MAX"];+ if (!raw?.trim()) return 8e3;+ const parsed = Number.parseInt(raw, 10);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 8e3;+}+function truncateCaptureOutput(value, max) {+ if (typeof value === "string" && value.length > max) {+ const suffix = "\n[...truncated]";+ return max <= 15 ? suffix.slice(0, max) : value.slice(0, max - 15) + suffix;+ }+ if (typeof value === "object" && value !== null) {+ const str = JSON.stringify(value);+ if (str.length > max) {+ const suffix = "...[truncated]";+ return max <= 14 ? suffix.slice(0, max) : str.slice(0, max - 14) + suffix;+ }+ return value;+ }+ return value;+}+//#endregion//#region src/hooks/_project.tsfunction resolveProject(cwd) {const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];@@ -57,9 +119,11 @@ async function main() {if (isSdkChildContext(data)) return;const sessionId = data.session_id || data.sessionId || data.conversation_id || "unknown";const toolName = data.tool_name ?? data.toolName;+ if (!shouldCaptureTool(toolName)) return;const toolInput = data.tool_input ?? data.toolArgs;const { imageData, cleanOutput } = extractImageData(toolOutput(data));const cwd = hookCwd(data) || process.cwd();+ const outputMax = captureOutputMax();fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",headers: authHeaders(),@@ -72,7 +136,7 @@ async function main() {data: {tool_name: toolName,tool_input: toolInput,- tool_output: truncate(cleanOutput, 8e3),+ tool_output: truncateCaptureOutput(cleanOutput, outputMax),...imageData ? { image_data: imageData } : {}}}),@@ -116,15 +180,6 @@ function extractImageData(output) {cleanOutput: output};}-function truncate(value, max) {- if (typeof value === "string" && value.length > max) return value.slice(0, max) + "\n[...truncated]";- if (typeof value === "object" && value !== null) {- const str = JSON.stringify(value);- if (str.length > max) return str.slice(0, max) + "...[truncated]";- return value;- }- return value;-}main().catch(() => process.exit(0));//#endregionexport {};diff --git a/plugin/scripts/pre-compact.mjs b/plugin/scripts/pre-compact.mjsindex 75309435..4af77810 100755--- a/plugin/scripts/pre-compact.mjs+++ b/plugin/scripts/pre-compact.mjs@@ -1,6 +1,15 @@#!/usr/bin/env nodeimport { execSync } from "node:child_process";import { basename } from "node:path";+//#region src/hooks/_capture-filter.ts+function preCompactBudget() {+ const raw = process.env["AGENTMEMORY_PRE_COMPACT_BUDGET"];+ if (raw?.trim() === "0") return 0;+ if (!raw?.trim()) return 1500;+ const parsed = Number.parseInt(raw, 10);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 1500;+}+//#endregion//#region src/hooks/_project.tsfunction resolveProject(cwd) {const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];@@ -65,6 +74,8 @@ async function main() {signal: AbortSignal.timeout(5e3)});} catch {}+ const budget = preCompactBudget();+ if (budget === 0) return;try {const res = await fetch(`${REST_URL}/agentmemory/context`, {method: "POST",@@ -72,7 +83,7 @@ async function main() {body: JSON.stringify({sessionId,project,- budget: 1500+ budget}),signal: AbortSignal.timeout(5e3)});diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.mdindex c7fc1d89..158b1f1e 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.<!-- AUTOGEN:env START - generated by scripts/skills/generate.ts, do not edit by hand -->-Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 54 recognized variables:+Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 58 recognized variables:- `AGENTMEMORY_AGENT_SCOPE`- `AGENTMEMORY_ALLOW_AGENT_SDK`@@ -11,6 +11,9 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e- `AGENTMEMORY_AUDIT_MIGRATE_MAX_BYTES`- `AGENTMEMORY_AUDIT_RETENTION_MONTHS`- `AGENTMEMORY_AUTO_COMPRESS`+- `AGENTMEMORY_CAPTURE_ALLOW`+- `AGENTMEMORY_CAPTURE_DENY`+- `AGENTMEMORY_CAPTURE_OUTPUT_MAX`- `AGENTMEMORY_COMMIT_SHA`- `AGENTMEMORY_CONSOLIDATION_COOLDOWN_MS`- `AGENTMEMORY_COPILOT_MCP_BLOCK`@@ -35,6 +38,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e- `AGENTMEMORY_LLM_TIMEOUT_MS`- `AGENTMEMORY_MCP_BLOCK`- `AGENTMEMORY_METRICS_PORT`+- `AGENTMEMORY_PRE_COMPACT_BUDGET`- `AGENTMEMORY_PROBE_TIMEOUT_MS`- `AGENTMEMORY_PROJECT_NAME`- `AGENTMEMORY_PROVIDER`diff --git a/src/hooks/_capture-filter.ts b/src/hooks/_capture-filter.tsnew file mode 100644index 00000000..4c57a709--- /dev/null+++ b/src/hooks/_capture-filter.ts@@ -0,0 +1,89 @@+const DEFAULT_DENY_PATTERNS = [+ "memory_*",+ "toolsearch",+ "listmcpresources",+ "fetchmcpresource",+];++function parseEnvList(raw: string | undefined): string[] | undefined {+ if (!raw?.trim()) return undefined;+ return raw+ .split(/[,\s]+/)+ .map((part) => part.trim())+ .filter(Boolean);+}++export function bareToolName(toolName: string): string {+ const trimmed = toolName.trim();+ if (/^mcp__/i.test(trimmed)) {+ const parts = trimmed.split("__");+ if (parts.length >= 3) return parts[parts.length - 1]!;+ }+ return trimmed;+}++function normalizePattern(pattern: string): string {+ return pattern.trim().toLowerCase();+}++function matchesPattern(toolName: string, pattern: string): boolean {+ const bare = bareToolName(toolName).toLowerCase();+ const full = toolName.trim().toLowerCase();+ const pat = normalizePattern(pattern);+ if (!pat.includes("*")) return bare === pat || full === pat;+ const escaped = pat.replace(/[.+?^${}()|[\]\\]/g, "\\$&");+ const re = new RegExp(`^${escaped.replace(/\*/g, ".*")}$`);+ return re.test(bare) || re.test(full);+}++function matchesAny(toolName: string, patterns: string[]): boolean {+ return patterns.some((pattern) => matchesPattern(toolName, pattern));+}++export function shouldCaptureTool(toolName: unknown): boolean {+ if (typeof toolName !== "string" || !toolName.trim()) return true;++ const allow = parseEnvList(process.env["AGENTMEMORY_CAPTURE_ALLOW"]);+ if (allow) return matchesAny(toolName, allow);++ const deny = [+ ...DEFAULT_DENY_PATTERNS,+ ...(parseEnvList(process.env["AGENTMEMORY_CAPTURE_DENY"]) ?? []),+ ];+ return !matchesAny(toolName, deny);+}++export function captureOutputMax(): number {+ const raw = process.env["AGENTMEMORY_CAPTURE_OUTPUT_MAX"];+ if (!raw?.trim()) return 8000;+ const parsed = Number.parseInt(raw, 10);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 8000;+}++export function truncateCaptureOutput(value: unknown, max: number): unknown {+ if (typeof value === "string" && value.length > max) {+ const suffix = "\n[...truncated]";+ return max <= suffix.length+ ? suffix.slice(0, max)+ : value.slice(0, max - suffix.length) + suffix;+ }+ if (typeof value === "object" && value !== null) {+ const str = JSON.stringify(value);+ if (str.length > max) {+ const suffix = "...[truncated]";+ return max <= suffix.length+ ? suffix.slice(0, max)+ : str.slice(0, max - suffix.length) + suffix;+ }+ return value;+ }+ return value;+}++export function preCompactBudget(): number {+ const raw = process.env["AGENTMEMORY_PRE_COMPACT_BUDGET"];+ if (raw?.trim() === "0") return 0;+ if (!raw?.trim()) return 1500;+ const parsed = Number.parseInt(raw, 10);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 1500;+}diff --git a/src/hooks/post-tool-failure.ts b/src/hooks/post-tool-failure.tsindex 69ec145d..427e32cd 100644--- a/src/hooks/post-tool-failure.ts+++ b/src/hooks/post-tool-failure.ts@@ -1,4 +1,5 @@#!/usr/bin/env node+import { shouldCaptureTool } from "./_capture-filter.js";import { resolveProject, hookCwd } from "./_project.js";function isSdkChildContext(payload: unknown): boolean {@@ -35,6 +36,8 @@ async function main() {const sessionId = ((data.session_id || data.sessionId || data.conversation_id) as string) || "unknown";const toolName = data.tool_name ?? data.toolName;+ if (!shouldCaptureTool(toolName)) return;+const toolInput = data.tool_input ?? data.toolArgs;const error = data.error ?? data.errorMessage;diff --git a/src/hooks/post-tool-use.ts b/src/hooks/post-tool-use.tsindex e8fe3483..05aed993 100644--- a/src/hooks/post-tool-use.ts+++ b/src/hooks/post-tool-use.ts@@ -1,4 +1,9 @@#!/usr/bin/env node+import {+ captureOutputMax,+ shouldCaptureTool,+ truncateCaptureOutput,+} from "./_capture-filter.js";import { resolveProject, hookCwd } from "./_project.js";function isSdkChildContext(payload: unknown): boolean {@@ -34,10 +39,13 @@ async function main() {const sessionId = ((data.session_id || data.sessionId || data.conversation_id) as string) || "unknown";const toolName = data.tool_name ?? data.toolName;+ if (!shouldCaptureTool(toolName)) return;+const toolInput = data.tool_input ?? data.toolArgs;const { imageData, cleanOutput } = extractImageData(toolOutput(data));const cwd = hookCwd(data) || process.cwd();+ const outputMax = captureOutputMax();fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",@@ -51,7 +59,7 @@ async function main() {data: {tool_name: toolName,tool_input: toolInput,- tool_output: truncate(cleanOutput, 8000),+ tool_output: truncateCaptureOutput(cleanOutput, outputMax),...(imageData ? { image_data: imageData } : {}),},}),@@ -104,16 +112,4 @@ function extractImageData(output: unknown): { imageData: string | undefined; clereturn { imageData: undefined, cleanOutput: output };}-function truncate(value: unknown, max: number): unknown {- if (typeof value === "string" && value.length > max) {- return value.slice(0, max) + "\n[...truncated]";- }- if (typeof value === "object" && value !== null) {- const str = JSON.stringify(value);- if (str.length > max) return str.slice(0, max) + "...[truncated]";- return value;- }- return value;-}-main().catch(() => process.exit(0));diff --git a/src/hooks/pre-compact.ts b/src/hooks/pre-compact.tsindex 71d7c5cb..07a8b9f8 100644--- a/src/hooks/pre-compact.ts+++ b/src/hooks/pre-compact.ts@@ -1,4 +1,5 @@#!/usr/bin/env node+import { preCompactBudget } from "./_capture-filter.js";import { resolveProject, hookCwd } from "./_project.js";function isSdkChildContext(payload: unknown): boolean {@@ -48,11 +49,14 @@ async function main() {}}+ const budget = preCompactBudget();+ if (budget === 0) return;+try {const res = await fetch(`${REST_URL}/agentmemory/context`, {method: "POST",headers: authHeaders(),- body: JSON.stringify({ sessionId, project, budget: 1500 }),+ body: JSON.stringify({ sessionId, project, budget }),signal: AbortSignal.timeout(5000),});diff --git a/test/capture-filter.test.ts b/test/capture-filter.test.tsnew file mode 100644index 00000000..6767c1a0--- /dev/null+++ b/test/capture-filter.test.ts@@ -0,0 +1,148 @@+import { describe, it, expect, beforeEach, afterEach } from "vitest";+import {+ bareToolName,+ captureOutputMax,+ preCompactBudget,+ shouldCaptureTool,+ truncateCaptureOutput,+} from "../src/hooks/_capture-filter.js";++describe("bareToolName", () => {+ it("returns plain tool names unchanged", () => {+ expect(bareToolName("Bash")).toBe("Bash");+ expect(bareToolName("memory_recall")).toBe("memory_recall");+ });++ it("strips Claude Code MCP prefixes", () => {+ expect(bareToolName("mcp__agentmemory__memory_smart_search")).toBe(+ "memory_smart_search",+ );+ });+});++describe("shouldCaptureTool (#993)", () => {+ const envKeys = [+ "AGENTMEMORY_CAPTURE_ALLOW",+ "AGENTMEMORY_CAPTURE_DENY",+ ] as const;+ const original: Record<string, string | undefined> = {};++ beforeEach(() => {+ for (const key of envKeys) {+ original[key] = process.env[key];+ delete process.env[key];+ }+ });++ afterEach(() => {+ for (const key of envKeys) {+ if (original[key] === undefined) delete process.env[key];+ else process.env[key] = original[key];+ }+ });++ it("captures normal agent tools by default", () => {+ expect(shouldCaptureTool("Bash")).toBe(true);+ expect(shouldCaptureTool("Edit")).toBe(true);+ expect(shouldCaptureTool("Agent")).toBe(true);+ });++ it("skips agentmemory memory_* MCP tools by default", () => {+ expect(shouldCaptureTool("memory_recall")).toBe(false);+ expect(shouldCaptureTool("memory_smart_search")).toBe(false);+ expect(shouldCaptureTool("mcp__agentmemory__memory_recall")).toBe(false);+ });++ it("skips plumbing tools by default", () => {+ expect(shouldCaptureTool("ToolSearch")).toBe(false);+ expect(shouldCaptureTool("ListMcpResources")).toBe(false);+ });++ it("honors AGENTMEMORY_CAPTURE_DENY", () => {+ process.env.AGENTMEMORY_CAPTURE_DENY = "Grep, Glob";+ expect(shouldCaptureTool("Grep")).toBe(false);+ expect(shouldCaptureTool("Bash")).toBe(true);+ });++ it("matches an exact pattern against the full MCP tool name", () => {+ process.env.AGENTMEMORY_CAPTURE_DENY = "mcp__github__create_issue";+ expect(shouldCaptureTool("mcp__github__create_issue")).toBe(false);+ expect(shouldCaptureTool("mcp__gitlab__create_issue")).toBe(true);+ process.env.AGENTMEMORY_CAPTURE_DENY = "create_issue";+ expect(shouldCaptureTool("mcp__gitlab__create_issue")).toBe(false);+ });++ it("honors AGENTMEMORY_CAPTURE_ALLOW over defaults", () => {+ process.env.AGENTMEMORY_CAPTURE_ALLOW = "memory_recall, Bash";+ expect(shouldCaptureTool("memory_recall")).toBe(true);+ expect(shouldCaptureTool("memory_smart_search")).toBe(false);+ expect(shouldCaptureTool("Bash")).toBe(true);+ expect(shouldCaptureTool("Edit")).toBe(false);+ });+});++describe("captureOutputMax", () => {+ const key = "AGENTMEMORY_CAPTURE_OUTPUT_MAX";+ const original = process.env[key];++ afterEach(() => {+ if (original === undefined) delete process.env[key];+ else process.env[key] = original;+ });++ it("defaults to 8000", () => {+ delete process.env[key];+ expect(captureOutputMax()).toBe(8000);+ });++ it("reads a positive override", () => {+ process.env[key] = "4096";+ expect(captureOutputMax()).toBe(4096);+ });+});++describe("truncateCaptureOutput", () => {+ it("leaves short strings alone", () => {+ expect(truncateCaptureOutput("hello", 20)).toBe("hello");+ });++ it("keeps truncated string length within max", () => {+ const out = truncateCaptureOutput("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 20);+ expect(typeof out).toBe("string");+ expect((out as string).length).toBe(20);+ expect(out).toBe("ABCDE\n[...truncated]");+ });++ it("handles max smaller than the marker", () => {+ expect(truncateCaptureOutput("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 5)).toBe(+ "\n[...",+ );+ });++ it("keeps truncated JSON length within max", () => {+ const out = truncateCaptureOutput({ a: "x".repeat(50) }, 30);+ expect(typeof out).toBe("string");+ expect((out as string).length).toBe(30);+ expect(out).toMatch(/\.\.\.\[truncated\]$/);+ });+});++describe("preCompactBudget", () => {+ const key = "AGENTMEMORY_PRE_COMPACT_BUDGET";+ const original = process.env[key];++ afterEach(() => {+ if (original === undefined) delete process.env[key];+ else process.env[key] = original;+ });++ it("defaults to 1500", () => {+ delete process.env[key];+ expect(preCompactBudget()).toBe(1500);+ });++ it("allows disabling injection with 0", () => {+ process.env[key] = "0";+ expect(preCompactBudget()).toBe(0);+ });+});diff --git a/test/post-tool-use-capture.test.ts b/test/post-tool-use-capture.test.tsnew file mode 100644index 00000000..a4e48302--- /dev/null+++ b/test/post-tool-use-capture.test.ts@@ -0,0 +1,119 @@+import { describe, it, expect, afterEach } from "vitest";+import { spawn } from "node:child_process";+import { createServer, type Server } from "node:http";+import { join } from "node:path";++const HOOKS_DIR = join(import.meta.dirname, "..", "plugin", "scripts");++function runHook(+ scriptName: string,+ stdin: string,+ env: Record<string, string>,+): Promise<{ exitCode: number | null }> {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [join(HOOKS_DIR, scriptName)], {+ env: {+ PATH: process.env["PATH"] ?? "",+ ...env,+ },+ stdio: ["pipe", "ignore", "ignore"],+ });+ child.on("error", reject);+ child.on("close", (exitCode) => resolve({ exitCode }));+ child.stdin.write(stdin);+ child.stdin.end();+ });+}++describe("post-tool-use hook — capture filter (#993)", () => {+ let server: Server;+ let observeCalls = 0;+ let port = 0;+ let onObserve: (() => void) | undefined;++ afterEach(async () => {+ observeCalls = 0;+ onObserve = undefined;+ if (server) {+ await new Promise<void>((resolve, reject) => {+ server.close((err) => (err ? reject(err) : resolve()));+ });+ }+ });++ async function assertNoObserveAfterHook(+ hook: Promise<{ exitCode: number | null }>,+ { settleMs = 300 } = {},+ ): Promise<{ exitCode: number | null }> {+ const result = await hook;+ const deadline = Date.now() + settleMs;+ while (Date.now() < deadline) {+ if (observeCalls !== 0) {+ throw new Error(`unexpected observe call(s): ${observeCalls}`);+ }+ await new Promise((r) => setTimeout(r, 25));+ }+ return result;+ }++ async function startServer() {+ server = createServer((req, res) => {+ if (req.method === "POST" && req.url === "/agentmemory/observe") {+ observeCalls += 1;+ onObserve?.();+ }+ res.writeHead(200, { "Content-Type": "application/json" });+ res.end("{}");+ });+ await new Promise<void>((resolve) => {+ server.listen(0, "127.0.0.1", () => {+ const addr = server.address();+ if (addr && typeof addr === "object") port = addr.port;+ resolve();+ });+ });+ }++ it("does not observe memory_* MCP tools", async () => {+ await startServer();+ const payload = JSON.stringify({+ session_id: "ses_test",+ tool_name: "mcp__agentmemory__memory_smart_search",+ tool_input: { query: "hooks" },+ tool_output: "results",+ });+ const result = await assertNoObserveAfterHook(+ runHook("post-tool-use.mjs", payload, {+ AGENTMEMORY_URL: `http://127.0.0.1:${port}`,+ }),+ );+ expect(result.exitCode).toBe(0);+ expect(observeCalls).toBe(0);+ });++ it("still observes normal tools", async () => {+ await startServer();+ const payload = JSON.stringify({+ session_id: "ses_test",+ tool_name: "Bash",+ tool_input: { command: "ls" },+ tool_output: "ok",+ });+ const observeSeen = new Promise<void>((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error("observe request never arrived")),+ 2000,+ );+ onObserve = () => {+ clearTimeout(timer);+ resolve();+ };+ });+ const result = await runHook("post-tool-use.mjs", payload, {+ AGENTMEMORY_URL: `http://127.0.0.1:${port}`,+ });+ await observeSeen;+ expect(result.exitCode).toBe(0);+ expect(observeCalls).toBe(1);+ });+});