Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(connect): make --with-hooks work when a hook handler has no command (#1574)

Dmitrii Zhukov34b790c2623b
diff --git a/src/cli/connect/codex-hooks.ts b/src/cli/connect/codex-hooks.ts
index 0a97eb82..554443f3 100644
--- a/src/cli/connect/codex-hooks.ts
+++ b/src/cli/connect/codex-hooks.ts
@@ -2,7 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
-type HookHandler = { type: string; command: string };
+type HookHandler = { type: string; command?: string; [key: string]: unknown };
type HookEntry = { matcher?: string; hooks: HookHandler[] };
export type HookManifest = { hooks: Record<string, HookEntry[]> };
@@ -34,13 +34,14 @@ export function findPluginRoot(startUrl: string = import.meta.url): string {
/**
* Build the merged hooks.json content.
*
- * 1. Strip any entry from `existing` whose first hook command points
- * under `<pluginRoot>/scripts/`. This lets us re-install idempotently
- * without leaving stale references.
+ * 1. Strip every handler in `existing` whose command points under
+ * `<pluginRoot>/scripts/`, and an entry only once nothing else is left
+ * in it. This lets us re-install idempotently without leaving stale
+ * references or dropping the user's own handlers.
* 2. Append fresh entries from the bundled Codex manifest with
* `${CLAUDE_PLUGIN_ROOT}` rewritten to the absolute plugin path.
- * Matcher values from the bundled manifest are preserved so PreToolUse
- * event routing keeps working.
+ * Matchers and the other handler fields from the bundled manifest are
+ * preserved so PreToolUse event routing keeps working.
*/
export function buildMergedHooks(
existing: HookManifest | null,
@@ -55,7 +56,13 @@ export function buildMergedHooks(
if (existing?.hooks) {
for (const [event, entries] of Object.entries(existing.hooks)) {
- const kept = entries.filter((entry) => !isAgentmemoryEntry(entry, scriptsDir));
+ const kept = entries.flatMap((entry) => {
+ const hooks = entry.hooks.filter(
+ (handler) => !isAgentmemoryHandler(handler, scriptsDir),
+ );
+ if (hooks.length === entry.hooks.length) return [entry];
+ return hooks.length > 0 ? [{ ...entry, hooks }] : [];
+ });
if (kept.length > 0) out.hooks[event] = kept;
}
}
@@ -64,8 +71,11 @@ export function buildMergedHooks(
const resolvedEntries: HookEntry[] = entries.map((entry) => {
const next: HookEntry = {
hooks: entry.hooks.map((handler) => ({
- type: handler.type,
- command: handler.command.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, pluginRoot),
+ ...handler,
+ command: handler.command?.replace(
+ /\$\{CLAUDE_PLUGIN_ROOT\}/g,
+ () => pluginRoot,
+ ),
})),
};
if (entry.matcher !== undefined) next.matcher = entry.matcher;
@@ -77,10 +87,12 @@ export function buildMergedHooks(
return out;
}
-function isAgentmemoryEntry(entry: HookEntry, scriptsDir: string): boolean {
- const normalizedScriptsDir = normalizePathForCommandMatch(scriptsDir);
- return entry.hooks.some((handler) =>
- normalizePathForCommandMatch(handler.command).includes(normalizedScriptsDir),
+function isAgentmemoryHandler(handler: HookHandler, scriptsDir: string): boolean {
+ return (
+ typeof handler.command === "string" &&
+ normalizePathForCommandMatch(handler.command).includes(
+ normalizePathForCommandMatch(scriptsDir),
+ )
);
}
diff --git a/test/claude-code-with-hooks.test.ts b/test/claude-code-with-hooks.test.ts
index 6c36b096..bf603747 100644
--- a/test/claude-code-with-hooks.test.ts
+++ b/test/claude-code-with-hooks.test.ts
@@ -1,5 +1,7 @@
-import { describe, it, expect } from "vitest";
-import { resolve } from "node:path";
+import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
import {
buildMergedHooks,
findPluginRoot,
@@ -61,6 +63,18 @@ describe("buildMergedHooks against plugin/hooks/hooks.json (Claude Code)", () =>
).toBe(true);
});
+ it("keeps a user command and its matcher from an entry it shares with agentmemory", () => {
+ const ours = buildMergedHooks(null, PLUGIN_ROOT, "hooks.json").hooks["PreToolUse"]!;
+ const user = { type: "command", command: "echo user-pre-tool" };
+ const existing: HookManifest = {
+ hooks: { PreToolUse: [{ matcher: "Bash", hooks: [ours[0]!.hooks[0]!, user] }] },
+ };
+ expect(buildMergedHooks(existing, PLUGIN_ROOT, "hooks.json").hooks["PreToolUse"]).toEqual([
+ { matcher: "Bash", hooks: [user] },
+ ...ours,
+ ]);
+ });
+
it("re-install strips previous agentmemory entries (idempotent)", () => {
const first = buildMergedHooks(null, PLUGIN_ROOT, "hooks.json");
const second = buildMergedHooks(first, PLUGIN_ROOT, "hooks.json");
@@ -72,3 +86,41 @@ describe("buildMergedHooks against plugin/hooks/hooks.json (Claude Code)", () =>
}
});
});
+
+describe("connect claude-code --with-hooks", () => {
+ let home: string;
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), "am-claude-hooks-"));
+ vi.stubEnv("HOME", home);
+ vi.stubEnv("USERPROFILE", home);
+ vi.resetModules();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ it("installs its hooks next to a prompt handler and keeps that handler", async () => {
+ const settingsPath = join(home, ".claude", "settings.json");
+ const promptEntry = { hooks: [{ type: "prompt", prompt: "Is the task done?" }] };
+ mkdirSync(join(home, ".claude"), { recursive: true });
+ writeFileSync(settingsPath, JSON.stringify({ hooks: { Stop: [promptEntry] } }));
+
+ const { resolveAdapter, runAdapter } = await import("../src/cli/connect/index.js");
+ const result = await runAdapter(resolveAdapter("claude-code")!, {
+ dryRun: false,
+ force: false,
+ withHooks: true,
+ });
+
+ expect(result.kind).toBe("installed");
+ const stop = (JSON.parse(readFileSync(settingsPath, "utf-8")) as HookManifest).hooks["Stop"];
+ expect(stop).toEqual([
+ promptEntry,
+ ...buildMergedHooks(null, PLUGIN_ROOT, "hooks.json").hooks["Stop"]!,
+ ]);
+ });
+});
diff --git a/test/codex-connect-hooks.test.ts b/test/codex-connect-hooks.test.ts
index 75accbee..6871ff5e 100644
--- a/test/codex-connect-hooks.test.ts
+++ b/test/codex-connect-hooks.test.ts
@@ -1,5 +1,12 @@
import { describe, it, expect } from "vitest";
-import { writeFileSync, readFileSync, mkdirSync, rmSync } from "node:fs";
+import {
+ copyFileSync,
+ writeFileSync,
+ readFileSync,
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+} from "node:fs";
import { join, resolve } from "node:path";
import { tmpdir } from "node:os";
import {
@@ -38,6 +45,29 @@ describe("buildMergedHooks", () => {
expect(preToolUse![0].matcher).toBe("Edit|Write|Read|Glob|Grep");
});
+ it("keeps handler fields other than the command, such as statusMessage", () => {
+ const merged = buildMergedHooks(null, PLUGIN_ROOT);
+ expect(merged.hooks["SessionStart"]![0]!.hooks[0]!.statusMessage).toBe(
+ "agentmemory: loading session context",
+ );
+ });
+
+ it("keeps a pluginRoot containing $-replacement patterns literal", () => {
+ const tmp = mkdtempSync(join(tmpdir(), "am-codex-hooks-"));
+ try {
+ const oddRoot = join(tmp, "plug$&$$in");
+ mkdirSync(join(oddRoot, "hooks"), { recursive: true });
+ copyFileSync(
+ join(PLUGIN_ROOT, "hooks", "hooks.codex.json"),
+ join(oddRoot, "hooks", "hooks.codex.json"),
+ );
+ const command = buildMergedHooks(null, oddRoot).hooks["Stop"]![0]!.hooks[0]!.command;
+ expect(command).toContain(`${oddRoot}/scripts/`);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
it("includes all six expected lifecycle events", () => {
const merged = buildMergedHooks(null, PLUGIN_ROOT);
for (const event of [