Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Skill resolver on Codex: offer skills again after a compaction

garrytan5b7e2de80e54
diff --git a/src/core/setup/skill-resolver-hook.ts b/src/core/setup/skill-resolver-hook.ts
index a3498ceffb..9a499f4d71 100644
--- a/src/core/setup/skill-resolver-hook.ts
+++ b/src/core/setup/skill-resolver-hook.ts
@@ -11,8 +11,11 @@
* SessionStart (`hook session-start`, which only resets a session's
* dedupe state after a compaction).
* - Codex: its own UserPromptSubmit group in CODEX_HOME/hooks.json
- * (`hook user-prompt --harness codex`), trusted by its hash in
- * config.toml beside it, like the turn-rule lane.
+ * (`hook user-prompt --harness codex`) and its own SessionStart group
+ * (`hook session-start --harness codex`, the same compaction reset:
+ * Codex sends SessionStart with source "compact" after it compacts),
+ * each trusted by its hash in config.toml beside it, like the turn-rule
+ * lane.
*
* Both run gbrain through the existing hook launcher (hook-launcher.ts); this
* module writes nothing else into the launcher's directory. Ownership: the
@@ -22,7 +25,7 @@
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';
-import { codexHookCensus, codexHookTrustHash, codexSetupHookGroup, codexSetupTrustEntry, writeCodexSetupHooks, type CodexHookGroup } from '../bootstrap/codex-hooks.ts';
+import { codexHookCensus, codexHookGroupRuns, codexSetupHookGroup, codexSetupTrustEntry, writeCodexSetupHooks, type CodexHookGroup } from '../bootstrap/codex-hooks.ts';
import { appendCodexTomlTable, readCodexTomlTable, removeCodexTomlTable } from '../bootstrap/codex-toml.ts';
import { buildClaudeHookCommand, hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../bootstrap/hooks.ts';
import { CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS, claudeUserSettingsPath, codexConfigPath, codexHooksPath, type ClaudeHookEvent } from '../bootstrap/host-specs.ts';
@@ -32,7 +35,9 @@ import { isSkillResolverCommand, isSkillResolverEntry, SKILL_RESOLVER_LANE, SKIL
export type ResolverHarness = 'claude-code' | 'codex';
const CLAUDE_EVENTS: ClaudeHookEvent[] = ['UserPromptSubmit', 'SessionStart'];
-const TRUST_STATE = 'user_prompt_submit';
+const CODEX_EVENTS = ['UserPromptSubmit', 'SessionStart'] as const;
+type CodexEvent = (typeof CODEX_EVENTS)[number];
+const CODEX_TIMEOUT_SECS = 15;
export interface ResolverHookPaths { claudeSettings?: string; codexHooks?: string; codexConfig?: string; hookLauncher?: string }
export interface ResolverHookOutcome { action: 'write' | 'keep' | 'remove' | 'skip' | 'refuse'; path: string; detail: string }
@@ -51,16 +56,18 @@ function claudeOurs(path: string): Array<{ event: string; entry: Record<string,
}
function codexOurs(p: { hooks: string }) {
- return codexHookCensus(p.hooks).filter((g) => g.event === 'UserPromptSubmit' && g.commands.some(isSkillResolverCommand));
+ return codexHookCensus(p.hooks).filter((g) => (CODEX_EVENTS as readonly string[]).includes(g.event) && g.commands.some(isSkillResolverCommand)) as Array<ReturnType<typeof codexHookCensus>[number] & { event: CodexEvent }>;
}
-export function codexResolverGroup(bin: string, home: string | undefined, launcher: string): CodexHookGroup {
- return codexSetupHookGroup(bin, 'UserPromptSubmit', home ? { GBRAIN_HOME: home } : {}, SKILL_RESOLVER_LANE, launcher);
+export function codexResolverGroup(bin: string, home: string | undefined, launcher: string, event: CodexEvent = 'UserPromptSubmit'): CodexHookGroup {
+ return codexSetupHookGroup(bin, event, home ? { GBRAIN_HOME: home } : {}, SKILL_RESOLVER_LANE, launcher);
}
+const codexTrusted = (p: { hooks: string; config: string }, g: { event: CodexEvent; index: number }) => codexHookGroupRuns(p.hooks, p.config, g);
+
/** The commands this install's lane runs (what the hook entries would hold). */
export function skillResolverCommands(harness: ResolverHarness, bin: string, home: string | undefined, launcher: string): string[] {
- if (harness === 'codex') return codexResolverGroup(bin, home, launcher).hooks.map((h) => h.command);
+ if (harness === 'codex') return CODEX_EVENTS.flatMap((e) => codexResolverGroup(bin, home, launcher, e).hooks.map((h) => h.command));
return CLAUDE_EVENTS.map((e) => buildClaudeHookCommand(bin, e, laneEnv(home), launcher));
}
@@ -70,11 +77,8 @@ export function inspectSkillResolverHook(harness: ResolverHarness, paths: Resolv
if (harness === 'codex') {
const p = codexPaths(paths);
const ours = codexOurs(p);
- if (ours.length === 0) return { state: 'absent', path: p.hooks, commands: [] };
- const g = ours[0]!;
- const table = readCodexTomlTable(p.config, ['hooks', 'state', `${p.hooks}:${TRUST_STATE}:${g.index}:0`]) as { trusted_hash?: unknown; enabled?: unknown } | undefined;
- const trusted = table?.enabled !== false && table?.trusted_hash === codexHookTrustHash(TRUST_STATE, g.commands[0]!, 15);
- return { state: trusted ? 'wired' : 'untrusted', path: p.hooks, commands: g.commands };
+ if (!ours.some((g) => g.event === 'UserPromptSubmit')) return { state: 'absent', path: p.hooks, commands: [] };
+ return { state: ours.every((g) => codexTrusted(p, g)) ? 'wired' : 'untrusted', path: p.hooks, commands: ours.flatMap((g) => g.commands) };
}
const path = claudePath(paths);
const ours = claudeOurs(path);
@@ -110,33 +114,34 @@ function syncClaude(bin: string, home: string | undefined, launcher: string, pat
const trustPath = (key: string) => ['hooks', 'state', key];
+/** Drop the trust entries of our groups, each only while it still trusts one of our commands. */
function dropOurTrust(config: string, hooks: string, ours: ReturnType<typeof codexOurs>): void {
const commands = ours.flatMap((g) => g.commands);
for (const g of ours) {
- const key = `${hooks}:${TRUST_STATE}:${g.index}:0`;
- const table = readCodexTomlTable(config, trustPath(key)) as { trusted_hash?: unknown } | undefined;
- if (table && commands.some((c) => codexHookTrustHash(TRUST_STATE, c, 15) === table.trusted_hash)) removeCodexTomlTable(config, trustPath(key));
+ const entries = commands.map((command) => codexSetupTrustEntry(hooks, g.event, g.index, { hooks: [{ type: 'command', command, timeout: CODEX_TIMEOUT_SECS }] }));
+ const table = readCodexTomlTable(config, trustPath(entries[0]!.key)) as { trusted_hash?: unknown } | undefined;
+ if (table && entries.some((t) => t.trusted_hash === table.trusted_hash)) removeCodexTomlTable(config, trustPath(entries[0]!.key));
}
}
function syncCodex(bin: string, home: string | undefined, launcher: string, p: { hooks: string; config: string }, dryRun: boolean): ResolverHookOutcome {
- const group = codexResolverGroup(bin, home, launcher);
- const hash = ownedEntryFingerprint(group);
+ const groups = Object.fromEntries(CODEX_EVENTS.map((e) => [e, codexResolverGroup(bin, home, launcher, e)])) as Record<CodexEvent, CodexHookGroup>;
const ours = codexOurs(p);
- const detail = `skill-resolver lane hook (UserPromptSubmit) in ${p.hooks}, trusted in ${p.config}`;
- const current = ours.length === 1 && ours[0]!.hash === hash;
- const entry = codexSetupTrustEntry(p.hooks, 'UserPromptSubmit', current ? ours[0]!.index : 0, group);
- if (current && (readCodexTomlTable(p.config, trustPath(entry.key)) as { trusted_hash?: unknown } | undefined)?.trusted_hash === entry.trusted_hash) return { action: 'keep', path: p.hooks, detail };
+ const detail = `skill-resolver lane hooks (UserPromptSubmit, SessionStart) in ${p.hooks}, trusted in ${p.config}`;
+ const current = ours.length === CODEX_EVENTS.length && CODEX_EVENTS.every((e) => ours.some((g) => g.event === e && g.hash === ownedEntryFingerprint(groups[e]) && codexTrusted(p, g)));
+ if (current) return { action: 'keep', path: p.hooks, detail };
if (dryRun) return { action: 'write', path: p.hooks, detail };
mkdirSync(dirname(p.hooks), { recursive: true, mode: 0o700 });
dropOurTrust(p.config, p.hooks, ours);
- const w = writeCodexSetupHooks(p.hooks, { want: { UserPromptSubmit: group }, owned: new Set(ours.map((g) => g.hash)), preserve: new Set() });
- const index = w.indexes.UserPromptSubmit;
- if (index === undefined) return { action: 'refuse', path: p.hooks, detail: `${p.hooks} did not take the skill-resolver hook` };
- const trust = codexSetupTrustEntry(p.hooks, 'UserPromptSubmit', index, group);
- const existing = readCodexTomlTable(p.config, trustPath(trust.key)) as { trusted_hash?: unknown } | undefined;
- if (existing === undefined) appendCodexTomlTable(p.config, trustPath(trust.key), { trusted_hash: trust.trusted_hash }, 'gbrain setup (skill-resolver): trusts the skill-resolver lane hook; owned by its hash');
- else if (existing.trusted_hash !== trust.trusted_hash) return { action: 'refuse', path: p.hooks, detail: `${p.config} already has a different [hooks.state."${trust.key}"]; trust gbrain's skill-resolver hook in Codex's /hooks` };
+ const w = writeCodexSetupHooks(p.hooks, { want: groups, owned: new Set(ours.map((g) => g.hash)), preserve: new Set() });
+ for (const event of CODEX_EVENTS) {
+ const index = w.indexes[event];
+ if (index === undefined) return { action: 'refuse', path: p.hooks, detail: `${p.hooks} did not take the skill-resolver ${event} hook` };
+ const trust = codexSetupTrustEntry(p.hooks, event, index, groups[event]);
+ const existing = readCodexTomlTable(p.config, trustPath(trust.key)) as { trusted_hash?: unknown } | undefined;
+ if (existing === undefined) appendCodexTomlTable(p.config, trustPath(trust.key), { trusted_hash: trust.trusted_hash }, `gbrain setup (skill-resolver): trusts the skill-resolver lane ${event} hook; owned by its hash`);
+ else if (existing.trusted_hash !== trust.trusted_hash) return { action: 'refuse', path: p.hooks, detail: `${p.config} already has a different [hooks.state."${trust.key}"]; trust gbrain's skill-resolver hook in Codex's /hooks` };
+ }
return { action: 'write', path: p.hooks, detail };
}
@@ -151,7 +156,7 @@ export function removeSkillResolverHook(opts: { harness: ResolverHarness; paths?
dropOurTrust(p.config, p.hooks, ours);
writeCodexSetupHooks(p.hooks, { want: {}, owned: new Set(ours.map((g) => g.hash)), preserve: new Set() });
}
- return { action: 'remove', path: p.hooks, detail: `skill-resolver lane hook from ${p.hooks} and its trust entry from ${p.config}` };
+ return { action: 'remove', path: p.hooks, detail: `skill-resolver lane hooks from ${p.hooks} and their trust entries from ${p.config}` };
}
const path = claudePath(paths);
const ours = claudeOurs(path);
diff --git a/src/core/skills/resolver/hook-lane.ts b/src/core/skills/resolver/hook-lane.ts
index f1675baa57..4332a3f507 100644
--- a/src/core/skills/resolver/hook-lane.ts
+++ b/src/core/skills/resolver/hook-lane.ts
@@ -1,7 +1,7 @@
/**
* The skill-resolver hook lane (`GBRAIN_HOOK_LANE=skill-resolver`): its own
- * hook entry in Claude Code (UserPromptSubmit, plus SessionStart for the
- * compaction reset) and its own hooks.json group in Codex (UserPromptSubmit),
+ * hook entry in Claude Code and its own hooks.json groups in Codex, each
+ * UserPromptSubmit plus SessionStart for the compaction reset,
* written by `gbrain setup <claude-code|codex> --skill-loading resolve`
* (src/core/setup/skill-resolver-hook.ts). It never shares output with the
* turn-rule, setup or plugin lanes: it prints only the <relevant_skills> block.
@@ -213,7 +213,6 @@ interface Turn { outcome: string; code?: string; catalogs?: string[]; dropped_ch
export async function runSkillResolverLane(event: string, harness: LaneHarness, io: LaneIo = {}): Promise<number> {
const t0 = performance.now();
if (event !== 'user-prompt' && event !== 'session-start') return 0;
- if (harness === 'codex' && event !== 'user-prompt') return 0;
const env = io.env ?? process.env;
let home: string;
try { home = resolverHome(env); } catch { return 0; }
diff --git a/test/setup-skill-resolver.test.ts b/test/setup-skill-resolver.test.ts
index 9a78e024bb..40c0e3b4b4 100644
--- a/test/setup-skill-resolver.test.ts
+++ b/test/setup-skill-resolver.test.ts
@@ -117,7 +117,7 @@ for (const harness of ['claude-code', 'codex'] as H[]) {
expect(JSON.parse(read(configPath(b))!)).toEqual({ skills: { resolver: { enabled: true, harnesses: [harness] } } });
expect(catalogs(b)).toEqual([`${harness}-user`]);
const hooks = read(HARNESS[harness].hookFile(b))!;
- expect(hooks.split('GBRAIN_HOOK_LANE=skill-resolver').length - 1).toBe(harness === 'codex' ? 1 : 2);
+ expect(hooks.split('GBRAIN_HOOK_LANE=skill-resolver').length - 1).toBe(2);
if (harness === 'claude-code') expect(hooks).toContain(SKILL_RESOLVER_MARKER);
else expect(read(join(b.home, '.codex', 'config.toml'))).toContain('skill-resolver');
const launcherDir = join(gb(b), 'hook-launcher');
diff --git a/test/skill-resolver-hook-lane.test.ts b/test/skill-resolver-hook-lane.test.ts
index 86fdeb4b76..2e6fff3aec 100644
--- a/test/skill-resolver-hook-lane.test.ts
+++ b/test/skill-resolver-hook-lane.test.ts
@@ -141,6 +141,27 @@ describe('skill-resolver lane: delivery per harness', () => {
expect(reset.stdout).toBe('');
expect(contextOf(await hook(b, cmd, turn, WIDE))).toContain('triage-bug');
});
+
+ test('codex SessionStart after a compaction (Codex 0.165 sends source "compact") resets the session, so the skill is offered again', async () => {
+ const b = box();
+ seedSkills(codexSkills(b));
+ await setup(b, 'codex');
+ const cmd = wired(b, 'codex');
+ const start = wired(b, 'codex', 'SessionStart');
+ expect(start).toContain('hook session-start --harness codex');
+ const toml = readFileSync(join(b.home, '.codex', 'config.toml'), 'utf8');
+ expect(toml).toContain(':session_start:');
+ expect(toml).toContain(':user_prompt_submit:');
+ const turn = { prompt: 'triage this bug report', session_id: 'sess-cx', hook_event_name: 'UserPromptSubmit' };
+ expect(contextOf(await hook(b, cmd, turn, WIDE))).toContain('triage-bug');
+ expect((await hook(b, cmd, turn, WIDE)).stdout).toBe('');
+ expect((await hook(b, start, { source: 'resume', session_id: 'sess-cx', hook_event_name: 'SessionStart' }, WIDE)).stdout).toBe('');
+ expect((await hook(b, cmd, turn, WIDE)).stdout).toBe('');
+ const reset = await hook(b, start, { source: 'compact', session_id: 'sess-cx', hook_event_name: 'SessionStart' }, WIDE);
+ expect(reset.exitCode).toBe(0);
+ expect(reset.stdout).toBe('');
+ expect(contextOf(await hook(b, cmd, turn, WIDE))).toContain('triage-bug');
+ });
});
describe('skill-resolver lane: deadline, measured outside the process', () => {