Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ jobs:
# in one pass.
- run: npm install --legacy-peer-deps --no-audit --no-fund
- run: npm run build
- run: npm run typecheck:hooks
- run: npm run skills:check
- run: npx tsc --noEmit --project tsconfig.eval.json
- run: npm test
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
},
"scripts": {
"build": "tsdown && node scripts/copy-assets.mjs",
"typecheck:hooks": "tsc --noEmit --project tsconfig.hooks.json",
"dev": "tsx src/index.ts",
"start": "node dist/cli.mjs",
"migrate": "node dist/functions/migrate.js",
Expand Down
41 changes: 41 additions & 0 deletions test/fixtures/hook-source-fetch.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { appendFileSync } from "node:fs";

function observedBody(body) {
if (typeof body !== "string") return body ?? null;
try {
return JSON.parse(body);
} catch {
return body;
}
}

globalThis.fetch = async (url, init = {}) => {
appendFileSync(
process.env.AGENTMEMORY_HOOK_TEST_REQUESTS,
`${JSON.stringify({
url: String(url),
method: init.method ?? "GET",
headers: Object.fromEntries(new Headers(init.headers)),
body: observedBody(init.body),
})}\n`,
);

const mode = process.env.AGENTMEMORY_HOOK_TEST_FETCH;
if (mode === "unreachable") throw new TypeError("fetch failed");
if (mode === "hanging") {
return new Promise((_resolve, reject) => {
const timer = setTimeout(() => reject(new Error("unaborted fetch")), 10_000);
const abort = () => {
clearTimeout(timer);
reject(init.signal.reason);
};
if (init.signal.aborted) abort();
else init.signal.addEventListener("abort", abort, { once: true });
});
}

return new Response(JSON.stringify({ context: "source-hook recalled context" }), {
status: String(url).endsWith("/observe") ? 201 : 200,
headers: { "content-type": "application/json" },
});
};
180 changes: 180 additions & 0 deletions test/helpers/hook-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { spawn } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { expect, it } from "vitest";

type HookName = "session-start" | "prompt-submit" | "pre-tool-use" | "post-tool-use" | "stop";

interface Request {
url: string;
method: string;
headers: Record<string, string>;
body: Record<string, unknown>;
}

interface SpoolRecord {
eventId: string;
reason: string;
body: Record<string, unknown>;
}

interface HookResult {
code: number | null;
signal: NodeJS.Signals | null;
elapsedMs: number;
stdout: string;
stderr: string;
requests: Request[];
spooled: SpoolRecord[];
}

const root = fileURLToPath(new URL("../../", import.meta.url));
const loader = pathToFileURL(createRequire(import.meta.url).resolve("tsx")).href;
const preload = pathToFileURL(join(root, "test/fixtures/hook-source-fetch.mjs")).href;

function lines<T>(path: string): T[] {
return existsSync(path)
? readFileSync(path, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line) as T)
: [];
}

export async function runSourceHook(
name: HookName,
payload: Record<string, unknown> | string,
options: {
fetch?: "success" | "unreachable" | "hanging";
env?: Record<string, string>;
} = {},
): Promise<HookResult> {
const dir = mkdtempSync(join(tmpdir(), "am-hook-source-"));
const requests = join(dir, "requests.jsonl");
const spool = join(dir, "spool");
const startedAt = performance.now();
try {
const result = await new Promise<Omit<HookResult, "requests" | "spooled">>((done, reject) => {
const child = spawn(process.execPath, [
"--import", loader,
"--import", preload,
resolve(root, "src/hooks", `${name}.ts`),
], {
cwd: dir,
env: {
PATH: process.env["PATH"],
SystemRoot: process.env["SystemRoot"],
HOME: dir,
USERPROFILE: dir,
APPDATA: dir,
LOCALAPPDATA: dir,
TEMP: dir,
TMP: dir,
AGENTMEMORY_URL: "http://127.0.0.1:3111",
AGENTMEMORY_SECRET: "source-hook-test-secret",
AGENTMEMORY_PROJECT_NAME: "source-hook-project",
AGENTMEMORY_INJECT_CONTEXT: "true",
AGENTMEMORY_CAPTURE_SPOOL_DIR: spool,
AGENTMEMORY_HOOK_TEST_FETCH: options.fetch ?? "success",
AGENTMEMORY_HOOK_TEST_REQUESTS: requests,
...options.env,
},
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
const timer = setTimeout(() => {
child.kill("SIGKILL");
reject(new Error(`${name} exceeded the test deadline: ${stderr}`));
}, 7000);
child.stdout.on("data", (chunk) => { stdout += chunk; });
child.stderr.on("data", (chunk) => { stderr += chunk; });
child.on("error", (error) => {
clearTimeout(timer);
reject(error);
});
child.on("close", (code, signal) => {
clearTimeout(timer);
done({ code, signal, stdout, stderr, elapsedMs: performance.now() - startedAt });
});
child.stdin.on("error", () => {});
child.stdin.end(typeof payload === "string" ? payload : JSON.stringify(payload));
});
return {
...result,
requests: lines<Request>(requests),
spooled: existsSync(spool)
? readdirSync(spool).filter((name) => name.endsWith(".jsonl"))
.flatMap((name) => lines<SpoolRecord>(join(spool, name)))
: [],
};
} finally {
rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
}
}

export function expectExit(result: HookResult, stdout = ""): void {
expect(result.code, result.stderr).toBe(0);
expect(result.signal).toBeNull();
expect(result.elapsedMs).toBeLessThan(5000);
expect(result.stdout).toBe(stdout);
}

export function expectPost(request: Request | undefined, path: string): asserts request is Request {
expect(request).toBeDefined();
expect(request!.url).toBe(`http://127.0.0.1:3111${path}`);
expect(request!.method).toBe("POST");
expect(request!.headers).toEqual({
authorization: "Bearer source-hook-test-secret",
"content-type": "application/json",
});
}

export function failureCases(
name: HookName,
payload: Record<string, unknown>,
options: { capture: boolean; requestPaths: string[] },
): void {
it.each(["{broken", "null", "7"])("ignores malformed stdin %s", async (input) => {
const result = await runSourceHook(name, input);
expectExit(result);
expect(result.requests).toEqual([]);
expect(result.spooled).toEqual([]);
});

it.each(["environment", "payload"])("ignores SDK child context from %s", async (source) => {
const result = await runSourceHook(name,
source === "payload" ? { ...payload, entrypoint: "sdk-ts" } : payload,
{ env: source === "environment" ? { AGENTMEMORY_SDK_CHILD: "1" } : {} },
);
expectExit(result);
expect(result.requests).toEqual([]);
expect(result.spooled).toEqual([]);
});

it.each(["unreachable", "hanging"] as const)("exits successfully when fetch is %s", async (mode) => {
const result = await runSourceHook(name, payload, { fetch: mode });
expectExit(result);
expect(result.requests.map((request) => new URL(request.url).pathname)).toEqual(options.requestPaths);
if (options.capture) {
expect(result.spooled).toHaveLength(1);
expect(result.spooled[0]).toMatchObject({
eventId: result.requests[0]!.body["eventId"],
reason: mode === "unreachable" ? "unreachable" : "timeout",
body: result.requests[0]!.body,
});
} else {
expect(result.spooled).toEqual([]);
}
}, 10_000);

it("refuses a secret over non-loopback HTTP without fetching or spooling", async () => {
const result = await runSourceHook(name, payload, {
env: { AGENTMEMORY_URL: "http://untrusted.example:3111" },
});
expectExit(result);
expect(result.stderr).toContain("must use HTTPS");
expect(result.requests).toEqual([]);
expect(result.spooled).toEqual([]);
});
}
41 changes: 41 additions & 0 deletions test/hook-source-fetch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";

const preload = new URL("./fixtures/hook-source-fetch.mjs", import.meta.url).href;

describe("source-hook fetch observer", () => {
it.each([
{ name: "an unexpected GET without a body", init: undefined, method: "GET", body: null },
{ name: "an unexpected non-JSON POST", init: { method: "POST", body: "not-json" }, method: "POST", body: "not-json" },
])("records $name so a no-fetch assertion cannot miss it", ({ init, method, body }) => {
const dir = mkdtempSync(join(tmpdir(), "am-hook-fetch-"));
const requests = join(dir, "requests.jsonl");
const url = "http://127.0.0.1:3111/unexpected";
const program = `await fetch(${JSON.stringify(url)}, ${JSON.stringify(init)}).catch(() => {});`;
try {
execFileSync(process.execPath, ["--import", preload, "--input-type=module", "-e", program], {
cwd: fileURLToPath(new URL("../", import.meta.url)),
env: {
PATH: process.env["PATH"],
SystemRoot: process.env["SystemRoot"],
HOME: dir,
USERPROFILE: dir,
AGENTMEMORY_HOOK_TEST_FETCH: "success",
AGENTMEMORY_HOOK_TEST_REQUESTS: requests,
},
timeout: 5000,
stdio: "pipe",
});
const observed: unknown[] = existsSync(requests)
? readFileSync(requests, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line))
: [];
expect(observed).toEqual([{ url, method, headers: {}, body }]);
} finally {
rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
}
});
});
30 changes: 30 additions & 0 deletions test/post-tool-use-source.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { expectExit, expectPost, failureCases, runSourceHook } from "./helpers/hook-source.js";

const payload = {
session_id: "source-session", cwd: "/fixture/repo", tool_use_id: "tool-1", tool_name: "Read",
tool_input: { file_path: "/fixture/repo/file.ts" }, tool_response: "Literal tool output.",
};

describe("post-tool-use source entrypoint", () => {
it("captures the complete tool payload with host event identity", async () => {
const result = await runSourceHook("post-tool-use", payload);
expectExit(result);
expect(result.requests).toHaveLength(1);
expectPost(result.requests[0], "/agentmemory/observe");
expect(result.requests[0].body).toEqual({
hookType: "post_tool_use", sessionId: "source-session", project: "source-hook-project", cwd: "/fixture/repo",
timestamp: expect.any(String), eventId: expect.stringMatching(/^evh_[0-9a-f]{32}$/),
data: { tool_name: "Read", tool_input: { file_path: "/fixture/repo/file.ts" }, tool_output: "Literal tool output." },
});
expect(result.spooled).toEqual([]);
});

it("keeps memory tool calls out of capture", async () => {
const result = await runSourceHook("post-tool-use", { ...payload, tool_name: "mcp__agentmemory__memory_save" });
expectExit(result);
expect(result.requests).toEqual([]);
});

failureCases("post-tool-use", payload, { capture: true, requestPaths: ["/agentmemory/observe"] });
});
30 changes: 30 additions & 0 deletions test/pre-tool-use-source.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { expectExit, expectPost, failureCases, runSourceHook } from "./helpers/hook-source.js";

const payload = {
session_id: "source-session", cwd: "/fixture/repo", hook_event_name: "PreToolUse",
tool_name: "Read", tool_input: { file_path: "/fixture/repo/file.ts" },
};

describe("pre-tool-use source entrypoint", () => {
it("requests scoped file context and prints the host envelope", async () => {
const result = await runSourceHook("pre-tool-use", payload);
expectExit(result, JSON.stringify({ hookSpecificOutput: {
hookEventName: "PreToolUse", additionalContext: "source-hook recalled context",
} }));
expect(result.requests).toHaveLength(1);
expectPost(result.requests[0], "/agentmemory/enrich");
expect(result.requests[0].body).toEqual({
sessionId: "source-session", files: ["/fixture/repo/file.ts"], terms: [], toolName: "Read", project: "source-hook-project",
});
expect(result.spooled).toEqual([]);
});

it("sends nothing when context injection is disabled", async () => {
const result = await runSourceHook("pre-tool-use", payload, { env: { AGENTMEMORY_INJECT_CONTEXT: "false" } });
expectExit(result);
expect(result.requests).toEqual([]);
});

failureCases("pre-tool-use", payload, { capture: false, requestPaths: ["/agentmemory/enrich"] });
});
21 changes: 21 additions & 0 deletions test/prompt-submit-source.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { expectExit, expectPost, failureCases, runSourceHook } from "./helpers/hook-source.js";

const payload = { session_id: "source-session", cwd: "/fixture/repo", prompt: "Keep this literal user prompt.", prompt_id: "prompt-1" };

describe("prompt-submit source entrypoint", () => {
it("captures the prompt with session, project and host event identity", async () => {
const result = await runSourceHook("prompt-submit", payload);
expectExit(result);
expect(result.requests).toHaveLength(1);
expectPost(result.requests[0], "/agentmemory/observe");
expect(result.requests[0].body).toEqual({
hookType: "prompt_submit", sessionId: "source-session", project: "source-hook-project", cwd: "/fixture/repo",
timestamp: expect.any(String), eventId: expect.stringMatching(/^evh_[0-9a-f]{32}$/),
data: { prompt: "Keep this literal user prompt." },
});
expect(result.spooled).toEqual([]);
});

failureCases("prompt-submit", payload, { capture: true, requestPaths: ["/agentmemory/observe"] });
});
28 changes: 28 additions & 0 deletions test/session-start-source.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { expectExit, expectPost, failureCases, runSourceHook } from "./helpers/hook-source.js";

const payload = { session_id: "source-session", cwd: "/fixture/repo", hook_event_name: "SessionStart" };

describe("session-start source entrypoint", () => {
it("registers the session and prints the host context envelope", async () => {
const result = await runSourceHook("session-start", payload);
expectExit(result, JSON.stringify({ hookSpecificOutput: {
hookEventName: "SessionStart", additionalContext: "source-hook recalled context",
} }));
expect(result.requests).toHaveLength(1);
expectPost(result.requests[0], "/agentmemory/session/start");
expect(result.requests[0].body).toEqual({
sessionId: "source-session", project: "source-hook-project", cwd: "/fixture/repo",
});
expect(result.spooled).toEqual([]);
});

it("registers without printing context when injection is disabled", async () => {
const result = await runSourceHook("session-start", payload, { env: { AGENTMEMORY_INJECT_CONTEXT: "false" } });
expectExit(result);
expect(result.requests).toHaveLength(1);
expectPost(result.requests[0], "/agentmemory/session/start");
});

failureCases("session-start", payload, { capture: false, requestPaths: ["/agentmemory/session/start"] });
});
Loading