Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: adversarial and outside-voice review fixes (#8424)

garrytan4da5b02a6d2f
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 39721e9943..316330f46e 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -124,7 +124,7 @@ import { HOOK_SUBCOMMANDS as HOOK_EVENTS, ROUTERS, subcommandHelpRequested } fro
import { isManagedFilesystemPath } from '../core/persistence/filesystem-guard.ts';
import { brainFirstTurnRule } from '../core/setup/brain-first.ts';
import { TURN_RULE_LANE, turnRuleHookYields } from '../core/setup/turn-hook.ts';
-import { hookSessionCwd } from '../core/setup/hook-launcher.ts';
+import { captureHookSessionCwd, hookSessionCwd } from '../core/setup/hook-launcher.ts';
// ── Tunables ────────────────────────────────────────────────────────────────
@@ -283,6 +283,7 @@ All events fail open: errors exit 0 with empty stdout and a heartbeat entry at
/** Dispatch a hook event. Returns the process exit code (0 for every runtime path). */
export async function runHook(args: string[], io: HookIo = {}): Promise<number> {
+ captureHookSessionCwd();
const event = args[0];
if (subcommandHelpRequested(args, ROUTERS.hook)) {
write(io, USAGE + '\n');
diff --git a/src/core/env-trust.ts b/src/core/env-trust.ts
index f01e7f8c59..768eb20710 100644
--- a/src/core/env-trust.ts
+++ b/src/core/env-trust.ts
@@ -186,6 +186,7 @@ export const CWD_DOTENV_PROTECTED_KEYS: readonly string[] = [
'GBRAIN_REMOTE_MCP_URL', // `init --remote` default: where the thin client sends its MCP traffic and bearer token
'GBRAIN_REMOTE_ISSUER_URL', // `init --remote` default: the OAuth issuer the client trusts and hands its credential to
'GBRAIN_OAUTH_RELAY_URL', // the OAuth relay that hands back Google tokens (creds/relay-client.ts): a planted relay is token theft
+ 'GBRAIN_HOOK_CWD', // #8424: the session directory the hook launcher records; a planted value moves the yield checks and the turn-rule project match
// --- re-run marker ------------------------------------------------------
'GBRAIN_CWD_ENV_QUARANTINED', // cli-preflight.ts's sanitized re-run marker; only honoured when the startup cwd IS the .env-free dir it names, so a planted one is inert — listed so it is also dropped and named in the warning
// --- posture-widening ----------------------------------------------------
diff --git a/src/core/setup/claude-code.ts b/src/core/setup/claude-code.ts
index 4ad4f083c2..e12e9806b5 100644
--- a/src/core/setup/claude-code.ts
+++ b/src/core/setup/claude-code.ts
@@ -270,7 +270,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 },
+ opts: { pluginOwner: string | null; brainCreated: boolean; beforeMcp?: () => Promise<void>; abortAfter?: string; mcpMustBeCurrent?: boolean },
): Promise<ApplyResult> {
const paths = claudeSetupPaths(plan);
const lock = await acquireBootstrapLock(dirname(paths.configPath));
@@ -278,6 +278,7 @@ export async function applyClaudeSetup(
// Every hook command starts gbrain through the launcher, so it goes down before anything names it (#8424).
if (plan.events.length) 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`);
const now = new Date().toISOString();
const desired = desiredMcpEntry(plan);
const desiredHash = entryHash(desired);
diff --git a/src/core/setup/codex.ts b/src/core/setup/codex.ts
index 0d632f1a61..cb6f3861ac 100644
--- a/src/core/setup/codex.ts
+++ b/src/core/setup/codex.ts
@@ -233,7 +233,7 @@ export interface CodexApplyResult { steps: CodexSetupStep[]; receipt: CodexSetup
export async function applyCodexSetup(
plan: CodexSetupPlan,
consent: SetupConsent,
- opts: { pluginOwner: string | null; brainCreated: boolean; beforeMcp?: () => Promise<void>; abortAfter?: string },
+ opts: { pluginOwner: string | null; brainCreated: boolean; beforeMcp?: () => Promise<void>; abortAfter?: string; mcpMustBeCurrent?: boolean },
): Promise<CodexApplyResult> {
const paths = codexSetupPaths(plan.name);
mkdirSync(dirname(paths.configPath), { recursive: true, mode: 0o700 });
@@ -242,6 +242,7 @@ export async function applyCodexSetup(
// Every hook command starts gbrain through the launcher, so it goes down before anything names it (#8424).
if (plan.events.length) ensureHookLauncher(hookLauncherPath(plan.brainHome));
const found = inspectCodexSetup(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`);
const prior = found.prior;
const now = new Date().toISOString();
const desired = desiredCodexMcpEntry(plan);
diff --git a/src/core/setup/hook-launcher-refresh.ts b/src/core/setup/hook-launcher-refresh.ts
index e8402cef89..651294580c 100644
--- a/src/core/setup/hook-launcher-refresh.ts
+++ b/src/core/setup/hook-launcher-refresh.ts
@@ -18,12 +18,13 @@
import { readFileSync } from 'node:fs';
import { configDir } from '../config.ts';
import { hookEntryHash, parseClaudeHookCommand } from '../bootstrap/hooks.ts';
-import { codexHookCensus } from '../bootstrap/codex-hooks.ts';
-import { GBRAIN_HOOK_MARKER_KEY, GBRAIN_SETUP_MARKER_VALUE, claudeUserSettingsPath, codexHooksPath, type ClaudeHookEvent } from '../bootstrap/host-specs.ts';
+import { codexHookCensus, codexHookGroupRuns, type CodexHookCensusGroup } from '../bootstrap/codex-hooks.ts';
+import { join } from 'node:path';
+import { GBRAIN_HOOK_MARKER_KEY, GBRAIN_SETUP_MARKER_VALUE, claudeUserSettingsPath, codexConfigPath, codexHooksPath, type ClaudeHookEvent } from '../bootstrap/host-specs.ts';
import type { CodexSetupEvent } from '../bootstrap/codex-hooks.ts';
import { applyClaudeSetup, claudeSetupPaths, inspectClaudeSetup, readSetupReceipt, type ClaudeSetupPlan } from './claude-code.ts';
import { applyCodexSetup, codexSetupPaths, inspectCodexSetup, readCodexSetupReceipt, type CodexSetupPlan } from './codex.ts';
-import { hookLauncherInCommand, hookLauncherState, shellWords } from './hook-launcher.ts';
+import { hookLauncherInCommand, hookLauncherPath, hookLauncherState, shellWords } from './hook-launcher.ts';
import { localSetupRecords } from './local-receipts.ts';
import { hasTurnRuleHook, isTurnRuleEntry, syncTurnRuleHook, TURN_RULE_LANE_TOKEN } from './turn-hook.ts';
@@ -55,20 +56,25 @@ function codexCommandParts(command: string): { gbrainBin: string; gbrainHome?: s
return gbrainBin?.startsWith('/') ? { gbrainBin, ...(gbrainHome ? { gbrainHome } : {}) } : null;
}
+/** The launcher of the install the hook's GBRAIN_HOME names, so a hook never depends on another install's directory. */
+const launcherFor = (gbrainHome: string | undefined) => (gbrainHome ? { hookLauncher: hookLauncherPath(join(gbrainHome, '.gbrain')) } : {});
+
function refreshTurnRule(log: (line: string) => void): void {
const claude = claudeHookEntries(claudeUserSettingsPath()).filter(isTurnRuleEntry).map((e) => e.command as string).find(needsLauncher);
const claudeParsed = claude ? parseClaudeHookCommand(claude) : null;
if (claude && claudeParsed) {
- const o = syncTurnRuleHook({ harness: 'claude-code', gbrainBin: claudeParsed.gbrainBin, gbrainHome: claudeParsed.env.GBRAIN_HOME, rerun: 'gbrain setup claude-code --instructions-only' });
+ const o = syncTurnRuleHook({ harness: 'claude-code', gbrainBin: claudeParsed.gbrainBin, gbrainHome: claudeParsed.env.GBRAIN_HOME, paths: launcherFor(claudeParsed.env.GBRAIN_HOME), rerun: 'gbrain setup claude-code --instructions-only' });
log(`Hook launcher: claude-code turn-rule hook ${o.action === 'write' ? 'now starts gbrain from its own directory' : `left as is (${o.detail}${o.next ? `; run ${o.next}` : ''})`}.`);
} else if (claude) log('Hook launcher: the claude-code turn-rule hook was edited, so it is left as is; run `gbrain setup claude-code --instructions-only` to rewrite it.');
if (!hasTurnRuleHook('codex')) return;
- let command: string | undefined;
- try { command = codexHookCensus(codexHooksPath()).filter((g) => g.lane === 'turn-rule').flatMap((g) => g.commands).find((c) => c.includes(TURN_RULE_LANE_TOKEN) && needsLauncher(c)); } catch { return; }
- if (!command) return;
- const parts = codexCommandParts(command);
+ let group: CodexHookCensusGroup | undefined;
+ try { group = codexHookCensus(codexHooksPath()).find((g) => g.lane === 'turn-rule' && g.commands.some((c) => c.includes(TURN_RULE_LANE_TOKEN) && needsLauncher(c))); } catch { return; }
+ if (!group) return;
+ // Rewriting re-trusts the group, so only a group Codex already runs moves: an untrusted or disabled one keeps Codex's approval gate.
+ if (!codexHookGroupRuns(codexHooksPath(), codexConfigPath(), group)) { log('Hook launcher: Codex does not run the codex turn-rule hook (not trusted, or disabled), so it is left as is; run `gbrain setup codex --instructions-only` to rewrite it.'); return; }
+ const parts = codexCommandParts(group.commands.find((c) => c.includes(TURN_RULE_LANE_TOKEN))!);
if (!parts) { log('Hook launcher: the codex turn-rule hook could not be read, so it is left as is; run `gbrain setup codex --instructions-only` to rewrite it.'); return; }
- const o = syncTurnRuleHook({ harness: 'codex', gbrainBin: parts.gbrainBin, gbrainHome: parts.gbrainHome, rerun: 'gbrain setup codex --instructions-only' });
+ const o = syncTurnRuleHook({ harness: 'codex', gbrainBin: parts.gbrainBin, gbrainHome: parts.gbrainHome, paths: launcherFor(parts.gbrainHome), rerun: 'gbrain setup codex --instructions-only' });
log(`Hook launcher: codex turn-rule hook ${o.action === 'write' ? 'now starts gbrain from its own directory' : `left as is (${o.detail}${o.next ? `; run ${o.next}` : ''})`}.`);
}
@@ -89,7 +95,7 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {
const plan: ClaudeSetupPlan = { name: receipt.name, scope: receipt.scope, launcher: receipt.launcher, brainHome: receipt.gbrain_home, ...(homeEnv ? { gbrainHomeEnv: homeEnv } : {}),
sourceId: receipt.source_id, surface: receipt.surface, advertise: receipt.advertise ?? null, events: Object.keys({ ...receipt.hooks.owned, ...receipt.hooks.pending }) as ClaudeHookEvent[] };
if (!receipt.mcp_plugin && inspectClaudeSetup(plan).mcp.state !== 'current') { log(`Hook launcher: gbrain's claude-code hooks start gbrain in the session's directory; run ${rerun} to rewrite them.`); continue; }
- const applied = await applyClaudeSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false });
+ const applied = await applyClaudeSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false, mcpMustBeCurrent: 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
@@ -104,7 +110,7 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {
const plan: CodexSetupPlan = { name: receipt.name, launcher: receipt.launcher, brainHome: receipt.gbrain_home, ...(receipt.gbrain_home_env ? { gbrainHomeEnv: receipt.gbrain_home_env } : {}),
sourceId: receipt.source_id, surface: receipt.surface, advertise: receipt.advertise ?? null, events: Object.keys({ ...receipt.hooks.owned, ...receipt.hooks.pending }) as CodexSetupEvent[] };
if (!receipt.mcp_plugin && inspectCodexSetup(plan).mcp.state !== 'current') { log(`Hook launcher: gbrain's codex hooks start gbrain in the session's directory; run ${rerun} to rewrite them.`); continue; }
- const applied = await applyCodexSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false });
+ const applied = await applyCodexSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false, mcpMustBeCurrent: true });
const left = new Set(codexHookCensus(paths.hooksPath).filter((g) => g.commands.some(needsLauncher)).map((g) => g.hash));
const kept = Object.entries(applied.receipt.hooks.edited).filter(([, hash]) => left.has(hash)).map(([event]) => event);
log(kept.length > 0
diff --git a/src/core/setup/hook-launcher.ts b/src/core/setup/hook-launcher.ts
index b7d479f442..f768245714 100644
--- a/src/core/setup/hook-launcher.ts
+++ b/src/core/setup/hook-launcher.ts
@@ -19,7 +19,7 @@
* session directory from GBRAIN_HOOK_CWD where it used process.cwd().
*/
import { randomBytes } from 'node:crypto';
-import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { configDir } from '../config.ts';
@@ -138,8 +138,22 @@ export function hookLauncherInCommand(command: string): string | null {
return shellWords(command)?.find((w) => w.startsWith('/') && w.endsWith(suffix)) ?? null;
}
+let capturedSessionCwd: string | null = null;
+
+/**
+ * `gbrain hook` start: take the session directory the launcher recorded and
+ * drop it from the environment, so no child inherits a stale value. Resolved
+ * like process.cwd() (sh keeps a symlinked $PWD), so project matching against
+ * setup's realpath'd directories still holds.
+ */
+export function captureHookSessionCwd(): void {
+ const recorded = process.env[HOOK_CWD_ENV];
+ delete process.env[HOOK_CWD_ENV];
+ if (!recorded || !recorded.startsWith('/')) { capturedSessionCwd = null; return; }
+ try { capturedSessionCwd = realpathSync(recorded); } catch { capturedSessionCwd = recorded; }
+}
+
/** The session directory for `gbrain hook`: what the launcher recorded, else this process's directory. */
export function hookSessionCwd(): string {
- const recorded = process.env[HOOK_CWD_ENV];
- return recorded && recorded.startsWith('/') ? recorded : process.cwd();
+ return capturedSessionCwd ?? process.cwd();
}
diff --git a/test/hook-launcher-bunfig.test.ts b/test/hook-launcher-bunfig.test.ts
index e1b1fde849..848a00af42 100644
--- a/test/hook-launcher-bunfig.test.ts
+++ b/test/hook-launcher-bunfig.test.ts
@@ -8,12 +8,14 @@
* and Codex run it. The marker must never appear.
*/
import { afterAll, describe, expect, test } from 'bun:test';
-import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { withEnv } from './helpers/with-env.ts';
import { buildClaudeHookCommand } from '../src/core/bootstrap/hooks.ts';
-import { codexSetupHookGroup } from '../src/core/bootstrap/codex-hooks.ts';
+import { codexHookGroupRuns, codexHookTrustHash, codexSetupHookGroup } from '../src/core/bootstrap/codex-hooks.ts';
+import { appendCodexTomlTable } from '../src/core/bootstrap/codex-toml.ts';
+import { captureHookSessionCwd, hookSessionCwd } from '../src/core/setup/hook-launcher.ts';
import { syncTurnRuleHook, TURN_RULE_MARKER } from '../src/core/setup/turn-hook.ts';
import { hookLauncherProblem } from '../src/core/setup/turn-hook-check.ts';
import { HOOK_LAUNCHER_NAME, ensureHookLauncher, hookLauncherInCommand, hookLauncherPath, hookLauncherState } from '../src/core/setup/hook-launcher.ts';
@@ -211,6 +213,8 @@ describe('hooks written before the launcher: doctor flags them, post-upgrade mov
const old = codexSetupHookGroup(b.gbrain, 'UserPromptSubmit', {}, 'turn-rule');
mkdirSync(dirname(hooks), { recursive: true });
writeFileSync(hooks, JSON.stringify({ hooks: { UserPromptSubmit: [old] } }));
+ appendCodexTomlTable(config, ['hooks', 'state', `${hooks}:user_prompt_submit:0:0`], { trusted_hash: codexHookTrustHash('user_prompt_submit', old.hooks[0]!.command, old.hooks[0]!.timeout) }, 'test: Codex trusted the old hook');
+ expect(codexHookGroupRuns(hooks, config, { event: 'UserPromptSubmit', index: 0 })).toBe(true);
expect(hookLauncherProblem('codex')).toMatchObject({ lane: 'turn-rule', reason: 'session_cwd' });
await refreshHookLaunchers(() => {});
expect(hookLauncherProblem('codex')).toBeNull();
@@ -221,6 +225,39 @@ describe('hooks written before the launcher: doctor flags them, post-upgrade mov
expect(existsSync(b.marker)).toBe(false);
});
+ test('codex: a turn-rule group Codex never trusted is left as is, so post-upgrade grants no trust', async () => {
+ const b = box();
+ const hooks = join(b.home, '.codex', 'hooks.json');
+ const config = join(b.home, '.codex', 'config.toml');
+ const payload = join(b.hostile, 'tooling', 'payload');
+ const group = { hooks: [{ type: 'command', command: `env GBRAIN_HOOK_LANE=turn-rule ${payload} hook user-prompt --harness codex`, timeout: 15 }] };
+ mkdirSync(dirname(hooks), { recursive: true });
+ writeFileSync(hooks, JSON.stringify({ hooks: { UserPromptSubmit: [group] } }));
+ writeFileSync(config, '');
+ await withEnv(env(b), async () => {
+ const lines: string[] = [];
+ await refreshHookLaunchers((l) => lines.push(l));
+ expect(lines.join('\n')).toContain('Codex does not run the codex turn-rule hook');
+ });
+ expect(readJson(hooks)).toEqual({ hooks: { UserPromptSubmit: [group] } });
+ expect(codexHookGroupRuns(hooks, config, { event: 'UserPromptSubmit', index: 0 })).toBe(false);
+ });
+
+ test('the recorded session directory is resolved and dropped from the environment', async () => {
+ const b = box();
+ const link = join(b.root, 'link-to-checkout');
+ symlinkSync(b.hostile, link);
+ await withEnv({ GBRAIN_HOOK_CWD: link }, async () => {
+ captureHookSessionCwd();
+ expect(process.env.GBRAIN_HOOK_CWD).toBeUndefined();
+ expect(hookSessionCwd()).toBe(realpathSync(b.hostile));
+ });
+ await withEnv({ GBRAIN_HOOK_CWD: 'relative/dir' }, async () => {
+ captureHookSessionCwd();
+ expect(hookSessionCwd()).toBe(process.cwd());
+ });
+ });
+
test('a launcher whose directory gained a foreign file is flagged foreign', async () => {
const b = box();
await withEnv(env(b), async () => {
diff --git a/test/setup.test.ts b/test/setup.test.ts
index a8e19ffbe5..3fa9f057a0 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -35,6 +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 } from '../src/commands/doctor/checks/harness-wiring.ts';
+import { applyClaudeSetup, readSetupReceipt } from '../src/core/setup/claude-code.ts';
const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');
const roots: string[] = [];
@@ -967,6 +968,22 @@ describe('hooks written before the hook launcher (#8424): the next setup and pos
expect(entries(b, 'SessionStart').every((e) => e.command.includes(launcher(b)))).toBe(true);
});
+ test('claude-code: the hook rewrite refuses under the lock when the MCP entry is no longer setup\'s, and writes nothing', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);
+ downgradeClaude(b);
+ const r = readSetupReceipt(receipt(b)).setup!;
+ const cfg = readJson(claudeJson(b));
+ cfg.mcpServers.gbrain = { type: 'http', url: 'https://new-brain.example/mcp' };
+ writeFileSync(claudeJson(b), JSON.stringify(cfg, null, 2));
+ const 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');
+ });
+ expect({ settings: readFileSync(settings(b), 'utf8'), config: readFileSync(claudeJson(b), 'utf8') }).toEqual(before);
+ });
+
test('claude-code: --instructions-only moves a pre-launcher turn-rule entry that sits beside setup hooks', async () => {
const b = box();
expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);