Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(security): doctor and post-upgrade cover the MCP entries and bootstrap lanes; Codex entries are only named, Claude Code setup entries move under the setup lock (#8426, #8428)
garrytane5797799deca
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.tsindex d4df8df890..49eeb6ec54 100644--- a/src/commands/bootstrap.ts+++ b/src/commands/bootstrap.ts@@ -1439,7 +1439,7 @@ async function runHooks();}// A user-scope stdio server starts through the launcher, never in the session's directory (#8426).- const hookLauncher = harness === 'codex' || mcpScope === 'user' ? hookLauncherPath() : undefined;+ const hookLauncher = harness === 'codex' || mcpScope === 'user' ? hookLauncherPath(home) : undefined;const buildArgvs = (surface?: McpSurface | null, advertise?: McpSurface | null) => harness === 'claude-code'? registerClaudeMcp({ gbrainBin, scope: mcpScope, sourceId, surface, advertise, ...(gbrainHome ? { gbrainHome } : {}), ...(hookLauncher ? { hookLauncher } : {}) }): registerCodexMcp({ gbrainBin, sourceId, surface, advertise, ...(gbrainHome ? { gbrainHome } : {}), ...(hookLauncher ? { hookLauncher } : {}) });@@ -1531,7 +1531,7 @@ async function runHooks(if (!mcpSkipped && !mcpPluginOwned) try {const listBin = harness === 'claude-code' ? 'claude' : 'codex';const scopeLabel = harness === 'claude-code' ? mcpScope : 'user-global';- const { verdict } = await verifyMcpTargetsWorkspace(runner, harness, 'gbrain', gbrainBin, sourceId, harness === 'codex' || mcpScope === 'user' ? hookLauncherPath() : undefined);+ const { verdict } = await verifyMcpTargetsWorkspace(runner, harness, 'gbrain', gbrainBin, sourceId, harness === 'codex' || mcpScope === 'user' ? hookLauncherPath(home) : undefined);if (verdict === 'match') {console.log(`MCP registered with ${harness} (scope: ${scopeLabel}) — verified targeting this workspace.`);} else if (verdict === 'mismatch') {@@ -1572,7 +1572,7 @@ async function runHooks(try {r = cloudCarrier? writeCommittedClaudeHooks(ws, { env: hookEnv })- : writeClaudeHooks(ws, { gbrainBin, hookLauncher: ensureHookLauncher(hookLauncherPath()), env: hookEnv });+ : writeClaudeHooks(ws, { gbrainBin, hookLauncher: ensureHookLauncher(hookLauncherPath(home)), env: hookEnv });} catch (e) {// Fail-closed on an unparseable settings file (either carrier): MCP// (step 1) still landed; record that, surface the fix, and exit@@ -1611,7 +1611,7 @@ async function runHooks(// this repo's source; session-end resolves from the payload instead.let r: ReturnType<typeof writeCodexHooks>;try {- r = writeCodexHooks({ gbrainBin, hookLauncher: ensureHookLauncher(hookLauncherPath()) });+ r = writeCodexHooks({ gbrainBin, hookLauncher: ensureHookLauncher(hookLauncherPath(home)) });} catch (e) {r = { ok: false, hooksPath: '', configPath: '', notes: [(e as Error).message] };}diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.tsindex 3837c7178a..7ef4c1095d 100644--- a/src/commands/doctor/checks/harness-wiring.ts+++ b/src/commands/doctor/checks/harness-wiring.ts@@ -44,6 +44,7 @@ import type { DoctorContext, DoctorEntry } from '../context.ts';import { VERSION } from '../../../version.ts';import { TURN_HOOK_NATIVE_INSPECT, hookLauncherProblem, inspectTurnHook, turnHookFix, type HookLauncherProblem, type TurnHookState } from '../../../core/setup/turn-hook-check.ts';import { localSetupRecords } from '../../../core/setup/local-receipts.ts';+import { launcherLaneFindings } from '../../../core/setup/launcher-lanes.ts';import { brainFirstTarget, inspectBrainFirst, isBrainFirstHarness, readBrainFirstLedger, renderBrainFirstBlock, type BrainFirstAccess } from '../../../core/setup/brain-first.ts';export const HARNESS_SMOKE_TIMEOUT_MS = 15_000;@@ -505,14 +506,16 @@ export function withTurnHooks(check: Check, views: InstructionBlockView[], hooks/*** The first setup or turn-rule hook that would let a session directory's* bunfig.toml or .env load (#8424): Claude Code user scope, every project a- * setup receipt or a CLAUDE.local.md block names, and Codex. Files only.+ * setup receipt or a CLAUDE.local.md block names, and Codex; then the stdio+ * MCP entries and the bootstrap and harness lanes (#8426, #8428). Files only.*/export function hookLauncherProblems(views: InstructionBlockView[]): HookLauncherProblem | null {const projects = new Set([...localSetupRecords().filter((r) => r.harness === 'claude-code' && r.scope === 'project' && r.projectDir).map((r) => r.projectDir!),...views.filter((v) => v.harness === 'claude-code' && basename(v.path) === 'CLAUDE.local.md').map((v) => dirname(v.path)),]);- return hookLauncherProblem('claude-code') ?? [...projects].map((projectDir) => hookLauncherProblem('claude-code', { projectDir })).find((p) => p !== null) ?? hookLauncherProblem('codex');+ return hookLauncherProblem('claude-code') ?? [...projects].map((projectDir) => hookLauncherProblem('claude-code', { projectDir })).find((p) => p !== null) ?? hookLauncherProblem('codex')+ ?? launcherLaneFindings()[0] ?? null;}/** The setup command that rewrites the lane's hooks through the launcher; a project install or a foreign file needs the user. */@@ -522,6 +525,13 @@ export function hookLauncherFix(p: HookLauncherProblem): Action {const argv = ['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 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.";+ 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.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, ${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(' ')}` };diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.tsindex c4361cf2a7..24a78858f0 100644--- a/src/core/bootstrap/harness.ts+++ b/src/core/bootstrap/harness.ts@@ -1457,7 +1457,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P}const r = writeClaudeHooksAt(settingsPath, {gbrainBin: bin,- hookLauncher: ensureHookLauncher(hookLauncherPath()),+ hookLauncher: ensureHookLauncher(hookLauncherPath(d.gbrainHome)),env,events: hookEvents,marker: GBRAIN_HARNESS_MARKER_VALUE,@@ -1583,7 +1583,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P} else {// Paths derive from THIS TARGET's config.toml (CODEX_HOME-resolved// upstream, test-injectable) — never the ambient global default.- const hr = writeCodexHooks({ gbrainBin: hooksBin, hookLauncher: ensureHookLauncher(hookLauncherPath()), configPath: t.path!, hooksPath: join(dirname(t.path!), 'hooks.json') });+ const hr = writeCodexHooks({ gbrainBin: hooksBin, hookLauncher: ensureHookLauncher(hookLauncherPath(d.gbrainHome)), configPath: t.path!, hooksPath: join(dirname(t.path!), 'hooks.json') });if (hr.ok) d.log(`Codex SessionEnd hook wired: ${hr.hooksPath} + trust entry in ${hr.configPath}.`);else for (const note of hr.notes) d.logError(note);}diff --git a/src/core/setup/claude-code.ts b/src/core/setup/claude-code.tsindex 1263744a0d..4a9678d702 100644--- a/src/core/setup/claude-code.ts+++ b/src/core/setup/claude-code.ts@@ -271,7 +271,7 @@ export interface ApplyResult { steps: SetupStep[]; receipt: ClaudeSetupReceipt;export async function applyClaudeSetup(plan: ClaudeSetupPlan,consent: SetupConsent,- opts: { pluginOwner: string | null; brainCreated: boolean; beforeMcp?: () => Promise<void>; abortAfter?: string; mcpMustBeCurrent?: boolean },+ opts: { pluginOwner: string | null; brainCreated: boolean; beforeMcp?: () => Promise<void>; abortAfter?: string; mcpMustBeSetups?: boolean },): Promise<ApplyResult> {const paths = claudeSetupPaths(plan);const lock = await acquireBootstrapLock(dirname(paths.configPath));@@ -279,7 +279,8 @@ export async function applyClaudeSetup(// The MCP entry and every hook command start gbrain through the launcher, so it goes down before anything names it (#8424, #8426).ensureHookLauncher(hookLauncherPath(plan.brainHome));const found = inspectClaudeSetup(plan);- if (opts.mcpMustBeCurrent && opts.pluginOwner === null && found.mcp.state !== 'current') throw new Error(`the '${plan.name}' MCP entry changed before the hooks were rewritten`);+ // post-upgrade's refresh: the MCP entry moves only while it is still setup's, read again under the lock (#8426).+ if (opts.mcpMustBeSetups && opts.pluginOwner === null && found.mcp.state !== 'current' && found.mcp.state !== 'owned') throw new Error(`the '${plan.name}' MCP entry changed before setup's entries were rewritten`);const now = new Date().toISOString();const desired = desiredMcpEntry(plan);const desiredHash = entryHash(desired);diff --git a/src/core/setup/hook-launcher-refresh.ts b/src/core/setup/hook-launcher-refresh.tsindex a4e28a120c..63e8c00633 100644--- a/src/core/setup/hook-launcher-refresh.ts+++ b/src/core/setup/hook-launcher-refresh.ts@@ -25,6 +25,7 @@ import { applyClaudeSetup, claudeSetupPaths, inspectClaudeSetup, readSetupReceipimport { codexSetupPaths, readCodexSetupReceipt } from './codex.ts';import { hookLauncherInCommand, hookLauncherPath, hookLauncherState, shellWords } from './hook-launcher.ts';import { localSetupRecords } from './local-receipts.ts';+import { launcherLaneFindings } 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. */@@ -88,25 +89,29 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {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);- if (!ours.some(needsLauncher)) continue;- if (receipt.scope === 'project') { log(`Hook launcher: gbrain's hooks in ${paths.settingsPath} start gbrain in the session's directory; from ${receipt.project_dir}, run ${rerun} --scope project.`); continue; }- const homeEnv = ours.map((c) => parseClaudeHookCommand(c)?.env.GBRAIN_HOME).find((h) => h !== undefined);- const plan: ClaudeSetupPlan = { name: receipt.name, scope: receipt.scope, launcher: receipt.launcher, brainHome: receipt.gbrain_home, ...(homeEnv ? { gbrainHomeEnv: homeEnv } : {}),+ const homeEnv = ours.map((c) => parseClaudeHookCommand(c)?.env.GBRAIN_HOME).find((h) => h !== undefined) ?? claudeMcpHome(paths.configPath, receipt.name, receipt.project_dir);+ const plan: ClaudeSetupPlan = { name: receipt.name, scope: receipt.scope, ...(receipt.project_dir ? { projectDir: receipt.project_dir } : {}), 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; }- const applied = await applyClaudeSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false, mcpMustBeCurrent: true });+ // An MCP entry still exactly what setup last wrote predates the launcher (#8426): setup's own rewrite moves it.+ const mcp = receipt.mcp_plugin ? 'plugin' : inspectClaudeSetup(plan).mcp.state;+ if (!ours.some(needsLauncher) && mcp !== 'owned') continue;+ if (receipt.scope === 'project') { log(`Hook launcher: gbrain setup's entries for ${receipt.project_dir} start gbrain in the session's directory; from ${receipt.project_dir}, run ${rerun} --scope project.`); continue; }+ if (mcp !== 'plugin' && mcp !== 'current' && mcp !== 'owned') { log(`Hook launcher: gbrain's claude-code hooks start gbrain in the session's directory; run ${rerun} to rewrite them.`); continue; }+ const applied = await applyClaudeSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false, mcpMustBeSetups: true });const left = new Set(claudeHookEntries(paths.settingsPath).filter((e) => needsLauncher(e.command as string)).map((e) => hookEntryHash(e) ?? ''));const kept = Object.entries(applied.edited).filter(([, hash]) => left.has(hash)).map(([event]) => event);log(kept.length > 0? `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.`);+ : `Hook launcher: gbrain setup's claude-code ${mcp === 'owned' ? 'MCP server and hooks' : 'hooks'} now start gbrain from its own directory.`);} else if (record.harness === 'codex') {const receipt = readCodexSetupReceipt(record.path).setup;if (!receipt) continue;const paths = codexSetupPaths(receipt.name);- if (!codexHookCensus(paths.hooksPath).some((g) => g.lane === 'setup' && g.commands.some(needsLauncher))) continue;- // Rewriting re-trusts setup's groups, and a hooks.json every install shares cannot show which install's group Codex runs, so the rewrite stays with setup, where the user approves it.- log(`Hook launcher: gbrain setup's codex hooks in ${paths.hooksPath} start gbrain in the session's directory; run ${rerun} to rewrite them.`);+ 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}]`));+ if (!hooks && !mcp) continue;+ // Rewriting re-trusts setup's groups, and a hooks.json every install shares cannot show which install's group Codex runs, so the rewrite stays with setup, where the user approves it; the MCP table moves in the same run.+ log(`Hook launcher: gbrain setup's codex ${[...(mcp ? [`MCP server in ${paths.configPath}`] : []), ...(hooks ? [`hooks in ${paths.hooksPath}`] : [])].join(' and ')} start gbrain in the session's directory; run ${rerun} to rewrite them.`);}} catch (e) {log(`Hook launcher: gbrain's ${record.harness} hooks were not refreshed (${(e as Error).message}); run ${rerun}.`);@@ -118,5 +123,18 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {export async function refreshHookLaunchers(log: (line: string) => void = console.log): Promise<void> {try { refreshTurnRule(log); } catch (e) { log(`Hook launcher: the turn-rule hooks were not refreshed (${(e as Error).message}); run gbrain doctor --only harness_wiring.`); }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.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.`); }+}++/** GBRAIN_HOME from setup's own MCP entry, for an install with no hooks to read it from. */+function claudeMcpHome(configPath: string, name: string, projectDir?: string): string | undefined {+ try {+ const cfg = JSON.parse(readFileSync(configPath, 'utf8')) as { mcpServers?: Record<string, { env?: Record<string, unknown> }>; projects?: Record<string, { mcpServers?: Record<string, { env?: Record<string, unknown> }> }> };+ const home = (projectDir ? cfg.projects?.[projectDir]?.mcpServers : cfg.mcpServers)?.[name]?.env?.GBRAIN_HOME;+ return typeof home === 'string' ? home : undefined;+ } catch { return undefined; }}diff --git a/src/core/setup/launcher-lanes.ts b/src/core/setup/launcher-lanes.tsnew file mode 100644index 0000000000..98237c3643--- /dev/null+++ b/src/core/setup/launcher-lanes.ts@@ -0,0 +1,136 @@+/**+ * launcher-lanes.ts — the gbrain entries outside setup's and the turn rule's+ * hooks that a harness starts in the session's directory (#8426, #8428): the+ * stdio MCP entries for gbrain serve, the `gbrain bootstrap harness` hooks,+ * the workspace bootstrap lane's hooks and the Codex bootstrap SessionEnd+ * capture. Each is reported with the command that rewrites it through the+ * hook launcher (src/core/setup/hook-launcher.ts). Files only, read-only;+ * doctor's hook_session_cwd and post-upgrade's log lines both read it.+ */+import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { classifyHarnessHook } from '../bootstrap/hooks.ts';+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 } from '../bootstrap/host-specs.ts';+import { resolveGbrainHome } from '../gbrain-home.ts';+import { hookLauncherInCommand, hookLauncherState, isHookLauncherPath, type HookLauncherState } from './hook-launcher.ts';+import { localSetupRecords } from './local-receipts.ts';++export type LauncherLane = 'mcp' | 'harness' | 'bootstrap';++export interface LauncherLaneFinding {+ harness: 'claude-code' | 'codex';+ lane: LauncherLane;+ /** The config, settings or hooks file holding the entry. */+ source: string;+ /** session_cwd: gbrain starts in the session's directory; otherwise the launcher's state. */+ reason: 'session_cwd' | Exclude<HookLauncherState, 'current'>;+ detail: string;+ /** The command that rewrites the entry through the launcher. */+ rerun: string[];+ /** Where to run it, when not from any directory. */+ rerunFrom?: string;+ /** True when rerun is gbrain setup for a user-scope entry setup owns, so an agent may run it; anything else is the user's. */+ setupOwned: boolean;+ /** Which writer owns the entry: setup's are refreshed (or named) by post-upgrade's setup pass, the rest get a line of their own. */+ owner: 'setup' | 'bootstrap' | 'none';+}++function readJson(path: string): Record<string, unknown> | null {+ if (!existsSync(path)) return null;+ try {+ const v = JSON.parse(readFileSync(path, 'utf8')) as unknown;+ return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null;+ } catch { return null; }+}++const record = (v: unknown): Record<string, unknown> | null => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null);++/** A stdio entry that starts gbrain serve, and the launcher state it starts through (null: none). */+function serveEntryLauncher(entry: unknown): { launcher: string | null } | null {+ const e = record(entry);+ if (!e || typeof e.command !== 'string' || typeof e.url === 'string') return null;+ const args = Array.isArray(e.args) ? e.args.filter((a): a is string => typeof a === 'string') : [];+ if (!args.includes('serve')) return null;+ return { launcher: isHookLauncherPath(e.command) ? e.command : null };+}++function state(launcher: string | null): { reason: LauncherLaneFinding['reason']; why: string } | null {+ if (!launcher) return { reason: 'session_cwd', why: 'starts gbrain in the session\'s directory, so Bun loads that directory\'s bunfig.toml and .env before gbrain runs' };+ const s = hookLauncherState(launcher);+ return s.state === 'current' ? null : { reason: s.state, why: `runs through ${launcher}, but ${s.detail}` };+}++function mcpFindings(): LauncherLaneFinding[] {+ const out: LauncherLaneFinding[] = [];+ const setup = localSetupRecords().filter((r) => r.status === 'installed');+ const bootstrap = (() => { try { return readReceipt(resolveGbrainHome()); } catch { return null; } })();+ const rerunFor = (harness: 'claude-code' | 'codex', name: string, projectDir?: string): Pick<LauncherLaneFinding, 'rerun' | 'rerunFrom' | 'setupOwned' | 'owner'> => {+ const owner = setup.find((r) => r.harness === harness && r.name === name && (projectDir ? r.projectDir === projectDir : r.scope !== 'project'));+ if (owner) return { rerun: ['gbrain', 'setup', harness, ...(name === 'gbrain' ? [] : ['--name', name]), ...(projectDir ? ['--scope', 'project'] : [])], ...(projectDir ? { rerunFrom: projectDir } : {}), setupOwned: !projectDir, owner: 'setup' };+ if (bootstrap?.registrations.some((r) => r.host === harness && (r.detail?.split('+') ?? []).includes('mcp'))) return { rerun: ['gbrain', 'bootstrap', 'hooks', '--harness', harness, '--repair'], rerunFrom: bootstrap.workspace_dir, setupOwned: false, owner: 'bootstrap' };+ return { rerun: ['gbrain', 'setup', harness, ...(name === 'gbrain' ? [] : ['--name', name])], setupOwned: false, owner: 'none' };+ };+ const names = [...new Set(['gbrain', ...setup.map((r) => r.name)])];+ const claudePath = claudeUserMcpConfigPath();+ const claude = readJson(claudePath);+ const holders: Array<[Record<string, unknown> | null, string | undefined]> = [[record(claude?.mcpServers), undefined],+ ...Object.entries(record(claude?.projects) ?? {}).map(([dir, p]): [Record<string, unknown> | null, string] => [record(record(p)?.mcpServers), dir])];+ for (const [servers, projectDir] of holders) {+ for (const name of names) {+ const serve = serveEntryLauncher(servers?.[name]);+ const s = serve && state(serve.launcher);+ if (!s) continue;+ out.push({ harness: 'claude-code', lane: 'mcp', source: claudePath, reason: s.reason, ...rerunFor('claude-code', name, projectDir),+ detail: `the '${name}' MCP server in ${claudePath}${projectDir ? ` (project ${projectDir})` : ''} ${s.why}` });+ }+ }+ const codexPath = codexConfigPath();+ for (const name of names) {+ let table: unknown;+ try { table = readCodexTomlTable(codexPath, ['mcp_servers', name]); } catch { continue; }+ const serve = serveEntryLauncher(table);+ const s = serve && state(serve.launcher);+ if (!s) continue;+ out.push({ harness: 'codex', lane: 'mcp', source: codexPath, reason: s.reason, ...rerunFor('codex', name), detail: `[mcp_servers.${name}] in ${codexPath} ${s.why}` });+ }+ return out;+}++function claudeHookCommands(path: string, pick: (entry: Record<string, unknown>, event: string) => boolean): string[] {+ const hooks = record(readJson(path)?.hooks);+ if (!hooks) return [];+ return Object.entries(hooks).flatMap(([event, groups]) => (Array.isArray(groups) ? groups : [])+ .flatMap((g) => (Array.isArray(record(g)?.hooks) ? (record(g)!.hooks as unknown[]) : []))+ .map(record).filter((e): e is Record<string, unknown> => !!e && typeof e.command === 'string' && pick(e, event))+ .map((e) => e.command as string));+}++function hookFindings(): LauncherLaneFinding[] {+ const out: LauncherLaneFinding[] = [];+ const first = (commands: string[]) => commands.map((c) => state(hookLauncherInCommand(c))).find((s) => s !== null) ?? null;+ const user = claudeUserSettingsPath();+ const harness = first(claudeHookCommands(user, (e, event) => classifyHarnessHook(e, event, 'any') !== null));+ if (harness) out.push({ harness: 'claude-code', lane: 'harness', source: user, reason: harness.reason, rerun: ['gbrain', 'bootstrap', 'harness', '--harness', 'claude-code'], setupOwned: false, owner: 'bootstrap',+ detail: `gbrain bootstrap harness's hooks in ${user} ${harness.why}` });+ const ws = (() => { try { return readReceipt(resolveGbrainHome())?.workspace_dir; } catch { return undefined; } })();+ if (ws) {+ const local = join(ws, CLAUDE_SETTINGS_FILE_RELPATH);+ const v1 = first(claudeHookCommands(local, (e) => e[GBRAIN_HOOK_MARKER_KEY] === GBRAIN_HOOK_MARKER_VALUE));+ if (v1) out.push({ harness: 'claude-code', lane: 'bootstrap', source: local, reason: v1.reason, rerun: ['gbrain', 'bootstrap', 'hooks', '--harness', 'claude-code', '--repair'], rerunFrom: ws, setupOwned: false, owner: 'bootstrap',+ detail: `gbrain bootstrap's workspace hooks in ${local} ${v1.why}` });+ }+ let census: ReturnType<typeof codexHookCensus> = [];+ try { census = codexHookCensus(codexHooksPath()); } catch { /* unparseable: Codex runs none of it */ }+ const capture = first(census.filter((g) => g.lane === 'bootstrap').flatMap((g) => g.commands));+ if (capture) out.push({ harness: 'codex', lane: 'bootstrap', source: codexHooksPath(), reason: capture.reason, rerun: ['gbrain', 'bootstrap', 'hooks', '--harness', 'codex', '--repair'], ...(ws ? { rerunFrom: ws } : {}), setupOwned: false, owner: 'bootstrap',+ detail: `gbrain bootstrap's Codex SessionEnd capture in ${codexHooksPath()} ${capture.why} (installed by \`gbrain bootstrap hooks\` or \`gbrain bootstrap harness\`; re-run the one you used)` });+ return out;+}++/** Every finding, MCP entries first. */+export function launcherLaneFindings(): LauncherLaneFinding[] {+ return [...mcpFindings(), ...hookFindings()];+}diff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.tsindex aa0a8d8a64..b71bacb8f3 100644--- a/src/core/setup/turn-hook-check.ts+++ b/src/core/setup/turn-hook-check.ts@@ -21,6 +21,7 @@ import { classifyHarnessHook, hookEntryHash } from '../bootstrap/hooks.ts';import { localSetupRecords } from './local-receipts.ts';import { CLAUDE_SETTINGS_FILE_RELPATH, GBRAIN_HOOK_MARKER_KEY, GBRAIN_SETUP_MARKER_VALUE, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';import { hookLauncherInCommand, hookLauncherState, type HookLauncherState } from './hook-launcher.ts';+import type { LauncherLane } from './launcher-lanes.ts';import { enabledPluginLanes } from '../bootstrap/plugin-lanes.ts';import { brainFirstTarget, openclawConfigPath, parseJson5ish } from './brain-first.ts';import { inspectHermesTurnHook } from './hermes-turn-hook.ts';@@ -123,7 +124,8 @@ export function inspectTurnHook(harness: string, opts: { projectDir?: string } =*/export interface HookLauncherProblem {harness: 'claude-code' | 'codex';- lane: 'setup' | 'turn-rule';+ /** setup and turn-rule: hooks; mcp, harness and bootstrap: the other lanes (launcher-lanes.ts), which carry their own rerun. */+ lane: 'setup' | 'turn-rule' | LauncherLane;/** The settings or hooks file holding the entry. */source: string;/** session_cwd: no launcher in the command; otherwise the launcher's state. */@@ -131,6 +133,10 @@ export interface HookLauncherProblem {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 other lanes: the command that rewrites the entry, where to run it, and whether it is setup's own (an agent may run it). */+ rerun?: string[];+ rerunFrom?: string;+ setupOwned?: boolean;}/** 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. */diff --git a/test/setup.test.ts b/test/setup.test.tsindex 62e17ac53e..90e69db589 100644--- a/test/setup.test.ts+++ b/test/setup.test.ts@@ -981,7 +981,7 @@ describe('hooks written before the hook launcher (#8424): the next setup and posconst before = { settings: readFileSync(settings(b), 'utf8'), config: readFileSync(claudeJson(b), 'utf8') };await withEnv(env(b), async () => {const plan = { name: r.name, scope: r.scope, launcher: r.launcher, brainHome: r.gbrain_home, sourceId: r.source_id, surface: r.surface, advertise: r.advertise ?? null, events: Object.keys(r.hooks.owned) as any };- await expect(applyClaudeSetup(plan, r.consent, { pluginOwner: null, brainCreated: false, mcpMustBeCurrent: true })).rejects.toThrow('MCP entry changed');+ await expect(applyClaudeSetup(plan, r.consent, { pluginOwner: null, brainCreated: false, mcpMustBeSetups: true })).rejects.toThrow('MCP entry changed');});expect({ settings: readFileSync(settings(b), 'utf8'), config: readFileSync(claudeJson(b), 'utf8') }).toEqual(before);});