Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(security): review round 2 for #8437

garrytan4008ffd9bd00
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b00df1374a..8cf49dccc2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,7 @@ identifiers and attribution are available in the pre-removal Git revision
- The hooks from `gbrain bootstrap hooks` (the workspace lane), `gbrain bootstrap harness` and the Codex `SessionEnd` capture both write now start gbrain through the launcher too, and the gbrain plugins' per-turn hook changes into the plugin directory before it starts gbrain. The plugin hook now needs gbrain 0.60.547.0 or newer (it exits silently on an older CLI, which would read the plugin directory as the session's).
- `gbrain post-upgrade` moves a user-scope `gbrain setup claude-code` MCP entry setup still owns onto the launcher, checking it again under setup's lock. It rewrites no Codex entry, the turn-rule hook included (a rewrite recomputes the trust of every install's groups in the shared hooks.json): for `gbrain setup codex`'s MCP table and hooks it prints the `gbrain setup codex` command, and for every `gbrain bootstrap` entry the bootstrap command that rewrites it, run from the workspace. An entry you edited after setup wrote it is kept and named, and the refresh stops when another install replaced the receipt it planned from.
-- `gbrain doctor` (`harness_wiring`, `hook_session_cwd`) now also covers the stdio MCP entries and the bootstrap, harness and Codex capture lanes, with the command that fixes each; only a user-scope entry setup owns gets an agent-runnable fix, and it carries the install's recorded `--no-hooks` and `--source`, so the rerun turns nothing on.
+- `gbrain doctor` (`harness_wiring`, `hook_session_cwd`) now also covers the stdio MCP entries and the bootstrap, harness and Codex capture lanes, with the command that fixes each. Only a user-scope Claude Code entry setup owns gets an agent-runnable fix: it reruns the install that owns the entry with its recorded `--no-hooks` and `--source`, so the rerun turns nothing on. Every `gbrain setup codex` rerun is now the user's to run, because it rewrites the shared hooks.json and its trust.
- `gbrain hook`'s git probes run with `-c core.fsmonitor=false`, and a session outside the workspace the install receipt names runs no git at all, so a `.git/config` from an extracted archive or shared folder cannot run a command at session start.
- The readiness fix for an unwired Claude Code or Codex now names `gbrain setup <harness> --no-hooks` instead of `claude mcp add` / `codex mcp add`, so the entry it writes goes through the launcher; it also writes the brain-first block and records hooks as off. The install docs now teach `gbrain setup claude-code` / `gbrain setup codex` instead of a bare stdio `mcp add`. A project-scope `.mcp.json` and committed `.claude/settings.json` hooks stay PATH-resolved: they belong to the repository.
diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.ts
index 9d934d0474..2d754c0f05 100644
--- a/src/commands/doctor/checks/harness-wiring.ts
+++ b/src/commands/doctor/checks/harness-wiring.ts
@@ -524,23 +524,27 @@ export function hookLauncherProblems(views: InstructionBlockView[]): HookLaunche
export function hookLauncherFix(p: HookLauncherProblem): Action {
const project = p.harness === 'claude-code' && p.source !== claudeUserSettingsPath() ? dirname(dirname(p.source)) : null;
const setupHarness = p.lane === 'setup' && p.harness !== 'opencode' ? p.harness : null;
- const record = setupHarness ? localSetupRecords().find((r) => r.harness === setupHarness && r.status === 'installed' && (project ? r.projectDir === project : r.scope !== 'project')) : undefined;
+ const record = setupHarness ? localSetupRecords().find((r) => r.harness === setupHarness && r.status === 'installed' && (p.receiptPath ? r.path === p.receiptPath : project ? r.projectDir === project : r.scope !== 'project')) : undefined;
const receipt = record && (() => { try { return (setupHarness === 'claude-code' ? readSetupReceipt(record.path) : readCodexSetupReceipt(record.path)).setup; } catch { return null; } })();
const argv = receipt && setupHarness ? setupRerunArgv(setupHarness, receipt, project ?? undefined)
: ['gbrain', 'setup', p.harness, ...(p.lane === 'turn-rule' ? ['--instructions-only'] : []), ...(record && record.name !== 'gbrain' ? ['--name', record.name] : []), ...(project ? ['--scope', 'project'] : [])];
- 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, except `gbrain setup codex`'s.";
+ 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 Claude Code's user-scope setup hooks too; it never rewrites a Codex file.";
+ // gbrain setup codex rewrites the shared hooks.json and recomputes its trust, which can re-enable or newly trust a group, so only the user runs it.
+ const codexTrust = '`gbrain setup codex` rewrites the Codex hooks.json and its trust entries, so run it yourself';
const verify = doctorVerify(NAME);
if (p.rerun) {
const run = `${p.rerunFrom ? `from ${p.rerunFrom}, ` : ''}run: ${p.rerun.join(' ')}`;
const laneWhy = `Rewrites the entry to start gbrain from its own launcher directory, so a repository's bunfig.toml or .env never runs when a session or MCP server starts there.${p.harness === 'codex' && p.rerun[1] === 'setup' ? " gbrain setup codex repeats the install's recorded decisions and re-trusts setup's own hook groups." : ''}`;
if (p.reason === 'foreign') return { consent: [], actor: 'user', requires_exclusive: false, verify, why: laneWhy, user_message: `${p.detail}. Remove that file (gbrain did not write it), then ${run}` };
if (p.edited) return { consent: [], actor: 'user', requires_exclusive: false, verify, why: laneWhy, user_message: `${p.detail}. Remove or rewrite that entry in ${p.source} (setup never overwrites an edit), then ${run}` };
+ if (p.setupOwned && p.harness === 'codex') return { consent: [], actor: 'user', requires_exclusive: false, verify, why: laneWhy, user_message: `${p.detail}. ${codexTrust}: ${p.rerun.join(' ')}` };
if (p.setupOwned) return { argv: p.rerun, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify, why: laneWhy };
- return { consent: [], actor: 'user', requires_exclusive: false, verify, why: laneWhy, user_message: `${p.detail}. To move it onto gbrain's launcher, ${p.lane === 'mcp' && p.owner === 'none' ? `remove that entry from ${p.source} (gbrain never overwrites an MCP entry it did not write), then ` : ''}${run}` };
+ return { consent: [], actor: 'user', requires_exclusive: false, verify, why: laneWhy, user_message: `${p.detail}. To move it onto gbrain's launcher, ${p.lane === 'mcp' && p.owner === 'none' ? `remove that entry from ${p.source} (gbrain does not rewrite it), then ` : ''}${run}` };
}
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 ${project ? `from ${project}, ` : ''}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(' ')}` };
+ if (p.harness === 'codex') return { consent: [], actor: 'user', requires_exclusive: false, verify, why, user_message: `${p.detail}. ${codexTrust}: ${argv.join(' ')}` };
return { argv, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify, why };
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 29201740fa..4bfa201187 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1409,7 +1409,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #8424 (GBRA-277) hook launcher. since stamped at the merge slot.
{ since: '0.60.547.0', id: 'hook_launcher_8424', text: 'The hooks `gbrain setup claude-code|codex` writes, and the per-turn rule hook from `--instructions-only`, `gbrain connect --install` and `gbrain bootstrap harness`, now start gbrain through `<gbrain config dir>/hook-launcher/gbrain-hook`, so a session opened in a cloned repository never runs that repository\'s bunfig.toml preload or loads its .env. `gbrain post-upgrade` moves existing hooks onto it, except `gbrain setup codex`\'s, which the next `gbrain setup codex` rewrites, and doctor `harness_wiring` warns with `hook_session_cwd` on any that still start gbrain in the session directory.' },
// #8426, #8428, #8427 (GBRA-279) MCP and lane launcher, hook git fsmonitor. since stamped at the merge slot.
- { since: '0.60.549.0', id: 'mcp_lane_launcher_8426', text: 'The stdio MCP entry `gbrain setup claude-code|codex` and `gbrain bootstrap hooks` (opencode\'s user-global entry included) register now starts `gbrain serve` through `<gbrain config dir>/hook-launcher/gbrain-hook`, and the hooks from `gbrain bootstrap hooks`, `gbrain bootstrap harness`, the Codex SessionEnd capture and the gbrain plugins start gbrain from the launcher\'s or the plugin\'s own directory, so a session opened in a cloned repository never runs that repository\'s bunfig.toml preload or loads its .env; serve still reads .gbrain-source from the session directory. `gbrain post-upgrade` moves a Claude Code setup MCP entry setup still owns and names the command for every Codex (the turn-rule hook included) and bootstrap entry, doctor `hook_session_cwd` covers them, and `gbrain hook` git probes skip core.fsmonitor and run only in the workspace the install receipt names.' },
+ { since: '0.60.550.0', id: 'mcp_lane_launcher_8426', text: 'The stdio MCP entry `gbrain setup claude-code|codex` and `gbrain bootstrap hooks` (opencode\'s user-global entry included) register now starts `gbrain serve` through `<gbrain config dir>/hook-launcher/gbrain-hook`, and the hooks from `gbrain bootstrap hooks`, `gbrain bootstrap harness`, the Codex SessionEnd capture and the gbrain plugins start gbrain from the launcher\'s or the plugin\'s own directory, so a session opened in a cloned repository never runs that repository\'s bunfig.toml preload or loads its .env; serve still reads .gbrain-source from the session directory. `gbrain post-upgrade` moves a Claude Code setup MCP entry setup still owns and names the command for every Codex (the turn-rule hook included) and bootstrap entry, doctor `hook_session_cwd` covers them, and `gbrain hook` git probes skip core.fsmonitor and run only in the workspace the install receipt names.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/setup/hook-launcher-refresh.ts b/src/core/setup/hook-launcher-refresh.ts
index 9a92e6a700..8085762a70 100644
--- a/src/core/setup/hook-launcher-refresh.ts
+++ b/src/core/setup/hook-launcher-refresh.ts
@@ -25,7 +25,7 @@ import { applyClaudeSetup, claudeSetupPaths, inspectClaudeSetup, readSetupReceip
import { codexSetupPaths, readCodexSetupReceipt } from './codex.ts';
import { hookLauncherInCommand, hookLauncherPath, hookLauncherState } from './hook-launcher.ts';
import { localSetupRecords } from './local-receipts.ts';
-import { launcherLaneFindings } from './launcher-lanes.ts';
+import { launcherLaneFindings, setupRerunArgv } from './launcher-lanes.ts';
import { hasTurnRuleHook, isTurnRuleEntry, syncTurnRuleHook, TURN_RULE_LANE_TOKEN } from './turn-hook.ts';
/** True when this command starts gbrain somewhere other than a current launcher. */
@@ -63,11 +63,12 @@ function refreshTurnRule(log: (line: string) => void): void {
async function refreshSetup(log: (line: string) => void): Promise<void> {
const home = configDir();
for (const record of localSetupRecords(home).filter((r) => r.status === 'installed')) {
- const rerun = `gbrain setup ${record.harness}${record.name === 'gbrain' ? '' : ` --name ${record.name}`}`;
+ let rerun = `gbrain setup ${record.harness}${record.name === 'gbrain' ? '' : ` --name ${record.name}`}`;
try {
if (record.harness === 'claude-code') {
const receipt = readSetupReceipt(record.path).setup;
if (!receipt) continue;
+ rerun = setupRerunArgv('claude-code', receipt).join(' ');
const paths = claudeSetupPaths({ name: receipt.name, scope: receipt.scope, projectDir: receipt.project_dir });
const owned = new Set([...Object.values(receipt.hooks.owned), ...Object.values(receipt.hooks.pending)]);
const ours = claudeHookEntries(paths.settingsPath).filter((e) => e[GBRAIN_HOOK_MARKER_KEY] === GBRAIN_SETUP_MARKER_VALUE || owned.has(hookEntryHash(e) ?? '')).map((e) => e.command as string);
@@ -88,6 +89,7 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {
} else if (record.harness === 'codex') {
const receipt = readCodexSetupReceipt(record.path).setup;
if (!receipt) continue;
+ rerun = setupRerunArgv('codex', receipt).join(' ');
const paths = codexSetupPaths(receipt.name);
const hooks = codexHookCensus(paths.hooksPath).some((g) => g.lane === 'setup' && g.commands.some(needsLauncher));
const mcp = !receipt.mcp_plugin && launcherLaneFindings().some((f) => f.harness === 'codex' && f.lane === 'mcp' && f.owner === 'setup' && f.detail.startsWith(`[mcp_servers.${receipt.name}]`));
@@ -107,7 +109,7 @@ export async function refreshHookLaunchers(log: (line: string) => void = console
try { await refreshSetup(log); } catch (e) { log(`Hook launcher: setup's hooks were not refreshed (${(e as Error).message}); run gbrain doctor --only harness_wiring.`); }
// The other lanes are named, never rewritten here: bootstrap's writers run from the workspace, and their Codex entries move trust.
try {
- for (const f of launcherLaneFindings().filter((x) => x.owner !== 'setup')) log(`Hook launcher: ${f.detail}; ${f.edited ? 'it was edited after setup wrote it, so it is kept as is; remove or rewrite it, then ' : f.owner === 'none' ? 'gbrain did not write it, so remove it, then ' : ''}${f.rerunFrom ? `from ${f.rerunFrom}, ` : ''}run ${f.rerun.join(' ')} to move it onto gbrain's launcher.`);
+ for (const f of launcherLaneFindings().filter((x) => x.owner !== 'setup')) log(`Hook launcher: ${f.detail}; ${f.edited ? 'it was edited after setup wrote it, so it is kept as is; remove or rewrite it, then ' : f.owner === 'none' ? 'gbrain does not rewrite it, so remove it, then ' : ''}${f.rerunFrom ? `from ${f.rerunFrom}, ` : ''}run ${f.rerun.join(' ')} to move it onto gbrain's launcher.`);
} catch (e) { log(`Hook launcher: the bootstrap lanes were not checked (${(e as Error).message}); run gbrain doctor --only harness_wiring.`); }
}
diff --git a/src/core/setup/launcher-lanes.ts b/src/core/setup/launcher-lanes.ts
index 0b8fe70ead..17ac73c210 100644
--- a/src/core/setup/launcher-lanes.ts
+++ b/src/core/setup/launcher-lanes.ts
@@ -14,7 +14,8 @@ import { codexHookCensus } from '../bootstrap/codex-hooks.ts';
import { readCodexTomlTable } from '../bootstrap/codex-toml.ts';
import { readReceipt } from '../bootstrap/format.ts';
import { CLAUDE_SETTINGS_FILE_RELPATH, GBRAIN_HOOK_MARKER_KEY, GBRAIN_HOOK_MARKER_VALUE, claudeUserMcpConfigPath, claudeUserSettingsPath, codexConfigPath, codexHooksPath, opencodeConfigDir } from '../bootstrap/host-specs.ts';
-import { parseOpencodeConfig } from '../bootstrap/opencode-json.ts';
+import { opencodeEntryKind, parseOpencodeConfig } from '../bootstrap/opencode-json.ts';
+import { readInterviewState } from '../bootstrap/interview.ts';
import { resolveGbrainHome } from '../gbrain-home.ts';
import { hookLauncherInCommand, hookLauncherState, isHookLauncherPath, type HookLauncherState } from './hook-launcher.ts';
import { localSetupRecords } from './local-receipts.ts';
@@ -121,15 +122,24 @@ function mcpFindings(): LauncherLaneFinding[] {
out.push({ harness: 'codex', lane: 'mcp', source: codexPath, reason: s.reason, ...rerunFor('codex', name, table), detail: `[mcp_servers.${name}] in ${codexPath} ${s.why}` });
}
// opencode merges both user-global filenames, and starts a local server in each directory it opens (#8435).
- for (const file of ['opencode.jsonc', 'opencode.json'].map((f) => join(opencodeConfigDir(), f))) {
- let entry: Record<string, unknown> | null;
- try { entry = existsSync(file) ? record(record(parseOpencodeConfig(readFileSync(file, 'utf8'), file).mcp)?.gbrain) : null; } catch { continue; }
- const argv = entry?.type === 'local' && Array.isArray(entry.command) ? entry.command.filter((a): a is string => typeof a === 'string') : [];
+ // bootstrap rewrites the global file only for an entry its writer calls ours and while the workspace still records user scope.
+ const ocProjectScope = (() => { if (!bootstrap) return false; const read = readInterviewState(bootstrap.workspace_dir); const v = read.ok ? read.state.answers['MCP_SCOPE'] : undefined; return v?.skipped !== true && typeof v?.value === 'string' && v.value.trim().toLowerCase() === 'project'; })();
+ const ocFiles = ['opencode.jsonc', 'opencode.json'].map((f) => join(opencodeConfigDir(), f)).flatMap((file) => {
+ try { return existsSync(file) ? [{ file, parsed: parseOpencodeConfig(readFileSync(file, 'utf8'), file) }] : []; } catch { return []; }
+ });
+ // A remote gbrain entry in either file makes bootstrap skip the stdio registration, so it never rewrites the local one.
+ const ocRemote = ocFiles.some(({ parsed }) => record(record(parsed.mcp)?.gbrain)?.type === 'remote');
+ for (const { file, parsed } of ocFiles) {
+ const entry = record(record(parsed.mcp)?.gbrain);
+ // A disabled entry never starts, and the repair would turn it back on.
+ const argv = entry?.type === 'local' && entry.enabled !== false && Array.isArray(entry.command) ? entry.command.filter((a): a is string => typeof a === 'string') : [];
const serve = argv.length > 0 ? serveEntryLauncher({ command: argv[0], args: argv.slice(1) }) : null;
const s = serve && state(serve.launcher);
if (!s) continue;
- out.push({ harness: 'opencode', lane: 'mcp', source: file, reason: s.reason, ...(bootstrapRerun('opencode') ?? { rerun: ['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--repair'], setupOwned: false, owner: 'none' }),
- detail: `the 'gbrain' MCP server in ${file} ${s.why}` });
+ const foreign = opencodeEntryKind(parsed, 'gbrain') === 'foreign';
+ const boot = foreign || ocProjectScope || ocRemote ? null : bootstrapRerun('opencode');
+ out.push({ harness: 'opencode', lane: 'mcp', source: file, reason: s.reason, ...(boot ?? { rerun: ['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--repair'], ...(bootstrap ? { rerunFrom: bootstrap.workspace_dir } : {}), setupOwned: false, owner: 'none' }),
+ detail: `the 'gbrain' MCP server in ${file} ${s.why}${foreign ? ` (gbrain's writer does not recognize it as its own)` : ocRemote ? ' (a remote gbrain entry is also configured, so bootstrap leaves this one alone)' : ocProjectScope ? ' (the workspace now records MCP_SCOPE=project, so bootstrap writes opencode.json in the workspace instead)' : ''}` });
}
return out;
}
diff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.ts
index c5f5c37a25..2b374be01a 100644
--- a/src/core/setup/turn-hook-check.ts
+++ b/src/core/setup/turn-hook-check.ts
@@ -138,23 +138,25 @@ export interface HookLauncherProblem {
rerunFrom?: string;
setupOwned?: boolean;
owner?: 'setup' | 'bootstrap' | 'none';
+ /** The setup receipt that owns the hook, when its hash is recorded. */
+ receiptPath?: string;
}
/** 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>();
+function setupReceiptHashes(harness: 'claude-code' | 'codex'): { owned: Map<string, string>; edited: Map<string, string> } {
+ const owned = new Map<string, string>();
+ const edited = new Map<string, 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);
+ for (const h of [...Object.values(hooks?.owned ?? {}), ...Object.values(hooks?.pending ?? {})]) if (typeof h === 'string') owned.set(h, r.path);
+ for (const h of Object.values(hooks?.edited ?? {})) if (typeof h === 'string') edited.set(h, r.path);
}
return { owned, edited };
}
-type LaneCommand = { lane: 'setup' | 'turn-rule'; command: string; edited?: boolean };
+type LaneCommand = { lane: 'setup' | 'turn-rule'; command: string; edited?: boolean; receiptPath?: string };
-function claudeLaneCommands(path: string, setup: { owned: Set<string>; edited: Set<string> }): LaneCommand[] {
+function claudeLaneCommands(path: string, setup: { owned: Map<string, string>; edited: Map<string, string> }): LaneCommand[] {
const hooks = readJson(path)?.hooks;
if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) return [];
const out: LaneCommand[] = [];
@@ -165,8 +167,8 @@ function claudeLaneCommands(path: string, setup: { owned: Set<string>; edited: S
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 (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 });
+ else if (setup.edited.has(hash)) out.push({ lane: 'setup', command: entry.command as string, edited: true, receiptPath: setup.edited.get(hash) });
+ else if (entry[GBRAIN_HOOK_MARKER_KEY] === GBRAIN_SETUP_MARKER_VALUE || setup.owned.has(hash)) out.push({ lane: 'setup', command: entry.command as string, receiptPath: setup.owned.get(hash) });
}
}
return out;
@@ -183,18 +185,18 @@ export function hookLauncherProblem(harness: 'claude-code' | 'codex', opts: { pr
} 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(), ...(setup.edited.has(g.hash) ? { edited: true } : {}) })));
+ 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 } : {}), receiptPath: setup.owned.get(g.hash) ?? setup.edited.get(g.hash) })));
}
} catch { /* unparseable: Codex runs none of it */ }
}
for (const f of found) {
const launcher = hookLauncherInCommand(f.command);
if (!launcher) {
- return { harness, lane: f.lane, source: f.source, reason: 'session_cwd', ...(f.edited ? { edited: true } : {}),
+ return { harness, lane: f.lane, source: f.source, reason: 'session_cwd', ...(f.edited ? { edited: true } : {}), ...(f.receiptPath ? { receiptPath: f.receiptPath } : {}),
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${f.edited ? '; it was edited after setup wrote it, so setup keeps it as is' : ''}` };
}
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, ...(f.receiptPath ? { receiptPath: f.receiptPath } : {}), detail: `gbrain's ${f.lane} hook in ${f.source} runs through ${launcher}, but ${s.detail}` };
}
return null;
}
diff --git a/test/hook-launcher-bunfig.test.ts b/test/hook-launcher-bunfig.test.ts
index 1379e607cd..317f2db83a 100644
--- a/test/hook-launcher-bunfig.test.ts
+++ b/test/hook-launcher-bunfig.test.ts
@@ -274,12 +274,17 @@ describe('doctor: the hook_session_cwd fix and how it joins the harness_wiring c
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 () => {
+ test('the fix: the agent re-runs setup for user scope; a project, a foreign file, an edited entry or any Codex rerun 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'] });
+ // gbrain setup codex rewrites the shared hooks.json and its trust (it can re-enable or newly trust a group), so the agent never runs it.
+ const codex = hookLauncherFix(problem(b, { harness: 'codex', lane: 'turn-rule', source: join(b.home, '.codex', 'hooks.json') }));
+ expect(codex).toMatchObject({ actor: 'user', consent: [] });
+ expect(codex.argv).toBeUndefined();
+ expect(codex.user_message).toContain('run it yourself: gbrain setup codex --instructions-only');
+ expect(hookLauncherFix(problem(b, { harness: 'codex', lane: 'mcp', source: join(b.home, '.codex', 'config.toml'), rerun: ['gbrain', 'setup', 'codex'], setupOwned: true, owner: 'setup' }))).toMatchObject({ actor: 'user', consent: [] });
const project = join(b.root, 'proj');
const p = hookLauncherFix(problem(b, { source: join(project, '.claude', 'settings.local.json') }));
expect(p.actor).toBe('user');
diff --git a/test/launcher-lanes-bunfig.serial.test.ts b/test/launcher-lanes-bunfig.serial.test.ts
index a7a10c5c8d..a9f6d1ef6a 100644
--- a/test/launcher-lanes-bunfig.serial.test.ts
+++ b/test/launcher-lanes-bunfig.serial.test.ts
@@ -251,6 +251,31 @@ describe('#8426, #8428: gbrain bootstrap hooks registers serve and writes its ho
expect(await serveFromSession(entry.command[0]!, entry.command.slice(1), { ...entry.environment, GBRAIN_SOURCE: 'source-b' }, 'notes/bootstrap-opencode')).toBe('source-b');
expect(existsSync(marker)).toBe(false);
await waitForDetached();
+
+ // bootstrap's rerun cannot clear an entry its writer calls foreign, or one in the global file once the workspace records project scope: both are the user's.
+ const old = { type: 'local', command: [gbrain, 'serve'], environment: { GBRAIN_SOURCE: entry.environment.GBRAIN_SOURCE }, enabled: true };
+ writeFileSync(config, JSON.stringify({ mcp: { gbrain: { ...old, command: ['/opt/team/memory-wrapper', 'serve'] } } }, null, 2));
+ await withEnv(procEnv, async () => {
+ expect(launcherLaneFindings().filter((f) => f.harness === 'opencode')).toMatchObject([{ owner: 'none', detail: expect.stringContaining('does not recognize it as its own') }]);
+ });
+ writeFileSync(config, JSON.stringify({ mcp: { gbrain: old } }, null, 2));
+ expect(setAnswer(ws, 'MCP_SCOPE', 'project').ok).toBe(true);
+ await withEnv(procEnv, async () => {
+ expect(launcherLaneFindings().filter((f) => f.harness === 'opencode')).toMatchObject([{ owner: 'none', detail: expect.stringContaining('MCP_SCOPE=project') }]);
+ });
+ expect(setAnswer(ws, 'MCP_SCOPE', 'user').ok).toBe(true);
+ // opencode.json is scanned too; a disabled entry never starts, and a remote entry beside it makes bootstrap skip the stdio lane.
+ const json = join(home, '.config', 'opencode', 'opencode.json');
+ rmSync(config);
+ writeFileSync(json, JSON.stringify({ mcp: { gbrain: old } }, null, 2));
+ await withEnv(procEnv, async () => { expect(launcherLaneFindings().filter((f) => f.harness === 'opencode')).toMatchObject([{ source: json, owner: 'bootstrap' }]); });
+ writeFileSync(json, JSON.stringify({ mcp: { gbrain: { ...old, enabled: false } } }, null, 2));
+ await withEnv(procEnv, async () => { expect(launcherLaneFindings().filter((f) => f.harness === 'opencode')).toEqual([]); });
+ writeFileSync(json, JSON.stringify({ mcp: { gbrain: old } }, null, 2));
+ writeFileSync(config, JSON.stringify({ mcp: { gbrain: { type: 'remote', url: 'https://brain.example/mcp', enabled: true } } }, null, 2));
+ await withEnv(procEnv, async () => { expect(launcherLaneFindings().filter((f) => f.harness === 'opencode')).toMatchObject([{ source: json, owner: 'none', detail: expect.stringContaining('a remote gbrain entry') }]); });
+ rmSync(json);
+ writeFileSync(config, JSON.stringify({ mcp: { gbrain: { ...old, command: entry.command } } }, null, 2));
}, 120_000);
});
@@ -275,7 +300,7 @@ describe('#8428: the harness and plugin hook lanes', () => {
chmodSync(join(pluginRoot, '.agents', 'gbrain-launcher'), 0o755);
const recorder = join(root, 'recording-gbrain');
const seen = join(root, 'recorder-saw');
- writeFileSync(recorder, `#!/bin/sh\nif [ "$1" = --version ]; then echo "gbrain 0.60.549.0"; exit 0; fi\nprintf '%s|%s|%s\\n' "$GBRAIN_HOOK_CWD" "$(pwd)" "$1" > '${seen}'\n`);
+ writeFileSync(recorder, `#!/bin/sh\nif [ "$1" = --version ]; then echo "gbrain 0.61.0.0"; exit 0; fi\nprintf '%s|%s|%s\\n' "$GBRAIN_HOOK_CWD" "$(pwd)" "$1" > '${seen}'\n`);
chmodSync(recorder, 0o755);
const manifests: Array<[string, string]> = [['.claude-plugin/plugin.json', '${CLAUDE_PLUGIN_ROOT}'], ['.codex-plugin/plugin.json', '${PLUGIN_ROOT}']];
for (const [file, token] of manifests) {
diff --git a/test/mcp-registration.test.ts b/test/mcp-registration.test.ts
index ba04c47d40..56d245cbb7 100644
--- a/test/mcp-registration.test.ts
+++ b/test/mcp-registration.test.ts
@@ -171,7 +171,7 @@ describe('S0: README, docs/mcp, INSTALL, BOOTSTRAP, push-context and the manifes
test('#8436: no install doc teaches a Claude Code or Codex stdio mcp add of serve that skips gbrain\'s launcher', () => {
const offenders: string[] = [];
- for (const file of DOCS) {
+ for (const file of [...DOCS, 'docs/protocol/AGENT_OPERATOR_v1.md']) {
readFileSync(join(ROOT, file), 'utf8').split('\n').forEach((line, i) => {
for (const m of line.matchAll(/\b(?:claude|codex)\s+mcp add\b[^`\n|]*?\bserve\b/g)) {
if (!m[0].includes('hook-launcher/gbrain-hook')) offenders.push(`${file}:${i + 1}: ${line.trim()}`);
diff --git a/test/setup.test.ts b/test/setup.test.ts
index 6f70c70a57..2d9e9eb108 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -35,7 +35,7 @@ import { hookLauncherProblem, inspectTurnHook } from '../src/core/setup/turn-hoo
import { refreshHookLaunchers } from '../src/core/setup/hook-launcher-refresh.ts';
import { syncTurnRuleHook, isTurnRuleEntry } from '../src/core/setup/turn-hook.ts';
import { hookLauncherFix, hookLauncherProblems } from '../src/commands/doctor/checks/harness-wiring.ts';
-import { launcherLaneFindings } from '../src/core/setup/launcher-lanes.ts';
+import { launcherLaneFindings, setupRerunArgv } from '../src/core/setup/launcher-lanes.ts';
import { applyClaudeSetup, readSetupReceipt } from '../src/core/setup/claude-code.ts';
const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');
@@ -1129,6 +1129,40 @@ describe('hooks written before the hook launcher (#8424): the next setup and pos
expect(readFileSync(claudeJson(b), 'utf8')).toBe(before);
});
+ test('claude-code (#8426): doctor reruns the install that owns the flagged hook, not the first receipt on disk', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--name', 'alpha', '--no-hooks', '--json'])).exitCode).toBe(0);
+ expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);
+ downgradeClaude(b);
+ await withEnv(env(b), async () => {
+ const problem = hookLauncherProblem('claude-code');
+ expect(problem).toMatchObject({ lane: 'setup', receiptPath: receipt(b) });
+ expect(hookLauncherFix(problem!)).toMatchObject({ actor: 'agent', argv: ['gbrain', 'setup', 'claude-code'] });
+ });
+ });
+
+ test('setupRerunArgv carries the recorded hooks opt-out and source pin, and nothing setup keeps on its own', () => {
+ const consent = (hooks: 'none' | 'read-context') => ({ wiring_scope: { value: { scope: 'user' as const, hooks }, source: 'flag' as const }, capture: { value: 'accepted' as const, source: 'flag' as const }, providers: { value: 'declined' as const, source: 'default' as const } });
+ expect(setupRerunArgv('codex', { name: 'gbrain', consent: consent('none') as any, source_id: 'source-a' })).toEqual(['gbrain', 'setup', 'codex', '--no-hooks', '--source', 'source-a']);
+ expect(setupRerunArgv('claude-code', { name: 'alpha', consent: consent('read-context') as any, source_id: null as any }, '/work/proj')).toEqual(['gbrain', 'setup', 'claude-code', '--name', 'alpha', '--scope', 'project']);
+ });
+
+ test('codex MCP (#8426): post-upgrade\'s printed rerun keeps a recorded --no-hooks', async () => {
+ const b = box();
+ expect((await setup(b, ['codex', '--no-hooks', '--json'])).exitCode).toBe(0);
+ const r = readJson(codexReceipt(b));
+ const old = { command: b.bin, args: ['serve'], env: { GBRAIN_HOME: b.gbrainHome } };
+ expect(removeCodexTomlTable(codexToml(b), ['mcp_servers', 'gbrain'])).toBe('removed');
+ appendCodexTomlTable(codexToml(b), ['mcp_servers', 'gbrain'], old, 'gbrain setup (gbrain): owned by fingerprint');
+ r.entry_hash = ownedEntryFingerprint(old);
+ writeFileSync(codexReceipt(b), JSON.stringify(r, null, 2));
+ await withEnv(env(b), async () => {
+ const lines: string[] = [];
+ await refreshHookLaunchers((l) => lines.push(l));
+ expect(lines.join('\n')).toContain('run gbrain setup codex --no-hooks to rewrite them');
+ });
+ });
+
test('codex MCP (#8426): post-upgrade names the setup rerun for a pre-launcher [mcp_servers] table and writes nothing; setup moves it', async () => {
const b = box();
expect((await setup(b, ['codex', '--json'])).exitCode).toBe(0);