Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
feat(hosts): bring the full Claude Code hook set to Codex
Shrish Dwivedi37a65e81a9bd
diff --git a/src/claude/hooks.ts b/src/claude/hooks.tsindex 77bea591..68d51eee 100644--- a/src/claude/hooks.ts+++ b/src/claude/hooks.ts@@ -1,6 +1,6 @@import { readFileSync, existsSync } from 'node:fs';import { execFileSync, spawn } from 'node:child_process';-import { join, basename } from 'node:path';+import { join, basename, isAbsolute } from 'node:path';import { readWiring } from './stats.js';import { formatBlastRadius, relevantRetrieval, formatOrientation } from './format.js';import { indexFreshness, staleBanner } from '../context/check.js';@@ -104,8 +104,31 @@ function emit(eventName: string, additionalContext: string): void {process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: eventName, additionalContext } }));}+/**+ * The absolute path of the file a PostToolUse edit touched, across host edit-tool+ * shapes:+ * - Claude Code (`Write`/`Edit`/`MultiEdit`) states it directly as+ * `tool_input.file_path` (already absolute).+ * - Codex (`apply_patch`) carries the whole patch in `tool_input.command` and+ * names the file in the patch header (`*** Add File:` / `*** Update File:`),+ * as a repo-relative path — resolved against `dir` here. Take the first+ * Add/Update target; that one file is enough to mark the graph dirty and+ * draw a blast radius (the sync re-checks the whole tree anyway).+ * Returns null when neither shape yields a path, so the hook stays a clean no-op.+ */+export function editedFilePath(input: any, dir: string): string | null {+ const direct = input?.tool_input?.file_path;+ if (typeof direct === 'string' && direct.trim()) return direct;+ const cmd = input?.tool_input?.command;+ if (typeof cmd === 'string' && cmd) {+ const m = /^\*\*\*\s+(?:Add|Update)\s+File:\s+(.+?)\s*$/m.exec(cmd);+ if (m) return isAbsolute(m[1]) ? m[1] : join(dir, m[1]);+ }+ return null;+}+async function handlePostEdit(input: any, dir: string): Promise<void> {- const file: string | undefined = input?.tool_input?.file_path;+ const file = editedFilePath(input, dir);if (!file || underGraft(dir, file)) return;patchStats(dir, { dirty: true, staleCount: checkStaleCount(dir), lastFile: basename(file) });const w = readWiring(dir);diff --git a/src/hosts/codex-hooks.ts b/src/hosts/codex-hooks.tsindex 92f96ccc..c5f545a8 100644--- a/src/hosts/codex-hooks.ts+++ b/src/hosts/codex-hooks.ts@@ -21,9 +21,9 @@ function dirExists(p: string): boolean {/*** The files installing the Codex hook would touch — pure, no writes. Both live- * under `~/.codex`, so both are scoped 'global': the PostToolUse entry fires on- * every edit in every repo opened with Codex, not just this one. Empty when the- * CLI isn't installed, mirroring `installCodexHooks`' early return.+ * under `~/.codex`, so both are scoped 'global': the hook entries fire in every+ * repo opened with Codex, not just this one. Empty when the CLI isn't installed,+ * mirroring `installCodexHooks`' early return.*/export function hookTargets(home: string): PlannedWrite[] {const base = join(home, '.codex');@@ -37,7 +37,7 @@ export function hookTargets(home: string): PlannedWrite[] {{hostId: 'agents', id: 'codex-hooks',path: join(base, 'hooks.json'),- scope: 'global', kind: 'hook', what: 'PostToolUse: Write|Edit|MultiEdit',+ scope: 'global', kind: 'hook', what: 'SessionStart / UserPromptSubmit / PostToolUse / Stop',},];}@@ -58,40 +58,56 @@ function isGraftEntry(entry: unknown): boolean {return JSON.stringify(entry).includes('graft-hooks.cjs');}+/**+ * The graft hook entries Codex should carry, mirroring the Claude Code set:+ * - SessionStart → orientation from `graft/INDEX.md`+ * - UserPromptSubmit → the coupling-seed retrieval pack (the accuracy hook)+ * - PostToolUse (an edit) → blast radius + mark the graph dirty+ * - Stop → one background graph sync at turn end (not after every edit)+ * `matcher` is omitted where Codex ignores it (UserPromptSubmit, Stop). The edit+ * matcher includes `apply_patch` — Codex's native edit tool — alongside the+ * Claude Code edit-tool names, and `hooks.ts`'s `editedFilePath` reads the touched+ * file out of either shape.+ */+interface DesiredEntry { event: string; matcher?: string; sub: string; timeout: number; }+function desiredEntries(): DesiredEntry[] {+ return [+ { event: 'SessionStart', matcher: 'startup|resume|compact', sub: 'session-start', timeout: 10000 },+ { event: 'UserPromptSubmit', sub: 'prompt', timeout: 15000 },+ { event: 'PostToolUse', matcher: 'apply_patch|Write|Edit|MultiEdit', sub: 'post-edit', timeout: 10000 },+ { event: 'Stop', sub: 'stop', timeout: 10000 },+ ];+}+export function installCodexHooks(home: string): HookWrite[] {const targets = hookTargets(home);if (targets.length === 0) return [];const shimPath = targets[0].path;const shimWrite = writeOwned('codex-hook-shim', shimPath, hooksShim(claudeDistDir()), 0o755);+ const skipped: HookWrite = { id: 'codex-hooks', path: targets[1].path, action: 'skipped-unparseable' };const cfgPath = targets[1].path;let root: Record<string, any> = {};const existed = existsSync(cfgPath);if (existed) {- try { root = JSON.parse(readFileSync(cfgPath, 'utf8')); } catch {- return [shimWrite, { id: 'codex-hooks', path: cfgPath, action: 'skipped-unparseable' }];- }- }- if (typeof root !== 'object' || root === null || Array.isArray(root)) {- return [shimWrite, { id: 'codex-hooks', path: cfgPath, action: 'skipped-unparseable' }];+ try { root = JSON.parse(readFileSync(cfgPath, 'utf8')); } catch { return [shimWrite, skipped]; }}+ if (typeof root !== 'object' || root === null || Array.isArray(root)) return [shimWrite, skipped];const before = JSON.stringify(root);const hooks = (root.hooks ??= {});- if (typeof hooks !== 'object' || hooks === null || Array.isArray(hooks)) {- return [shimWrite, { id: 'codex-hooks', path: cfgPath, action: 'skipped-unparseable' }];- }- if (hooks.PostToolUse !== undefined && !Array.isArray(hooks.PostToolUse)) {- return [shimWrite, { id: 'codex-hooks', path: cfgPath, action: 'skipped-unparseable' }];+ if (typeof hooks !== 'object' || hooks === null || Array.isArray(hooks)) return [shimWrite, skipped];++ for (const d of desiredEntries()) {+ if (hooks[d.event] !== undefined && !Array.isArray(hooks[d.event])) return [shimWrite, skipped];+ const prior: unknown[] = Array.isArray(hooks[d.event]) ? hooks[d.event] : [];+ const handler = { type: 'command', command: `node "${shimPath}" ${d.sub}`, timeout: d.timeout };+ const entry = d.matcher ? { matcher: d.matcher, hooks: [handler] } : { hooks: [handler] };+ // Preserve foreign entries in this event; replace any prior graft entry so an+ // upgrade re-points to the current shim/sub-command instead of stacking.+ hooks[d.event] = [...prior.filter((e) => !isGraftEntry(e)), entry];}- const prior: unknown[] = Array.isArray(hooks.PostToolUse) ? hooks.PostToolUse : [];- hooks.PostToolUse = [- ...prior.filter((e) => !isGraftEntry(e)),- {- matcher: 'Write|Edit|MultiEdit',- hooks: [{ type: 'command', command: `node "${shimPath}" post-edit-sync`, timeout: 10000 }],- },- ];+if (JSON.stringify(root) === before) return [shimWrite, { id: 'codex-hooks', path: cfgPath, action: 'unchanged' }];writeFileSync(cfgPath, `${JSON.stringify(root, null, 2)}\n`);return [shimWrite, { id: 'codex-hooks', path: cfgPath, action: existed ? 'updated' : 'created' }];diff --git a/test/cli-picker.test.ts b/test/cli-picker.test.tsindex 2ba40783..50120ece 100644--- a/test/cli-picker.test.ts+++ b/test/cli-picker.test.ts@@ -187,7 +187,7 @@ test('formatPlan separates repo writes from machine-wide ones', () => {const globalAt = text.indexOf('affects ALL repos:');assert.ok(repoAt >= 0 && globalAt > repoAt, 'repo section comes first');assert.ok(text.includes(`~${sep}${join('.codex', 'hooks.json')}`), `plan should name the codex hooks file:\n${text}`);- assert.match(text, /PostToolUse: Write\|Edit\|MultiEdit/);+ assert.match(text, /SessionStart \/ UserPromptSubmit \/ PostToolUse \/ Stop/);assert.match(text, /nothing was written \(--dry-run\)/);assert.match(text, /--no-global/);});diff --git a/test/hosts-codex-hooks.test.ts b/test/hosts-codex-hooks.test.tsindex bb0bd339..abd5b68b 100644--- a/test/hosts-codex-hooks.test.ts+++ b/test/hosts-codex-hooks.test.ts@@ -4,6 +4,7 @@ import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, statSyimport { tmpdir } from 'node:os';import { join } from 'node:path';import { installCodexHooks } from '../src/hosts/codex-hooks.js';+import { editedFilePath } from '../src/claude/hooks.js';function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-cxhooks-')); }@@ -34,13 +35,24 @@ test('writes shim + hooks.json entry, idempotent on re-run', () => {const shim = join(home, '.codex', 'hooks', 'graft', 'graft-hooks.cjs');assertRunnableShim(shim, 'shim is executable');const cfg = JSON.parse(readFileSync(join(home, '.codex', 'hooks.json'), 'utf8'));- const entries = cfg.hooks.PostToolUse;- assert.equal(entries.length, 1);- assert.equal(entries[0].matcher, 'Write|Edit|MultiEdit');- assert.match(entries[0].hooks[0].command, /post-edit-sync/);+ // Full Claude-Code parity: retrieval on prompt, orientation on start, blast+ // radius on edit, one background sync at turn end.+ const sub = (event: string) => cfg.hooks[event][0].hooks[0].command.match(/cjs" (\S+)$/)?.[1];+ assert.equal(sub('UserPromptSubmit'), 'prompt', 'the coupling-seed retrieval hook');+ assert.equal(sub('SessionStart'), 'session-start', 'orientation hook');+ assert.equal(sub('PostToolUse'), 'post-edit', 'edit hook (sync split out to Stop)');+ assert.equal(sub('Stop'), 'stop', 'background-sync hook');+ // the edit matcher must include Codex's native edit tool+ assert.match(cfg.hooks.PostToolUse[0].matcher, /apply_patch/);+ // Codex ignores matcher for these, so we omit it rather than write a dead field+ assert.ok(!('matcher' in cfg.hooks.UserPromptSubmit[0]), 'no matcher on UserPromptSubmit');+ assert.ok(!('matcher' in cfg.hooks.Stop[0]), 'no matcher on Stop');+const again = installCodexHooks(home);- assert.deepEqual(again.map((x) => x.action), ['unchanged', 'unchanged']);- assert.equal(JSON.parse(readFileSync(join(home, '.codex', 'hooks.json'), 'utf8')).hooks.PostToolUse.length, 1);+ assert.deepEqual(again.map((x) => x.action), ['unchanged', 'unchanged'], 'idempotent');+ const after = JSON.parse(readFileSync(join(home, '.codex', 'hooks.json'), 'utf8'));+ for (const ev of ['SessionStart', 'UserPromptSubmit', 'PostToolUse', 'Stop'])+ assert.equal(after.hooks[ev].length, 1, `${ev} not duplicated on re-run`);});test('foreign hook entries are preserved; stale graft entries replaced', () => {@@ -55,9 +67,27 @@ test('foreign hook entries are preserved; stale graft entries replaced', () => {installCodexHooks(home);const entries = JSON.parse(readFileSync(join(home, '.codex', 'hooks.json'), 'utf8')).hooks.PostToolUse;assert.equal(entries.length, 2, 'foreign kept, stale graft replaced by fresh');- assert.ok(entries.some((e: any) => e.hooks[0].command === 'other-tool'));- assert.ok(entries.some((e: any) => /post-edit-sync/.test(JSON.stringify(e))));- assert.ok(!JSON.stringify(entries).includes('/old/'));+ assert.ok(entries.some((e: any) => e.hooks[0].command === 'other-tool'), 'foreign entry preserved');+ assert.ok(entries.some((e: any) => /graft-hooks\.cjs" post-edit$/.test(e.hooks[0].command)), 'fresh graft entry present');+ assert.ok(!JSON.stringify(entries).includes('/old/'), 'stale graft entry removed');+});++test('editedFilePath reads the touched file from BOTH host edit-tool shapes', () => {+ const dir = '/repo';+ // Claude Code: Write/Edit state the absolute path directly+ assert.equal(+ editedFilePath({ tool_input: { file_path: '/repo/src/a.ts' } }, dir),+ '/repo/src/a.ts',+ );+ // Codex: apply_patch names the file (repo-relative) in the patch header → resolved absolute+ const patch = '*** Begin Patch\n*** Update File: src/b.ts\n@@\n-old\n+new\n*** End Patch';+ assert.equal(editedFilePath({ tool_input: { command: patch } }, dir), join(dir, 'src/b.ts'));+ // an Add File header works too+ const add = '*** Begin Patch\n*** Add File: pkg/new.rs\n+content\n*** End Patch';+ assert.equal(editedFilePath({ tool_input: { command: add } }, dir), join(dir, 'pkg/new.rs'));+ // neither shape present → null (hook stays a clean no-op)+ assert.equal(editedFilePath({ tool_input: {} }, dir), null);+ assert.equal(editedFilePath({}, dir), null);});test('unparseable hooks.json is never rewritten', () => {