Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: post-upgrade moves gbrain setup's Codex hooks only when Codex runs every one (#8424)

garrytan02f7ab81f9ea
diff --git a/src/core/bootstrap/codex-hooks.ts b/src/core/bootstrap/codex-hooks.ts
index c0e2b7fc16..383924c4d2 100644
--- a/src/core/bootstrap/codex-hooks.ts
+++ b/src/core/bootstrap/codex-hooks.ts
@@ -443,14 +443,24 @@ export function codexHookCensus(hooksPath: string): CodexHookCensusGroup[] {
*/
export function codexHookGroupRuns(hooksPath: string, configPath: string, group: { event: string; index: number }): boolean {
if (group.event !== 'SessionStart' && group.event !== 'UserPromptSubmit') return false;
- const { stateName } = SETUP_EVENT_SPECS[group.event];
- const handlers = loadHooksJson(hooksPath).hooks[group.event]?.[group.index]?.hooks;
+ return groupHandlerRuns(hooksPath, configPath, group.event, group.index, (c) => c.includes(CODEX_SETUP_LANE_TOKEN) || CONTEXT_LANE_TOKENS.some((t) => c.includes(t)));
+}
+
+/** codexHookGroupRuns for setup's own groups, SessionEnd's capture group included (its handler carries setup's lane token). */
+export function codexSetupGroupRuns(hooksPath: string, configPath: string, group: { event: string; index: number }): boolean {
+ if (group.event !== 'SessionEnd') return codexHookGroupRuns(hooksPath, configPath, group);
+ return groupHandlerRuns(hooksPath, configPath, 'SessionEnd', group.index, (c) => c.includes(CODEX_SETUP_LANE_TOKEN));
+}
+
+function groupHandlerRuns(hooksPath: string, configPath: string, event: CodexSetupEvent, index: number, accepts: (command: string) => boolean): boolean {
+ const { stateName } = SETUP_EVENT_SPECS[event];
+ const handlers = loadHooksJson(hooksPath).hooks[event]?.[index]?.hooks;
if (!Array.isArray(handlers)) return false;
const states = readCodexTomlTable(configPath, ['hooks', 'state']) as Record<string, { enabled?: unknown; trusted_hash?: unknown } | undefined> | undefined;
return handlers.some((h, i) => {
const command = h?.command;
- if (typeof command !== 'string' || !(command.includes(CODEX_SETUP_LANE_TOKEN) || CONTEXT_LANE_TOKENS.some((t) => command.includes(t)))) return false;
- const state = states?.[`${hooksPath}:${stateName}:${group.index}:${i}`];
+ if (typeof command !== 'string' || !accepts(command)) return false;
+ const state = states?.[`${hooksPath}:${stateName}:${index}:${i}`];
if (!state || state.enabled === false) return false;
return state.trusted_hash === codexHookTrustHash(stateName, command, typeof h.timeout === 'number' ? Math.max(1, h.timeout) : 600);
});
diff --git a/src/core/setup/hook-launcher-refresh.ts b/src/core/setup/hook-launcher-refresh.ts
index 651294580c..03b29fac2b 100644
--- a/src/core/setup/hook-launcher-refresh.ts
+++ b/src/core/setup/hook-launcher-refresh.ts
@@ -18,7 +18,7 @@
import { readFileSync } from 'node:fs';
import { configDir } from '../config.ts';
import { hookEntryHash, parseClaudeHookCommand } from '../bootstrap/hooks.ts';
-import { codexHookCensus, codexHookGroupRuns, type CodexHookCensusGroup } from '../bootstrap/codex-hooks.ts';
+import { codexHookCensus, codexHookGroupRuns, codexSetupGroupRuns, type CodexHookCensusGroup } from '../bootstrap/codex-hooks.ts';
import { join } from 'node:path';
import { GBRAIN_HOOK_MARKER_KEY, GBRAIN_SETUP_MARKER_VALUE, claudeUserSettingsPath, codexConfigPath, codexHooksPath, type ClaudeHookEvent } from '../bootstrap/host-specs.ts';
import type { CodexSetupEvent } from '../bootstrap/codex-hooks.ts';
@@ -105,10 +105,14 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {
const receipt = readCodexSetupReceipt(record.path).setup;
if (!receipt) continue;
const paths = codexSetupPaths(receipt.name);
- const ours = codexHookCensus(paths.hooksPath).filter((g) => g.lane === 'setup').flatMap((g) => g.commands);
- if (!ours.some(needsLauncher)) continue;
+ const groups = codexHookCensus(paths.hooksPath).filter((g) => g.lane === 'setup');
+ if (!groups.flatMap((g) => g.commands).some(needsLauncher)) continue;
const plan: CodexSetupPlan = { name: receipt.name, launcher: receipt.launcher, brainHome: receipt.gbrain_home, ...(receipt.gbrain_home_env ? { gbrainHomeEnv: receipt.gbrain_home_env } : {}),
sourceId: receipt.source_id, surface: receipt.surface, advertise: receipt.advertise ?? null, events: Object.keys({ ...receipt.hooks.owned, ...receipt.hooks.pending }) as CodexSetupEvent[] };
+ // Rewriting re-trusts every setup group, so it runs only when Codex already runs each one: an untrusted, disabled or missing group keeps Codex's approval gate.
+ const runs = (g: CodexHookCensusGroup) => codexSetupGroupRuns(paths.hooksPath, paths.configPath, g);
+ const idle = [...new Set([...plan.events.filter((e) => !groups.some((g) => g.event === e && runs(g))), ...groups.filter((g) => !runs(g)).map((g) => g.event)])];
+ if (idle.length > 0) { log(`Hook launcher: Codex does not run gbrain setup's codex ${idle.join(', ')} hook in ${paths.hooksPath} (not trusted, disabled or removed), so setup's codex hooks are left as is; run ${rerun} to rewrite them.`); continue; }
if (!receipt.mcp_plugin && inspectCodexSetup(plan).mcp.state !== 'current') { log(`Hook launcher: gbrain's codex hooks start gbrain in the session's directory; run ${rerun} to rewrite them.`); continue; }
const applied = await applyCodexSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false, mcpMustBeCurrent: true });
const left = new Set(codexHookCensus(paths.hooksPath).filter((g) => g.commands.some(needsLauncher)).map((g) => g.hash));
diff --git a/test/hook-launcher-bunfig.test.ts b/test/hook-launcher-bunfig.test.ts
index e15709118d..0ae236e631 100644
--- a/test/hook-launcher-bunfig.test.ts
+++ b/test/hook-launcher-bunfig.test.ts
@@ -13,7 +13,7 @@ import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { withEnv } from './helpers/with-env.ts';
import { buildClaudeHookCommand } from '../src/core/bootstrap/hooks.ts';
-import { codexHookGroupRuns, codexHookTrustHash, codexSetupHookGroup } from '../src/core/bootstrap/codex-hooks.ts';
+import { codexHookGroupRuns, codexHookTrustHash, codexSetupGroupRuns, codexSetupHookGroup, codexSetupTrustEntry } from '../src/core/bootstrap/codex-hooks.ts';
import { appendCodexTomlTable } from '../src/core/bootstrap/codex-toml.ts';
import { captureHookSessionCwd, hookSessionCwd } from '../src/core/setup/hook-launcher.ts';
import { syncTurnRuleHook, TURN_RULE_MARKER } from '../src/core/setup/turn-hook.ts';
@@ -243,6 +243,21 @@ describe('hooks written before the launcher: doctor flags them, post-upgrade mov
expect(codexHookGroupRuns(hooks, config, { event: 'UserPromptSubmit', index: 0 })).toBe(false);
});
+ test("codex: setup's SessionEnd capture group runs only with its own trust entry", () => {
+ const b = box();
+ const hooks = join(b.home, '.codex', 'hooks.json');
+ const config = join(b.home, '.codex', 'config.toml');
+ const group = codexSetupHookGroup(b.gbrain, 'SessionEnd', {}, 'setup');
+ mkdirSync(dirname(hooks), { recursive: true });
+ writeFileSync(hooks, JSON.stringify({ hooks: { SessionEnd: [group] } }));
+ writeFileSync(config, '');
+ expect(codexSetupGroupRuns(hooks, config, { event: 'SessionEnd', index: 0 })).toBe(false);
+ const { key, trusted_hash } = codexSetupTrustEntry(hooks, 'SessionEnd', 0, group);
+ appendCodexTomlTable(config, ['hooks', 'state', key], { trusted_hash }, 'test: Codex trusted the capture hook');
+ expect(codexSetupGroupRuns(hooks, config, { event: 'SessionEnd', index: 0 })).toBe(true);
+ expect(codexHookGroupRuns(hooks, config, { event: 'SessionEnd', index: 0 })).toBe(false);
+ });
+
test('the recorded session directory is resolved and dropped from the environment', async () => {
const b = box();
const link = join(b.root, 'link-to-checkout');
diff --git a/test/setup.test.ts b/test/setup.test.ts
index 3fa9f057a0..40e869f345 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -1016,4 +1016,20 @@ describe('hooks written before the hook launcher (#8424): the next setup and pos
expect(viaLauncher(b, codexSetupCommands(b))).toBe(true);
expect((await setup(b, ['codex', '--json'])).doc.steps.map((s: any) => s.action)).toEqual(['keep', 'keep', 'keep', 'keep']);
});
+
+ test('codex: post-upgrade leaves setup groups Codex does not run as is, so it grants no trust', async () => {
+ const b = box();
+ expect((await setup(b, ['codex', '--json'])).exitCode).toBe(0);
+ downgradeCodex(b);
+ for (const rec of Object.values(readJson(codexReceipt(b)).trust.owned) as Array<{ key: string }>) removeCodexTomlTable(codexToml(b), ['hooks', 'state', rec.key]);
+ const before = { hooks: readFileSync(hooksJson(b), 'utf8'), config: readFileSync(codexToml(b), 'utf8') };
+ await withEnv(env(b), async () => {
+ const lines: string[] = [];
+ await refreshHookLaunchers((l) => lines.push(l));
+ expect(lines.join('\n')).toContain("Codex does not run gbrain setup's codex SessionStart, UserPromptSubmit hook");
+ expect(lines.join('\n')).not.toContain('now start gbrain from its own directory');
+ expect(hookLauncherProblem('codex')).toMatchObject({ lane: 'setup', reason: 'session_cwd' });
+ });
+ expect({ hooks: readFileSync(hooksJson(b), 'utf8'), config: readFileSync(codexToml(b), 'utf8') }).toEqual(before);
+ });
});