Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(security): red-first marker tests for the MCP entries, bootstrap/harness/plugin lanes and the planted fsmonitor (#8426, #8428, #8427); an edited setup MCP entry goes to the user

garrytan4bae09400074
diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.ts
index 7ef4c1095d..0d4c563ba2 100644
--- a/src/commands/doctor/checks/harness-wiring.ts
+++ b/src/commands/doctor/checks/harness-wiring.ts
@@ -529,6 +529,7 @@ export function hookLauncherFix(p: HookLauncherProblem): Action {
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.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) 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}` };
}
diff --git a/src/core/setup/hook-launcher-refresh.ts b/src/core/setup/hook-launcher-refresh.ts
index 63e8c00633..37698ab61f 100644
--- a/src/core/setup/hook-launcher-refresh.ts
+++ b/src/core/setup/hook-launcher-refresh.ts
@@ -125,7 +125,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.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.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 98237c3643..6b4bb79ba3 100644
--- a/src/core/setup/launcher-lanes.ts
+++ b/src/core/setup/launcher-lanes.ts
@@ -17,6 +17,9 @@ import { CLAUDE_SETTINGS_FILE_RELPATH, GBRAIN_HOOK_MARKER_KEY, GBRAIN_HOOK_MARKE
import { resolveGbrainHome } from '../gbrain-home.ts';
import { hookLauncherInCommand, hookLauncherState, isHookLauncherPath, type HookLauncherState } from './hook-launcher.ts';
import { localSetupRecords } from './local-receipts.ts';
+import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';
+import { readSetupReceipt } from './claude-code.ts';
+import { readCodexSetupReceipt } from './codex.ts';
export type LauncherLane = 'mcp' | 'harness' | 'bootstrap';
@@ -36,6 +39,8 @@ export interface LauncherLaneFinding {
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';
+ /** A setup install's entry changed after setup wrote it: setup keeps it, so the user removes or rewrites it first. */
+ edited?: boolean;
}
function readJson(path: string): Record<string, unknown> | null {
@@ -67,11 +72,14 @@ 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'));
+ const rerunFor = (harness: 'claude-code' | 'codex', name: string, entry: unknown, projectDir?: string): Pick<LauncherLaneFinding, 'rerun' | 'rerunFrom' | 'setupOwned' | 'owner' | 'edited'> => {
+ const record = setup.find((r) => r.harness === harness && r.name === name && (projectDir ? r.projectDir === projectDir : r.scope !== 'project'));
+ // Setup owns the entry only while it is still what setup wrote; an edited one stays the user's, and setup refuses to overwrite it.
+ const receipt = record && (() => { try { return (harness === 'claude-code' ? readSetupReceipt(record.path) : readCodexSetupReceipt(record.path)).setup; } catch { return null; } })();
+ const owner = receipt && [receipt.entry_hash, receipt.pending_entry_hash].includes(ownedEntryFingerprint(entry as Record<string, unknown>)) ? record : undefined;
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' };
+ return { rerun: ['gbrain', 'setup', harness, ...(name === 'gbrain' ? [] : ['--name', name]), ...(projectDir ? ['--scope', 'project'] : [])], ...(projectDir ? { rerunFrom: projectDir } : {}), setupOwned: false, owner: 'none', ...(record ? { edited: true } : {}) };
};
const names = [...new Set(['gbrain', ...setup.map((r) => r.name)])];
const claudePath = claudeUserMcpConfigPath();
@@ -83,7 +91,7 @@ function mcpFindings(): LauncherLaneFinding[] {
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),
+ out.push({ harness: 'claude-code', lane: 'mcp', source: claudePath, reason: s.reason, ...rerunFor('claude-code', name, servers?.[name], projectDir),
detail: `the '${name}' MCP server in ${claudePath}${projectDir ? ` (project ${projectDir})` : ''} ${s.why}` });
}
}
@@ -94,7 +102,7 @@ function mcpFindings(): LauncherLaneFinding[] {
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}` });
+ out.push({ harness: 'codex', lane: 'mcp', source: codexPath, reason: s.reason, ...rerunFor('codex', name, table), detail: `[mcp_servers.${name}] in ${codexPath} ${s.why}` });
}
return out;
}
diff --git a/test/doctor-harness-smoke.test.ts b/test/doctor-harness-smoke.test.ts
index fc2df8aca9..c04c928be5 100644
--- a/test/doctor-harness-smoke.test.ts
+++ b/test/doctor-harness-smoke.test.ts
@@ -23,6 +23,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { peekLock } from '../src/core/pglite-lock.ts';
import { renderBrainFirstSnippet } from '../src/core/setup/brain-first.ts';
+import { ensureHookLauncher, hookLauncherPath } from '../src/core/setup/hook-launcher.ts';
import { makeDoctorHome, runGbrain, type DoctorHome } from './helpers/doctor-json-golden.ts';
const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');
@@ -37,6 +38,13 @@ function register(command: string, args: string[]): void {
writeFileSync(join(h.home, '.claude', 'CLAUDE.md'), renderBrainFirstSnippet('claude-code', { kind: 'mcp', server: 'gbrain' }));
}
+/** The entry gbrain setup writes: serve starts through the hook launcher, never in the session's directory (#8426). */
+function registerThroughLauncher(args: string[]): void {
+ const launcher = hookLauncherPath(join(h.home, '.gbrain'));
+ ensureHookLauncher(launcher);
+ register(launcher, [process.execPath, ...args]);
+}
+
function harnessCheck(run: { json: unknown; stdout: string }): Record<string, unknown> {
const report = run.json as { checks?: Array<Record<string, unknown>> } | null;
const check = report?.checks?.find(c => c.name === 'harness_wiring');
@@ -63,15 +71,24 @@ describe('doctor --only harness_wiring', () => {
}, 60_000);
test('a registered stdio serve answers initialize + tools/list + recall', async () => {
- register(process.execPath, ['--no-env-file', CLI, 'serve', '--surface', 'verbs']);
+ registerThroughLauncher(['--no-env-file', CLI, 'serve', '--surface', 'verbs']);
const run = await runGbrain(h, ['doctor', '--only', 'harness_wiring', '--json']);
const check = harnessCheck(run);
expect(check, run.stderr).toMatchObject({ status: 'ok', details: { reason: 'wired_running', smoke: 'smoke_passed', harness: 'claude-code' } });
expect(String(check.message)).toContain('recall answered');
}, 60_000);
- test('a live serve holding the brain lock passes without spawning a second one', async () => {
+ test('a registration that starts serve in the session directory answers, and warns hook_session_cwd (#8426)', async () => {
register(process.execPath, ['--no-env-file', CLI, 'serve', '--surface', 'verbs']);
+ const run = await runGbrain(h, ['doctor', '--only', 'harness_wiring', '--json']);
+ const check = harnessCheck(run);
+ expect(check, run.stderr).toMatchObject({ status: 'warn', details: { code: 'hook_session_cwd', hook_launcher_reason: 'session_cwd', smoke: 'smoke_passed' }, fix: { actor: 'user' } });
+ expect(String((check.fix as Record<string, unknown>).user_message)).toContain(`the 'gbrain' MCP server in ${join(h.home, '.claude.json')} starts gbrain in the session's directory`);
+ expect(String((check.fix as Record<string, unknown>).user_message)).toContain('run: gbrain setup claude-code');
+ }, 60_000);
+
+ test('a live serve holding the brain lock passes without spawning a second one', async () => {
+ registerThroughLauncher(['--no-env-file', CLI, 'serve', '--surface', 'verbs']);
const env: Record<string, string> = {};
for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;
Object.assign(env, { HOME: h.home, GBRAIN_HOME: h.home, GBRAIN_SKIP_STARTUP_HOOKS: '1' });
diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.ts
index 5bdb1e4793..cc365ed7ec 100644
--- a/test/hook-command.serial.test.ts
+++ b/test/hook-command.serial.test.ts
@@ -1428,6 +1428,39 @@ describe('stop-hook per-turn push [D3]', () => {
expect((await lastHeartbeat())?.reason).toBe('push_disabled');
});
+ /** #8427: a core.fsmonitor command planted in the checkout's .git/config; git status would run it. */
+ function plantFsmonitor(repo: string): string {
+ const name = repo.split('/').pop()!;
+ const marker = join(tmp, `${name}-FSMONITOR_RAN`);
+ const hook = join(tmp, `${name}-fsmonitor.sh`);
+ writeFileSync(hook, `#!/bin/sh\necho ran > ${JSON.stringify(marker)}\n`, { mode: 0o755 });
+ execFileSync('git', ['-C', repo, 'config', 'core.fsmonitor', hook]);
+ return marker;
+ }
+
+ test('#8427: the per-turn push probe in the bootstrapped workspace never runs a planted core.fsmonitor', async () => {
+ const repo = bootRepo('stop-fsmonitor');
+ const marker = plantFsmonitor(repo);
+ const spawned: string[] = [];
+ await runHook(['stop'], stopIo(repo, spawned));
+ expect(spawned).toHaveLength(1);
+ expect(existsSync(marker)).toBe(false);
+ });
+
+ test('#8427: a checkout the install receipt does not name runs no git, even with an initialized agent.json', async () => {
+ bootRepo('stop-fsmonitor-receipt');
+ const repo = join(tmp, 'stop-fsmonitor-planted');
+ initGitRepoWithDirtyTree(repo);
+ writeFileSync(join(repo, 'agent.json'), JSON.stringify(INITIALIZED_MANIFEST, null, 2) + '\n');
+ const marker = plantFsmonitor(repo);
+ const spawned: string[] = [];
+ await runHook(['stop'], stopIo(repo, spawned));
+ expect((await lastHeartbeat())?.reason).toBe('push_skipped_not_bootstrap');
+ await runHook(['session-start'], { write: () => {}, spawnPush: (root: string) => { spawned.push(root); }, stdin: '', cwd: repo });
+ expect(spawned).toEqual([]);
+ expect(existsSync(marker)).toBe(false);
+ });
+
test('non-bootstrap git repo: never spawns (same security boundary as session-end)', async () => {
const repo = join(tmp, 'stop-plain');
initGitRepoWithDirtyTree(repo);
diff --git a/test/launcher-lanes-bunfig.serial.test.ts b/test/launcher-lanes-bunfig.serial.test.ts
new file mode 100644
index 0000000000..09a62c5081
--- /dev/null
+++ b/test/launcher-lanes-bunfig.serial.test.ts
@@ -0,0 +1,237 @@
+/**
+ * #8426, #8428: the stdio MCP entries for gbrain serve and the remaining hook
+ * lanes (gbrain bootstrap's workspace hooks and Codex SessionEnd capture,
+ * gbrain bootstrap harness's hooks, the plugin hook) never let the session
+ * directory's bunfig.toml or .env run. Each entry is written by its real
+ * writer and started the way the harness starts it, from a checkout whose
+ * bunfig.toml preload drops a marker file; the marker must never appear.
+ * serve still resolves .gbrain-source from that session directory, which the
+ * launcher passes on in GBRAIN_HOOK_CWD.
+ *
+ * SERIAL: spawns gbrain serve against one PGLite brain and mutates HOME.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { withEnv } from './helpers/with-env.ts';
+import { runBootstrap } from '../src/commands/bootstrap.ts';
+import type { ExecRunner } from '../src/core/bootstrap/repo.ts';
+import { writeClaudeHooksAt } from '../src/core/bootstrap/hooks.ts';
+import { GBRAIN_HARNESS_MARKER_VALUE } from '../src/core/bootstrap/host-specs.ts';
+import { confirm, initState, readBackHash, setAnswer } from '../src/core/bootstrap/interview.ts';
+import { desiredMcpEntry } from '../src/core/setup/claude-code.ts';
+import { desiredCodexMcpEntry } from '../src/core/setup/codex.ts';
+import { ensureHookLauncher, hookLauncherPath } from '../src/core/setup/hook-launcher.ts';
+import { launcherLaneFindings } from '../src/core/setup/launcher-lanes.ts';
+
+const ROOT = resolve(import.meta.dir, '..');
+const CLI = join(ROOT, 'src', 'cli.ts');
+const root = mkdtempSync(join(tmpdir(), 'gbrain-launcher-lanes-'));
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+const home = join(root, 'home');
+const bin = join(root, 'bin');
+const hostile = join(root, 'hostile-checkout');
+const tmp = join(root, 'tmp');
+const marker = join(root, 'PRELOAD_RAN');
+const gbrain = join(bin, 'gbrain');
+const launcher = hookLauncherPath(join(home, '.gbrain'));
+const env: Record<string, string> = { HOME: home, GBRAIN_HOME: home, CODEX_HOME: join(home, '.codex'), PATH: `${bin}:/usr/bin:/bin`, TMPDIR: tmp, GBRAIN_AGENT_INSTRUCTIONS: '0', GBRAIN_SKIP_STARTUP_HOOKS: '1' };
+const procEnv = { HOME: home, GBRAIN_HOME: home, CODEX_HOME: join(home, '.codex'), CLAUDE_CONFIG_DIR: undefined, XDG_CONFIG_HOME: undefined };
+
+beforeAll(() => {
+ for (const d of [home, bin, join(hostile, 'tooling'), tmp, join(root, 'source-a')]) mkdirSync(d, { recursive: true });
+ symlinkSync(process.execPath, join(bin, 'bun'));
+ symlinkSync(CLI, gbrain);
+ writeFileSync(join(hostile, 'tooling', 'pre.ts'), `require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'ran');\n`);
+ writeFileSync(join(hostile, 'bunfig.toml'), 'preload = ["./tooling/pre.ts"]\n');
+ writeFileSync(join(hostile, '.env'), 'GBRAIN_HOOKS=1\n');
+ writeFileSync(join(root, 'source-a', 'a.md'), '# a\n');
+ const run = (args: string[]) => {
+ const r = Bun.spawnSync([gbrain, ...args], { cwd: root, env, stdout: 'pipe', stderr: 'pipe', timeout: 120_000 });
+ if (r.exitCode !== 0) throw new Error(`gbrain ${args.join(' ')} failed: ${r.stderr.toString()}`);
+ };
+ run(['init', '--pglite', '--no-embedding']);
+ run(['sources', 'add', 'source-a', '--path', join(root, 'source-a'), '--force', '--no-federated']);
+ writeFileSync(join(hostile, '.gbrain-source'), 'source-a\n');
+ chmodSync(join(hostile, '.gbrain-source'), 0o600);
+ ensureHookLauncher(launcher);
+}, 180_000);
+
+const clearMarker = () => rmSync(marker, { force: true });
+
+/** Start a stdio MCP entry the way the harness does (from the session directory), write one page, and report where it landed. */
+async function serveFromSession(command: string, args: string[], entryEnv: Record<string, string> = {}, slug = 'notes/probe'): Promise<string> {
+ const transport = new StdioClientTransport({ command, args, env: { ...env, ...entryEnv }, cwd: hostile, stderr: 'pipe' });
+ let stderr = '';
+ transport.stderr?.on('data', (chunk) => { stderr += String(chunk); });
+ const client = new Client({ name: 'launcher-lanes', version: '1' }, { capabilities: {} });
+ try {
+ await client.connect(transport);
+ const r = await client.callTool({ name: 'put_page', arguments: { slug, content: '---\ntitle: probe\n---\n# probe\n' } });
+ const text = (r.content as Array<{ text: string }>)[0]!.text;
+ const parsed = JSON.parse(text) as { source_id?: string };
+ if (!parsed.source_id) throw new Error(`put_page answered without a source: ${text}\n${stderr}`);
+ return parsed.source_id;
+ } finally {
+ await client.close().catch(() => {});
+ }
+}
+
+/** Run a hook command the way the harness does: sh -c from the session directory, the event JSON on stdin. */
+function runHook(command: string, extraEnv: Record<string, string> = {}) {
+ const r = Bun.spawnSync(['sh', '-c', command], { cwd: hostile, env: { ...env, ...extraEnv }, stdin: Buffer.from(JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt: 'hi', session_id: 'launcher-lanes', cwd: hostile })), stdout: 'pipe', stderr: 'pipe', timeout: 60_000 });
+ return { exitCode: r.exitCode, stderr: r.stderr.toString() };
+}
+
+async function waitForDetached() {
+ for (let i = 0; i < 300 && readdirSync(tmp).length > 0; i++) await Bun.sleep(100);
+ expect(readdirSync(tmp)).toEqual([]);
+}
+
+const readJson = (p: string) => JSON.parse(readFileSync(p, 'utf8'));
+
+describe('#8426: a stdio MCP entry started from a checkout whose bunfig.toml preloads code', () => {
+ test('control: gbrain serve started in that checkout runs the preload (the hole the launcher closes)', async () => {
+ clearMarker();
+ expect(await serveFromSession(gbrain, ['serve'], {}, 'notes/control')).toBe('source-a');
+ expect(existsSync(marker)).toBe(true);
+ }, 90_000);
+
+ test('gbrain setup claude-code: the MCP entry starts serve through the launcher, and serve still reads the session .gbrain-source', async () => {
+ clearMarker();
+ const entry = desiredMcpEntry({ name: 'gbrain', scope: 'user', launcher: gbrain, brainHome: join(home, '.gbrain'), gbrainHomeEnv: home, sourceId: null, surface: 'full', advertise: null, events: [] }) as { command: string; args: string[]; env: Record<string, string> };
+ expect(entry.command).toBe(launcher);
+ expect(await serveFromSession(entry.command, entry.args, entry.env, 'notes/setup-claude')).toBe('source-a');
+ expect(existsSync(marker)).toBe(false);
+ }, 90_000);
+
+ test('gbrain setup codex: the [mcp_servers] table starts serve through the launcher', async () => {
+ clearMarker();
+ const entry = desiredCodexMcpEntry({ launcher: gbrain, brainHome: join(home, '.gbrain'), gbrainHomeEnv: home, sourceId: null, surface: 'full', advertise: null }) as { command: string; args: string[]; env: Record<string, string> };
+ expect(entry.command).toBe(launcher);
+ expect(await serveFromSession(entry.command, entry.args, entry.env, 'notes/setup-codex')).toBe('source-a');
+ expect(existsSync(marker)).toBe(false);
+ }, 90_000);
+});
+
+/** A confirmed bootstrap interview whose MCP scope is user (a project-scope .mcp.json belongs to the repository). */
+function bootstrapWorkspace(): string {
+ const ws = mkdtempSync(join(root, 'ws-'));
+ expect(initState(ws).ok).toBe(true);
+ for (const [key, value] of Object.entries({
+ AGENT_NAME: 'Dispatch', PRINCIPAL_NAME: 'Pat Example',
+ AGENT_PURPOSE: 'Maintain the research corpus and draft the weekly memo without re-briefing.',
+ AGENT_TOP_JOBS: '- corpus upkeep\n- weekly memo\n- meeting prep',
+ PRINCIPAL_CONTEXT: 'Runs a small research group; values signal over noise.',
+ VOICE_REGISTER: 'Direct: three options, the second one wins.', MCP_SCOPE: 'user',
+ })) {
+ const r = setAnswer(ws, key, value);
+ if (!r.ok) throw new Error(r.message);
+ }
+ const h = readBackHash(ws);
+ if (!h.ok) throw new Error(h.message);
+ expect(confirm(ws, h.hash).ok).toBe(true);
+ return ws;
+}
+
+async function quiet<T>(fn: () => Promise<T>): Promise<{ result: T; err: string }> {
+ const [log, error] = [console.log, console.error];
+ let err = '';
+ console.log = () => {};
+ console.error = (...a: unknown[]) => { err += a.map(String).join(' ') + '\n'; };
+ try { return { result: await fn(), err }; } finally { console.log = log; console.error = error; }
+}
+
+describe('#8426, #8428: gbrain bootstrap hooks registers serve and writes its hooks through the launcher', () => {
+ test('claude-code: the user-scope claude mcp add argv and the workspace hooks', async () => {
+ const ws = bootstrapWorkspace();
+ const calls: string[][] = [];
+ const runner: ExecRunner = async (argv) => { calls.push(argv); return argv[1] === 'mcp' && argv[2] === 'list' ? { code: 0, stdout: 'gbrain: stdio serve', stderr: '' } : { code: 0, stdout: '', stderr: '' }; };
+ await withEnv(procEnv, async () => {
+ expect((await quiet(() => runBootstrap(['render', '--workspace', ws]))).result).toBe(0);
+ const r = await quiet(() => runBootstrap(['hooks', '--workspace', ws, '--harness', 'claude-code', '--gbrain-bin', gbrain], { runner }));
+ expect(r.result, r.err).toBe(0);
+ });
+ const add = calls.find((c) => c[0] === 'claude' && c[2] === 'add')!;
+ const serve = add.slice(add.indexOf('--') + 1);
+ expect(serve.slice(0, 3)).toEqual([launcher, gbrain, 'serve']);
+ clearMarker();
+ expect(await serveFromSession(serve[0]!, serve.slice(1), {}, 'notes/bootstrap-claude')).toBe('source-a');
+ expect(existsSync(marker)).toBe(false);
+
+ const settings = readJson(join(ws, '.claude', 'settings.local.json'));
+ const commands = Object.values(settings.hooks as Record<string, Array<{ hooks: Array<{ command: string; _gbrain?: string }> }>>)
+ .flatMap((groups) => groups.flatMap((g) => g.hooks.filter((h) => h._gbrain).map((h) => h.command)));
+ expect(commands.length).toBeGreaterThan(0);
+ for (const command of commands) {
+ expect(command).toContain(`${launcher} ${gbrain} hook`);
+ expect(runHook(command).exitCode).toBe(0);
+ expect(existsSync(marker)).toBe(false);
+ }
+ await waitForDetached();
+ }, 120_000);
+
+ test('codex: the codex mcp add argv and the SessionEnd capture', async () => {
+ const ws = bootstrapWorkspace();
+ const calls: string[][] = [];
+ const runner: ExecRunner = async (argv) => { calls.push(argv); return argv[1] === 'mcp' && argv[2] === 'list' ? { code: 0, stdout: 'gbrain: stdio serve', stderr: '' } : { code: 0, stdout: '', stderr: '' }; };
+ await withEnv(procEnv, async () => {
+ expect((await quiet(() => runBootstrap(['render', '--workspace', ws]))).result).toBe(0);
+ const r = await quiet(() => runBootstrap(['hooks', '--workspace', ws, '--harness', 'codex', '--gbrain-bin', gbrain], { runner }));
+ expect(r.result, r.err).toBe(0);
+ });
+ const add = calls.find((c) => c[0] === 'codex' && c[2] === 'add')!;
+ const serve = add.slice(add.indexOf('--') + 1);
+ expect(serve.slice(0, 3)).toEqual([launcher, gbrain, 'serve']);
+ clearMarker();
+ expect(await serveFromSession(serve[0]!, serve.slice(1), {}, 'notes/bootstrap-codex')).toBe('source-a');
+ expect(existsSync(marker)).toBe(false);
+
+ const hooks = readJson(join(home, '.codex', 'hooks.json'));
+ const capture = (hooks.hooks.SessionEnd as Array<{ hooks: Array<{ command: string }> }>).flatMap((g) => g.hooks.map((h) => h.command));
+ expect(capture.length).toBeGreaterThan(0);
+ for (const command of capture) {
+ expect(command).toContain(launcher);
+ expect(runHook(command).exitCode).toBe(0);
+ await waitForDetached();
+ expect(existsSync(marker)).toBe(false);
+ }
+ await withEnv(procEnv, async () => { expect(launcherLaneFindings().filter((f) => f.lane !== 'harness')).toEqual([]); });
+ }, 120_000);
+});
+
+describe('#8428: the harness and plugin hook lanes', () => {
+ test('gbrain bootstrap harness: the user-scope hooks start gbrain through the launcher', async () => {
+ const settings = join(root, 'harness-settings.json');
+ writeClaudeHooksAt(settings, { gbrainBin: gbrain, hookLauncher: launcher, env: { GBRAIN_HOOK_LANE: 'harness' }, marker: GBRAIN_HARNESS_MARKER_VALUE });
+ const commands = Object.values(readJson(settings).hooks as Record<string, Array<{ hooks: Array<{ command: string }> }>>).flatMap((groups) => groups.flatMap((g) => g.hooks.map((h) => h.command)));
+ expect(commands.length).toBeGreaterThan(0);
+ clearMarker();
+ for (const command of commands) {
+ expect(runHook(command).exitCode).toBe(0);
+ expect(existsSync(marker)).toBe(false);
+ }
+ await waitForDetached();
+ }, 120_000);
+
+ test('the plugin hook (Claude Code and Codex manifests) runs gbrain from the plugin launcher directory', () => {
+ const pluginRoot = join(root, 'plugin snapshot');
+ mkdirSync(join(pluginRoot, '.agents'), { recursive: true });
+ copyFileSync(join(ROOT, 'plugin-variants', 'gbrain-coding', '.agents', 'gbrain-launcher'), join(pluginRoot, '.agents', 'gbrain-launcher'));
+ chmodSync(join(pluginRoot, '.agents', 'gbrain-launcher'), 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) {
+ const m = readJson(join(ROOT, 'plugin-variants', 'gbrain-coding', file));
+ const command = ((m.hooks.hooks ?? m.hooks).UserPromptSubmit as Array<{ hooks: Array<{ command: string }> }>)[0]!.hooks[0]!.command;
+ expect(command).toContain(token);
+ clearMarker();
+ const r = runHook(command.replaceAll(token, pluginRoot), { GBRAIN_BIN: gbrain });
+ expect(r.exitCode, r.stderr).toBe(0);
+ expect(existsSync(marker)).toBe(false);
+ }
+ }, 120_000);
+});
diff --git a/test/setup.test.ts b/test/setup.test.ts
index 90e69db589..2498cc1411 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -34,7 +34,8 @@ import { ownedEntryFingerprint } from '../src/core/bootstrap/adopted-connections
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';
+import { hookLauncherFix, hookLauncherProblems } from '../src/commands/doctor/checks/harness-wiring.ts';
+import { launcherLaneFindings } 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');
@@ -1042,4 +1043,83 @@ describe('hooks written before the hook launcher (#8424): the next setup and pos
});
expect({ hooks: readFileSync(hooksJson(b), 'utf8'), config: readFileSync(codexToml(b), 'utf8') }).toEqual(before);
});
+
+ /** Rewrite setup's MCP entry to the pre-launcher shape (bin serve …); with own, the receipt still owns it by hash. */
+ function downgradeClaudeMcp(b: Box, own = true): Record<string, unknown> {
+ const cfg = readJson(claudeJson(b));
+ const entry = cfg.mcpServers.gbrain;
+ expect(entry.command).toBe(launcher(b));
+ const old = { ...entry, command: entry.args[0], args: entry.args.slice(1) };
+ cfg.mcpServers.gbrain = old;
+ writeFileSync(claudeJson(b), JSON.stringify(cfg, null, 2));
+ if (own) {
+ const r = readJson(receipt(b));
+ r.entry_hash = ownedEntryFingerprint(old);
+ writeFileSync(receipt(b), JSON.stringify(r, null, 2));
+ }
+ return old;
+ }
+
+ test('claude-code MCP (#8426): doctor flags a pre-launcher MCP entry setup still owns; post-upgrade moves it under the lock', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);
+ downgradeClaudeMcp(b);
+ await withEnv(env(b), async () => {
+ expect(hookLauncherProblem('claude-code')).toBeNull();
+ const problem = hookLauncherProblems([]);
+ expect(problem).toMatchObject({ harness: 'claude-code', lane: 'mcp', reason: 'session_cwd', owner: 'setup', setupOwned: true });
+ expect(hookLauncherFix(problem!)).toMatchObject({ actor: 'agent', argv: ['gbrain', 'setup', 'claude-code'] });
+ const lines: string[] = [];
+ await refreshHookLaunchers((l) => lines.push(l));
+ expect(lines.join('\n')).toContain("gbrain setup's claude-code MCP server and hooks now start gbrain from its own directory");
+ expect(launcherLaneFindings()).toEqual([]);
+ });
+ const moved = readJson(claudeJson(b)).mcpServers.gbrain;
+ expect([moved.command, ...moved.args.slice(0, 2)]).toEqual([launcher(b), b.bin, 'serve']);
+ expect((await setup(b, ['claude-code', '--json'])).doc.steps.map((s: any) => s.action)).toEqual(['keep', 'keep', 'keep']);
+ });
+
+ test('claude-code MCP (#8426): a pre-launcher MCP entry the user edited is kept; post-upgrade and doctor hand it to the user', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);
+ downgradeClaudeMcp(b, false);
+ const before = readFileSync(claudeJson(b), 'utf8');
+ await withEnv(env(b), async () => {
+ const lines: string[] = [];
+ await refreshHookLaunchers((l) => lines.push(l));
+ expect(lines.join('\n')).toContain("the 'gbrain' MCP server in");
+ expect(lines.join('\n')).toContain('it was edited after setup wrote it, so it is kept as is');
+ const problem = hookLauncherProblems([]);
+ expect(problem).toMatchObject({ lane: 'mcp', owner: 'none', edited: true, setupOwned: false });
+ const fix = hookLauncherFix(problem!);
+ expect(fix.actor).toBe('user');
+ expect(fix.user_message).toContain('Remove or rewrite that entry');
+ });
+ expect(readFileSync(claudeJson(b), 'utf8')).toBe(before);
+ });
+
+ 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);
+ const r = readJson(codexReceipt(b));
+ const toml = readFileSync(codexToml(b), 'utf8');
+ 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));
+ expect(toml).toContain(launcher(b));
+ const before = { hooks: readFileSync(hooksJson(b), 'utf8'), config: readFileSync(codexToml(b), 'utf8') };
+ await withEnv(env(b), async () => {
+ expect(hookLauncherProblem('codex')).toBeNull();
+ expect(hookLauncherProblems([])).toMatchObject({ harness: 'codex', lane: 'mcp', reason: 'session_cwd', owner: 'setup' });
+ const lines: string[] = [];
+ await refreshHookLaunchers((l) => lines.push(l));
+ expect(lines.join('\n')).toContain(`gbrain setup's codex MCP server in ${codexToml(b)} start gbrain in the session's directory; run gbrain setup codex to rewrite them`);
+ });
+ expect({ hooks: readFileSync(hooksJson(b), 'utf8'), config: readFileSync(codexToml(b), 'utf8') }).toEqual(before);
+ expect((await setup(b, ['codex', '--json'])).exitCode).toBe(0);
+ expect(readFileSync(codexToml(b), 'utf8')).toContain(launcher(b));
+ await withEnv(env(b), async () => { expect(launcherLaneFindings()).toEqual([]); });
+ });
});