Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes (#8424)

garrytan3912a33cbd15
diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.ts
index efd488b94b..11e0a6f491 100644
--- a/src/commands/doctor/checks/harness-wiring.ts
+++ b/src/commands/doctor/checks/harness-wiring.ts
@@ -523,17 +523,23 @@ export function hookLauncherFix(p: HookLauncherProblem): Action {
const why = "Rewrites gbrain's hooks to start gbrain from its own launcher directory, so a repository's bunfig.toml or .env never runs when a session opens there. `gbrain post-upgrade` refreshes the user-scope hooks too.";
const verify = doctorVerify(NAME);
if (p.reason === 'foreign') return { consent: [], actor: 'user', requires_exclusive: false, verify, why, user_message: `${p.detail}. Remove that file (gbrain did not write it), then run: ${argv.join(' ')}` };
+ if (p.edited) return { consent: [], actor: 'user', requires_exclusive: false, verify, why, user_message: `${p.detail}. Remove or rewrite that entry in ${p.source} (setup never overwrites an edit), then run: ${argv.join(' ')}` };
if (project) return { consent: [], actor: 'user', requires_exclusive: false, verify, why, user_message: `gbrain's hooks for ${project} start gbrain in the session's directory. From ${project}, run: ${argv.join(' ')}` };
return { argv, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify, why };
}
-/** A hook that lets the session directory's bunfig.toml or .env load turns an ok or warn check into a warn (code hook_session_cwd). */
+/**
+ * A hook that lets the session directory's bunfig.toml or .env load turns an ok
+ * check into a warn (code hook_session_cwd). A warn keeps its own code and fix
+ * unless the launcher fix is one the agent can run.
+ */
export function withHookLaunchers(check: Check, problem: HookLauncherProblem | null): Check {
if (!problem) return check;
const message = `${check.message} Hook launcher: ${problem.detail}.`;
const details = { ...(check.details ?? {}), hook_launcher: problem };
- if (check.status === 'fail') return { ...check, message, details };
- return { name: NAME, status: 'warn', message, details: { ...details, code: 'hook_session_cwd', hook_launcher_reason: problem.reason }, fix: hookLauncherFix(problem) };
+ const fix = hookLauncherFix(problem);
+ if (check.status === 'fail' || (check.status === 'warn' && check.fix && fix.actor !== 'agent')) return { ...check, message, details: { ...details, hook_launcher_fix: fix } };
+ return { name: NAME, status: 'warn', message, details: { ...details, code: 'hook_session_cwd', hook_launcher_reason: problem.reason }, fix };
}
/** Registration read (full run) or registration read + smoke (`--only harness_wiring`), plus the brain-first block, its per-turn hook and the hook launcher. */
diff --git a/src/core/setup/hook-launcher-refresh.ts b/src/core/setup/hook-launcher-refresh.ts
index a90151e394..24ceaf809a 100644
--- a/src/core/setup/hook-launcher-refresh.ts
+++ b/src/core/setup/hook-launcher-refresh.ts
@@ -89,8 +89,12 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {
const plan: ClaudeSetupPlan = { name: receipt.name, scope: receipt.scope, launcher: receipt.launcher, brainHome: receipt.gbrain_home, ...(homeEnv ? { gbrainHomeEnv: homeEnv } : {}),
sourceId: receipt.source_id, surface: receipt.surface, advertise: receipt.advertise ?? null, events: Object.keys({ ...receipt.hooks.owned, ...receipt.hooks.pending }) as ClaudeHookEvent[] };
if (!receipt.mcp_plugin && inspectClaudeSetup(plan).mcp.state !== 'current') { log(`Hook launcher: gbrain's claude-code hooks start gbrain in the session's directory; run ${rerun} to rewrite them.`); continue; }
- await applyClaudeSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false });
- log(`Hook launcher: gbrain setup's claude-code hooks in ${paths.settingsPath} now start gbrain from its own directory.`);
+ const applied = await applyClaudeSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false });
+ const edited = new Set(Object.values(applied.edited));
+ const kept = Object.keys(applied.edited);
+ log(claudeHookEntries(paths.settingsPath).some((e) => edited.has(hookEntryHash(e) ?? '') && needsLauncher(e.command as string))
+ ? `Hook launcher: gbrain setup's claude-code ${kept.join(', ')} hook in ${paths.settingsPath} was edited after setup wrote it, so it is kept as is and still starts gbrain in the session's directory; remove or rewrite it, then run ${rerun}.`
+ : `Hook launcher: gbrain setup's claude-code hooks in ${paths.settingsPath} now start gbrain from its own directory.`);
} else if (record.harness === 'codex') {
const receipt = readCodexSetupReceipt(record.path).setup;
if (!receipt) continue;
@@ -100,8 +104,12 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {
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[] };
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; }
- await applyCodexSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false });
- log(`Hook launcher: gbrain setup's codex hooks in ${paths.hooksPath} now start gbrain from its own directory.`);
+ const applied = await applyCodexSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false });
+ const edited = new Set(Object.values(applied.receipt.hooks.edited));
+ const kept = applied.preserved.filter((p) => p.kind === 'hook' && p.reason === 'edited').map((p) => p.event);
+ log(codexHookCensus(paths.hooksPath).some((g) => edited.has(g.hash) && g.commands.some(needsLauncher))
+ ? `Hook launcher: gbrain setup's codex ${kept.join(', ')} hook in ${paths.hooksPath} was edited after setup wrote it, so it is kept as is and still starts gbrain in the session's directory; remove or rewrite it, then run ${rerun}.`
+ : `Hook launcher: gbrain setup's codex hooks in ${paths.hooksPath} now start gbrain from its own directory.`);
}
} catch (e) {
log(`Hook launcher: gbrain's ${record.harness} hooks were not refreshed (${(e as Error).message}); run ${rerun}.`);
diff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.ts
index 12ac606a01..81d200f77d 100644
--- a/src/core/setup/turn-hook-check.ts
+++ b/src/core/setup/turn-hook-check.ts
@@ -129,29 +129,37 @@ export interface HookLauncherProblem {
/** session_cwd: no launcher in the command; otherwise the launcher's state. */
reason: 'session_cwd' | Exclude<HookLauncherState, 'current'>;
detail: string;
+ /** A setup entry the user edited after setup wrote it: setup keeps it as is, so only the user can move it. */
+ edited?: boolean;
}
-/** The hook hashes Claude Code setup receipts own: Claude Code can drop the `_gbrain` marker on a rewrite, and setup owns its entries by hash. */
-function claudeSetupOwnedHashes(): Set<string> {
- const out = new Set<string>();
- for (const r of localSetupRecords().filter((x) => x.harness === 'claude-code')) {
- const hooks = (readJson(r.path) as { hooks?: { owned?: Record<string, unknown>; pending?: Record<string, unknown> } } | null)?.hooks;
- for (const h of [...Object.values(hooks?.owned ?? {}), ...Object.values(hooks?.pending ?? {})]) if (typeof h === 'string') out.add(h);
+/** The hook hashes a harness's setup receipts own and the ones they record as edited by the user: Claude Code can drop the `_gbrain` marker on a rewrite, and setup owns its entries by hash. */
+function setupReceiptHashes(harness: 'claude-code' | 'codex'): { owned: Set<string>; edited: Set<string> } {
+ const owned = new Set<string>();
+ const edited = new Set<string>();
+ for (const r of localSetupRecords().filter((x) => x.harness === harness)) {
+ const hooks = (readJson(r.path) as { hooks?: { owned?: Record<string, unknown>; pending?: Record<string, unknown>; edited?: Record<string, unknown> } } | null)?.hooks;
+ for (const h of [...Object.values(hooks?.owned ?? {}), ...Object.values(hooks?.pending ?? {})]) if (typeof h === 'string') owned.add(h);
+ for (const h of Object.values(hooks?.edited ?? {})) if (typeof h === 'string') edited.add(h);
}
- return out;
+ return { owned, edited };
}
-function claudeLaneCommands(path: string, setupOwned: Set<string>): Array<{ lane: 'setup' | 'turn-rule'; command: string }> {
+type LaneCommand = { lane: 'setup' | 'turn-rule'; command: string; edited?: boolean };
+
+function claudeLaneCommands(path: string, setup: { owned: Set<string>; edited: Set<string> }): LaneCommand[] {
const hooks = readJson(path)?.hooks;
if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) return [];
- const out: Array<{ lane: 'setup' | 'turn-rule'; command: string }> = [];
+ const out: LaneCommand[] = [];
for (const groups of Object.values(hooks as Record<string, unknown>)) {
if (!Array.isArray(groups)) continue;
for (const e of groups.flatMap((g) => (Array.isArray((g as { hooks?: unknown })?.hooks) ? (g as { hooks: unknown[] }).hooks : []))) {
if (!e || typeof e !== 'object' || typeof (e as Record<string, unknown>).command !== 'string') continue;
const entry = e as Record<string, unknown>;
+ const hash = hookEntryHash(entry) ?? '';
if (isTurnRuleEntry(entry)) out.push({ lane: 'turn-rule', command: entry.command as string });
- else if (entry[GBRAIN_HOOK_MARKER_KEY] === GBRAIN_SETUP_MARKER_VALUE || setupOwned.has(hookEntryHash(entry) ?? '')) out.push({ lane: 'setup', command: entry.command as string });
+ else if (setup.edited.has(hash)) out.push({ lane: 'setup', command: entry.command as string, edited: true });
+ else if (entry[GBRAIN_HOOK_MARKER_KEY] === GBRAIN_SETUP_MARKER_VALUE || setup.owned.has(hash)) out.push({ lane: 'setup', command: entry.command as string });
}
}
return out;
@@ -159,27 +167,29 @@ function claudeLaneCommands(path: string, setupOwned: Set<string>): Array<{ lane
/** Files only. Every event's setup and turn-rule entries, user scope plus `projectDir`'s settings.local.json (Claude Code). */
export function hookLauncherProblem(harness: 'claude-code' | 'codex', opts: { projectDir?: string } = {}): HookLauncherProblem | null {
- const found: Array<{ lane: 'setup' | 'turn-rule'; command: string; source: string }> = [];
+ const found: Array<LaneCommand & { source: string }> = [];
+ const setup = setupReceiptHashes(harness);
if (harness === 'claude-code') {
- const setupOwned = claudeSetupOwnedHashes();
for (const source of [claudeUserSettingsPath(), ...(opts.projectDir ? [join(opts.projectDir, CLAUDE_SETTINGS_FILE_RELPATH)] : [])]) {
- found.push(...claudeLaneCommands(source, setupOwned).map((c) => ({ ...c, source })));
+ found.push(...claudeLaneCommands(source, setup).map((c) => ({ ...c, source })));
}
} else {
try {
for (const g of codexHookCensus(codexHooksPath())) {
- if (g.lane === 'setup' || g.lane === 'turn-rule') found.push(...g.commands.map((command) => ({ lane: g.lane as 'setup' | 'turn-rule', command, source: codexHooksPath() })));
+ if (g.lane === 'setup' || g.lane === 'turn-rule') found.push(...g.commands.map((command) => ({ lane: g.lane as 'setup' | 'turn-rule', command, source: codexHooksPath(), ...(setup.edited.has(g.hash) ? { edited: true } : {}) })));
}
} catch { /* unparseable: Codex runs none of it */ }
}
for (const f of found) {
const launcher = hookLauncherInCommand(f.command);
+ const edited = f.edited ? { edited: true } : {};
+ const kept = f.edited ? '; it was edited after setup wrote it, so setup keeps it as is' : '';
if (!launcher) {
- return { harness, lane: f.lane, source: f.source, reason: 'session_cwd',
- detail: `gbrain's ${f.lane} hook in ${f.source} starts gbrain in the session's directory, so Bun loads that directory's bunfig.toml and .env before gbrain runs` };
+ return { harness, lane: f.lane, source: f.source, reason: 'session_cwd', ...edited,
+ detail: `gbrain's ${f.lane} hook in ${f.source} starts gbrain in the session's directory, so Bun loads that directory's bunfig.toml and .env before gbrain runs${kept}` };
}
const s = hookLauncherState(launcher);
- if (s.state !== 'current') return { harness, lane: f.lane, source: f.source, reason: s.state, detail: `gbrain's ${f.lane} hook in ${f.source} runs through ${launcher}, but ${s.detail}` };
+ if (s.state !== 'current') return { harness, lane: f.lane, source: f.source, reason: s.state, ...edited, detail: `gbrain's ${f.lane} hook in ${f.source} runs through ${launcher}, but ${s.detail}${kept}` };
}
return null;
}
diff --git a/test/hook-launcher-bunfig.test.ts b/test/hook-launcher-bunfig.test.ts
index f07e96d05e..8386dbadb9 100644
--- a/test/hook-launcher-bunfig.test.ts
+++ b/test/hook-launcher-bunfig.test.ts
@@ -18,6 +18,8 @@ import { syncTurnRuleHook, TURN_RULE_MARKER } from '../src/core/setup/turn-hook.
import { hookLauncherProblem } from '../src/core/setup/turn-hook-check.ts';
import { HOOK_LAUNCHER_NAME, ensureHookLauncher, hookLauncherInCommand, hookLauncherPath, hookLauncherState } from '../src/core/setup/hook-launcher.ts';
import { refreshHookLaunchers } from '../src/core/setup/hook-launcher-refresh.ts';
+import { hookLauncherFix, withHookLaunchers } from '../src/commands/doctor/checks/harness-wiring.ts';
+import type { HookLauncherProblem } from '../src/core/setup/turn-hook-check.ts';
const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');
const roots: string[] = [];
@@ -230,3 +232,44 @@ describe('hooks written before the launcher: doctor flags them, post-upgrade mov
});
});
});
+
+describe('doctor: the hook_session_cwd fix and how it joins the harness_wiring check', () => {
+ const problem = (b: Box, over: Partial<HookLauncherProblem> = {}): HookLauncherProblem =>
+ ({ harness: 'claude-code', lane: 'setup', source: join(b.home, '.claude', 'settings.json'), reason: 'session_cwd', detail: 'old hook', ...over });
+
+ test('the fix: the agent re-runs setup for user scope; a project, a foreign file or an edited entry goes to the user', async () => {
+ const b = box();
+ await withEnv({ HOME: b.home, GBRAIN_HOME: b.home, CLAUDE_CONFIG_DIR: undefined }, async () => {
+ expect(hookLauncherFix(problem(b))).toMatchObject({ actor: 'agent', argv: ['gbrain', 'setup', 'claude-code'] });
+ expect(hookLauncherFix(problem(b, { lane: 'turn-rule' }))).toMatchObject({ actor: 'agent', argv: ['gbrain', 'setup', 'claude-code', '--instructions-only'] });
+ expect(hookLauncherFix(problem(b, { harness: 'codex', lane: 'turn-rule', source: join(b.home, '.codex', 'hooks.json') }))).toMatchObject({ actor: 'agent', argv: ['gbrain', 'setup', 'codex', '--instructions-only'] });
+ const project = join(b.root, 'proj');
+ const p = hookLauncherFix(problem(b, { source: join(project, '.claude', 'settings.local.json') }));
+ expect(p.actor).toBe('user');
+ expect(p.user_message).toContain(`From ${project}, run: gbrain setup claude-code --scope project`);
+ const foreign = hookLauncherFix(problem(b, { reason: 'foreign', detail: 'the launcher directory holds .env' }));
+ expect(foreign.actor).toBe('user');
+ expect(foreign.user_message).toContain('Remove that file (gbrain did not write it), then run: gbrain setup claude-code');
+ const edited = hookLauncherFix(problem(b, { edited: true }));
+ expect(edited.actor).toBe('user');
+ expect(edited.user_message).toContain('Remove or rewrite that entry');
+ });
+ });
+
+ test('withHookLaunchers: ok becomes a warn; a fail stays a fail; a warn keeps its own fix unless the agent can run the launcher fix', async () => {
+ const b = box();
+ await withEnv({ HOME: b.home, GBRAIN_HOME: b.home, CLAUDE_CONFIG_DIR: undefined }, async () => {
+ const ok = { name: 'harness_wiring', status: 'ok', message: 'Registered.' } as any;
+ expect(withHookLaunchers(ok, null)).toBe(ok);
+ const warned = withHookLaunchers(ok, problem(b));
+ expect(warned).toMatchObject({ status: 'warn', details: { code: 'hook_session_cwd', hook_launcher_reason: 'session_cwd' }, fix: { actor: 'agent' } });
+ const fail = withHookLaunchers({ ...ok, status: 'fail', details: { code: 'x' } }, problem(b));
+ expect(fail).toMatchObject({ status: 'fail', details: { code: 'x', hook_launcher_fix: { actor: 'agent' } } });
+ const prior = { ...ok, status: 'warn', details: { code: 'turn_hook_not_loaded' }, fix: { actor: 'agent', argv: ['gbrain', 'setup', 'claude-code', '--instructions-only'] } };
+ const kept = withHookLaunchers(prior, problem(b, { reason: 'foreign' }));
+ expect(kept).toMatchObject({ status: 'warn', details: { code: 'turn_hook_not_loaded', hook_launcher_fix: { actor: 'user' } }, fix: prior.fix });
+ expect(kept.message).toContain('Hook launcher: old hook.');
+ expect(withHookLaunchers(prior, problem(b))).toMatchObject({ details: { code: 'hook_session_cwd' }, fix: { actor: 'agent', argv: ['gbrain', 'setup', 'claude-code'] } });
+ });
+ });
+});
diff --git a/test/setup.test.ts b/test/setup.test.ts
index f1ea12d111..a8e19ffbe5 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -33,6 +33,8 @@ import { withEnv } from './helpers/with-env.ts';
import { ownedEntryFingerprint } from '../src/core/bootstrap/adopted-connections.ts';
import { hookLauncherProblem, inspectTurnHook } from '../src/core/setup/turn-hook-check.ts';
import { refreshHookLaunchers } from '../src/core/setup/hook-launcher-refresh.ts';
+import { syncTurnRuleHook, isTurnRuleEntry } from '../src/core/setup/turn-hook.ts';
+import { hookLauncherFix } from '../src/commands/doctor/checks/harness-wiring.ts';
const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');
const roots: string[] = [];
@@ -941,6 +943,48 @@ describe('hooks written before the hook launcher (#8424): the next setup and pos
expect(['SessionStart', 'UserPromptSubmit'].map((e) => entries(b, e).length)).toEqual([1, 1]);
});
+ test('claude-code: a pre-launcher hook the user edited is kept, post-upgrade says so, and doctor hands it to the user', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);
+ downgradeClaude(b);
+ const s = readJson(settings(b));
+ const mine = (s.hooks.UserPromptSubmit as any[]).flatMap((g) => g.hooks).find((e) => e._gbrain === 'setup-v1');
+ mine.command = `${mine.command} # mine`;
+ writeFileSync(settings(b), JSON.stringify(s, null, 2));
+ await withEnv(env(b), async () => {
+ const lines: string[] = [];
+ await refreshHookLaunchers((l) => lines.push(l));
+ expect(lines.join('\n')).toContain('UserPromptSubmit hook');
+ expect(lines.join('\n')).toContain('was edited after setup wrote it');
+ expect(lines.join('\n')).not.toContain('now start gbrain from its own directory');
+ const problem = hookLauncherProblem('claude-code');
+ expect(problem).toMatchObject({ lane: 'setup', reason: 'session_cwd', edited: true });
+ const fix = hookLauncherFix(problem!);
+ expect(fix.actor).toBe('user');
+ expect(fix.user_message).toContain('Remove or rewrite that entry');
+ });
+ expect(entries(b, 'UserPromptSubmit').find((e) => e._gbrain === 'setup-v1').command).toBe(mine.command);
+ expect(entries(b, 'SessionStart').every((e) => e.command.includes(launcher(b)))).toBe(true);
+ });
+
+ test('claude-code: --instructions-only moves a pre-launcher turn-rule entry that sits beside setup hooks', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);
+ await withEnv(env(b), async () => {
+ expect(syncTurnRuleHook({ harness: 'claude-code', gbrainBin: b.bin, gbrainHome: b.gbrainHome, rerun: 'gbrain setup claude-code --instructions-only' }).action).toBe('write');
+ });
+ const s = readJson(settings(b));
+ const turnRule = (s.hooks.UserPromptSubmit as any[]).flatMap((g) => g.hooks).find((e) => isTurnRuleEntry(e));
+ turnRule.command = turnRule.command.replace(` ${launcher(b)} `, ' ');
+ writeFileSync(settings(b), JSON.stringify(s, null, 2));
+ await withEnv(env(b), async () => { expect(hookLauncherProblem('claude-code')).toMatchObject({ lane: 'turn-rule', reason: 'session_cwd' }); });
+ expect((await setup(b, ['claude-code', '--instructions-only', '--json'])).exitCode).toBe(0);
+ const after = entries(b, 'UserPromptSubmit').filter((e) => isTurnRuleEntry(e));
+ expect(after).toHaveLength(1);
+ expect(after[0].command).toContain(`${launcher(b)} ${b.bin} hook`);
+ await withEnv(env(b), async () => { expect(hookLauncherProblem('claude-code')).toBeNull(); });
+ });
+
test('codex: post-upgrade rewrites them with matching trust, and a later setup keeps everything', async () => {
const b = box();
expect((await setup(b, ['codex', '--json'])).exitCode).toBe(0);