#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix(codex): --with-hooks workaround for openai/codex#16430 (closes #509) (#564)
Rohit Ghumaree371be9d98e1
diff --git a/README.md b/README.mdindex 96e804d4..840a75c4 100644--- a/README.md+++ b/README.md@@ -430,6 +430,18 @@ The Codex plugin ships from the same `plugin/` directory as the Claude Code plugCodex's hook engine injects `CLAUDE_PLUGIN_ROOT` into hook subprocesses (per [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), so the same hook scripts work across both hosts without duplication. Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure events are Claude-Code-only and are not registered for Codex.+#### Codex Desktop: plugin hooks currently silent (workaround available)++`CodexHooks` and `PluginHooks` are both stable + default-enabled in [`codex-rs/features/src/lib.rs`](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs), but Codex Desktop builds currently do not dispatch plugin-local `hooks.json` ([openai/codex#16430](https://github.com/openai/codex/issues/16430)). MCP tools still work; only the lifecycle observations are missing.++Until upstream lands the fix, mirror the same hook commands into the global `~/.codex/hooks.json`:++```bash+agentmemory connect codex --with-hooks+```++This adds an idempotent block to `~/.codex/hooks.json` referencing absolute paths to the bundled scripts (no `${CLAUDE_PLUGIN_ROOT}` expansion needed at user-scope). Re-run the same command after upgrading agentmemory to refresh paths. User entries in the same file are preserved; only previous agentmemory entries are replaced.+<details><summary><b>OpenClaw (paste this prompt)</b></summary>@@ -504,7 +516,7 @@ The agentmemory entry is the **same MCP server block** across every host that us| **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (auto-merges). || **OpenClaw** | OpenClaw MCP config | Same `mcpServers` block, or use the deeper [memory plugin](integrations/openclaw/). || **Codex CLI (MCP only)** | `.codex/config.toml` | TOML shape: `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, or add `[mcp_servers.agentmemory]` manually. |-| **Codex CLI (full plugin)** | Codex plugin marketplace | `codex plugin marketplace add rohitg00/agentmemory` then `codex plugin install agentmemory`. Registers MCP + 6 lifecycle hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skills. |+| **Codex CLI (full plugin)** | Codex plugin marketplace | `codex plugin marketplace add rohitg00/agentmemory` then `codex plugin install agentmemory`. Registers MCP + 6 lifecycle hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skills. On Codex Desktop, also run `agentmemory connect codex --with-hooks` until [openai/codex#16430](https://github.com/openai/codex/issues/16430) lands — plugin hooks are currently silent there. || **OpenCode (MCP only)** | `opencode.json` | Different shape — top-level `mcp` key, command as array: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. || **OpenCode (full plugin)** | `plugin/opencode/` | 22 auto-capture hooks covering session lifecycle, messages, tools, errors. Two slash commands (`/recall`, `/remember`). Copy `plugin/opencode/` into your OpenCode workspace and add the plugin entry to `opencode.json`. See [`plugin/opencode/README.md`](plugin/opencode/README.md) for the full hook table + gap analysis. || **pi** | `~/.pi/agent/extensions/agentmemory` | Copy [`integrations/pi`](integrations/pi/) and restart pi. |diff --git a/src/cli/connect/codex-hooks.ts b/src/cli/connect/codex-hooks.tsnew file mode 100644index 00000000..679ec8be--- /dev/null+++ b/src/cli/connect/codex-hooks.ts@@ -0,0 +1,100 @@+import { existsSync, readFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++/**+ * Workaround for openai/codex#16430 — Codex Desktop does not dispatch+ * plugin-local `hooks.json` even though both `CodexHooks` and `PluginHooks`+ * feature flags are stable + default-enabled in+ * `codex-rs/features/src/lib.rs`. Until upstream fixes plugin-scope+ * dispatch, the same hook commands can be mirrored into the global+ * `~/.codex/hooks.json`, which is loaded reliably.+ *+ * This module builds that mirror, with `${CLAUDE_PLUGIN_ROOT}` resolved to+ * the bundled `plugin/` directory so the user-scope file does not depend+ * on env-var expansion (Codex only injects `CLAUDE_PLUGIN_ROOT` for+ * plugin-scope hooks).+ *+ * Identification on re-install: every command we write contains the+ * resolved `<pluginRoot>/scripts/` prefix, so subsequent installs can+ * strip our entries and re-add cleanly without touching the user's other+ * hook entries.+ */++type HookHandler = { type: string; command: string };+type HookEntry = { matcher?: string; hooks: HookHandler[] };+export type HookManifest = { hooks: Record<string, HookEntry[]> };++/**+ * Locate the bundled `plugin/` directory at runtime. Walks up from the+ * module's own location looking for `plugin/scripts/` + `plugin/hooks/`,+ * both shipped via the npm `files` field. Works for both `dist/cli.mjs`+ * (bundled) and `src/cli/connect/codex-hooks.ts` (dev) layouts.+ */+export function findPluginRoot(startUrl: string = import.meta.url): string {+ const here = dirname(fileURLToPath(startUrl));+ let dir = here;+ for (let i = 0; i < 12; i++) {+ if (+ existsSync(join(dir, "plugin", "scripts")) &&+ existsSync(join(dir, "plugin", "hooks"))+ ) {+ return resolve(join(dir, "plugin"));+ }+ const parent = dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ throw new Error(+ `agentmemory: could not locate bundled plugin/ directory (searched up from ${here})`,+ );+}++/**+ * 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.+ * 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.+ */+export function buildMergedHooks(+ existing: HookManifest | null,+ pluginRoot: string,+): HookManifest {+ const codexManifestPath = join(pluginRoot, "hooks", "hooks.codex.json");+ const ours = JSON.parse(readFileSync(codexManifestPath, "utf-8")) as HookManifest;+ const scriptsDir = join(pluginRoot, "scripts");++ const out: HookManifest = { hooks: {} };++ if (existing?.hooks) {+ for (const [event, entries] of Object.entries(existing.hooks)) {+ const kept = entries.filter((entry) => !isAgentmemoryEntry(entry, scriptsDir));+ if (kept.length > 0) out.hooks[event] = kept;+ }+ }++ for (const [event, entries] of Object.entries(ours.hooks)) {+ 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),+ })),+ };+ if (entry.matcher !== undefined) next.matcher = entry.matcher;+ return next;+ });+ out.hooks[event] = [...(out.hooks[event] ?? []), ...resolvedEntries];+ }++ return out;+}++function isAgentmemoryEntry(entry: HookEntry, scriptsDir: string): boolean {+ return entry.hooks.some((handler) => handler.command.includes(scriptsDir));+}diff --git a/src/cli/connect/codex.ts b/src/cli/connect/codex.tsindex 003dc99a..a87b2858 100644--- a/src/cli/connect/codex.ts+++ b/src/cli/connect/codex.ts@@ -8,10 +8,18 @@ import {logAlreadyWired,logBackup,logInstalled,+ readJsonSafe,+ writeJsonAtomic,} from "./util.js";+import {+ buildMergedHooks,+ findPluginRoot,+ type HookManifest,+} from "./codex-hooks.js";const CODEX_DIR = join(homedir(), ".codex");const CODEX_TOML = join(CODEX_DIR, "config.toml");+const CODEX_HOOKS = join(CODEX_DIR, "hooks.json");const TOML_BLOCK = `[mcp_servers.agentmemory]command = "npx"@@ -57,7 +65,7 @@ export const adapter: ConnectAdapter = {displayName: "Codex CLI",docs: "https://github.com/rohitg00/agentmemory#codex-cli-codex-plugin-platform",protocolNote:- "→ Using MCP. Hooks are also available — see docs/codex.md.",+ "→ Using MCP. Hooks ship via the Codex plugin; on Codex Desktop, also pass --with-hooks to install the global hooks.json workaround for openai/codex#16430.",detect(): boolean {return existsSync(CODEX_DIR);@@ -77,6 +85,7 @@ export const adapter: ConnectAdapter = {p.log.info(`[dry-run] Would ${wired ? "rewrite" : "append"} [mcp_servers.agentmemory] in ${CODEX_TOML}`,);+ if (opts.withHooks) installCodexHooks(opts);return { kind: "installed", mutatedPath: CODEX_TOML };}@@ -105,6 +114,16 @@ export const adapter: ConnectAdapter = {p.log.info("Codex picks up MCP servers on next launch. For the deeper plugin install, run: codex plugin marketplace add rohitg00/agentmemory && codex plugin install agentmemory",);++ if (opts.withHooks) {+ const hookResult = installCodexHooks(opts);+ if (hookResult.kind === "skipped") {+ p.log.warn(+ `Codex hooks fallback skipped: ${hookResult.reason}. MCP wiring still applied.`,+ );+ }+ }+return {kind: "installed",mutatedPath: CODEX_TOML,@@ -112,3 +131,50 @@ export const adapter: ConnectAdapter = {};},};++/**+ * Install the global `~/.codex/hooks.json` fallback. See+ * `codex-hooks.ts` for context (openai/codex#16430). Returns a result+ * describing the side effect for the caller's summary; failures here do+ * not roll back the MCP wiring.+ */+function installCodexHooks(opts: ConnectOptions): ConnectResult {+ let pluginRoot: string;+ try {+ pluginRoot = findPluginRoot();+ } catch (err) {+ return {+ kind: "skipped",+ reason: err instanceof Error ? err.message : String(err),+ };+ }++ const existing = readJsonSafe<HookManifest>(CODEX_HOOKS);+ const merged = buildMergedHooks(existing, pluginRoot);++ if (opts.dryRun) {+ p.log.info(+ `[dry-run] Would ${existing ? "merge" : "create"} ${CODEX_HOOKS} with ${Object.keys(merged.hooks).length} event(s)`,+ );+ return { kind: "installed", mutatedPath: CODEX_HOOKS };+ }++ let backupPath: string | undefined;+ if (existsSync(CODEX_HOOKS)) {+ backupPath = backupFile(CODEX_HOOKS, "codex-hooks", "json");+ logBackup(backupPath);+ }++ writeJsonAtomic(CODEX_HOOKS, merged);++ logInstalled("Codex hooks (workaround for openai/codex#16430)", CODEX_HOOKS);+ p.log.info(+ "User-scope hooks reference absolute paths under the bundled plugin/ dir. Re-run `agentmemory connect codex --with-hooks` after upgrading agentmemory to refresh them.",+ );++ return {+ kind: "installed",+ mutatedPath: CODEX_HOOKS,+ ...(backupPath !== undefined && { backupPath }),+ };+}diff --git a/src/cli/connect/index.ts b/src/cli/connect/index.tsindex 17aedf8f..48c23c66 100644--- a/src/cli/connect/index.ts+++ b/src/cli/connect/index.ts@@ -34,19 +34,22 @@ function parseFlags(args: string[]): {dryRun: boolean;force: boolean;all: boolean;+ withHooks: boolean;positional: string[];} {const positional: string[] = [];let dryRun = false;let force = false;let all = false;+ let withHooks = false;for (const a of args) {if (a === "--dry-run") dryRun = true;else if (a === "--force") force = true;else if (a === "--all") all = true;+ else if (a === "--with-hooks") withHooks = true;else if (!a.startsWith("-")) positional.push(a);}- return { dryRun, force, all, positional };+ return { dryRun, force, all, withHooks, positional };}export async function runAdapter(@@ -83,8 +86,8 @@ export async function runConnect(args: string[]): Promise<void> {return;}- const { dryRun, force, all, positional } = parseFlags(args);- const opts: ConnectOptions = { dryRun, force };+ const { dryRun, force, all, withHooks, positional } = parseFlags(args);+ const opts: ConnectOptions = { dryRun, force, withHooks };p.intro("agentmemory connect");diff --git a/src/cli/connect/types.ts b/src/cli/connect/types.tsindex 4f64c867..8abd2745 100644--- a/src/cli/connect/types.ts+++ b/src/cli/connect/types.ts@@ -1,6 +1,13 @@export type ConnectOptions = {dryRun: boolean;force: boolean;+ /**+ * When true, the Codex adapter additionally writes a global+ * `~/.codex/hooks.json` block referencing absolute paths to bundled hook+ * scripts. Workaround for openai/codex#16430, which prevents plugin-local+ * hooks from dispatching on Codex Desktop. No-op for other adapters.+ */+ withHooks?: boolean;};export type ConnectAdapter = {diff --git a/test/codex-connect-hooks.test.ts b/test/codex-connect-hooks.test.tsnew file mode 100644index 00000000..75accbee--- /dev/null+++ b/test/codex-connect-hooks.test.ts@@ -0,0 +1,137 @@+import { describe, it, expect } from "vitest";+import { writeFileSync, readFileSync, mkdirSync, rmSync } from "node:fs";+import { join, resolve } from "node:path";+import { tmpdir } from "node:os";+import {+ buildMergedHooks,+ findPluginRoot,+ type HookManifest,+} from "../src/cli/connect/codex-hooks.js";++const PLUGIN_ROOT = resolve(__dirname, "..", "plugin");++describe("findPluginRoot", () => {+ it("locates the bundled plugin/ directory from src/cli/connect/", () => {+ const root = findPluginRoot();+ expect(root).toBe(PLUGIN_ROOT);+ });+});++describe("buildMergedHooks", () => {+ it("rewrites ${CLAUDE_PLUGIN_ROOT} to absolute pluginRoot in every command", () => {+ const merged = buildMergedHooks(null, PLUGIN_ROOT);+ for (const entries of Object.values(merged.hooks)) {+ for (const entry of entries) {+ for (const handler of entry.hooks) {+ expect(handler.command).not.toContain("${CLAUDE_PLUGIN_ROOT}");+ expect(handler.command).toContain(`${PLUGIN_ROOT}/scripts/`);+ }+ }+ }+ });++ it("preserves matchers from the bundled manifest (e.g. PreToolUse)", () => {+ const merged = buildMergedHooks(null, PLUGIN_ROOT);+ const preToolUse = merged.hooks["PreToolUse"];+ expect(preToolUse).toBeDefined();+ expect(preToolUse!.length).toBeGreaterThan(0);+ expect(preToolUse![0].matcher).toBe("Edit|Write|Read|Glob|Grep");+ });++ it("includes all six expected lifecycle events", () => {+ const merged = buildMergedHooks(null, PLUGIN_ROOT);+ for (const event of [+ "SessionStart",+ "UserPromptSubmit",+ "PreToolUse",+ "PostToolUse",+ "PreCompact",+ "Stop",+ ]) {+ expect(Object.keys(merged.hooks)).toContain(event);+ }+ });++ it("appends to existing user hooks without dropping them", () => {+ const existing: HookManifest = {+ hooks: {+ SessionStart: [+ {+ hooks: [{ type: "command", command: "echo user-custom" }],+ },+ ],+ UserPromptSubmit: [+ {+ hooks: [{ type: "command", command: "echo another-user-hook" }],+ },+ ],+ },+ };+ const merged = buildMergedHooks(existing, PLUGIN_ROOT);+ const sessionStart = merged.hooks["SessionStart"]!;+ const userHook = sessionStart.find((e) =>+ e.hooks.some((h) => h.command === "echo user-custom"),+ );+ expect(userHook, "user's SessionStart hook should survive").toBeDefined();+ const ours = sessionStart.find((e) =>+ e.hooks.some((h) => h.command.includes(`${PLUGIN_ROOT}/scripts/session-start.mjs`)),+ );+ expect(ours, "agentmemory SessionStart hook should be appended").toBeDefined();+ });++ it("re-install strips previous agentmemory entries (idempotent by script path)", () => {+ const first = buildMergedHooks(null, PLUGIN_ROOT);+ const second = buildMergedHooks(first, PLUGIN_ROOT);+ for (const event of Object.keys(first.hooks)) {+ expect(+ second.hooks[event]!.length,+ `${event} should not double after second install`,+ ).toBe(first.hooks[event]!.length);+ }+ });++ it("re-install preserves unrelated user entries", () => {+ const userEntry = {+ hooks: [{ type: "command", command: "echo user-untouchable" }],+ };+ const withUser: HookManifest = {+ hooks: {+ SessionStart: [userEntry],+ Stop: [{ hooks: [{ type: "command", command: "echo also-user" }] }],+ },+ };+ const installed = buildMergedHooks(withUser, PLUGIN_ROOT);+ const reinstalled = buildMergedHooks(installed, PLUGIN_ROOT);+ expect(+ reinstalled.hooks["SessionStart"]!.some((e) =>+ e.hooks.some((h) => h.command === "echo user-untouchable"),+ ),+ ).toBe(true);+ expect(+ reinstalled.hooks["Stop"]!.some((e) =>+ e.hooks.some((h) => h.command === "echo also-user"),+ ),+ ).toBe(true);+ });++ it("handles empty existing manifest object", () => {+ const merged = buildMergedHooks({ hooks: {} }, PLUGIN_ROOT);+ expect(Object.keys(merged.hooks).length).toBeGreaterThan(0);+ });+});++describe("buildMergedHooks file round-trip", () => {+ it("produces JSON that parses back to a structurally equivalent manifest", () => {+ const dir = join(tmpdir(), `agentmemory-codex-hooks-${process.pid}-${Date.now()}`);+ mkdirSync(dir, { recursive: true });+ const path = join(dir, "hooks.json");+ try {+ const merged = buildMergedHooks(null, PLUGIN_ROOT);+ writeFileSync(path, `${JSON.stringify(merged, null, 2)}\n`, "utf-8");+ const reread = JSON.parse(readFileSync(path, "utf-8")) as HookManifest;+ expect(Object.keys(reread.hooks).sort()).toEqual(Object.keys(merged.hooks).sort());+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});