Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(security): review round 1 for the hook launcher (#8424)

garrytan13d297fa9e89
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c661dab04..bb9df0bcbe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,8 @@ identifiers and attribution are available in the pre-removal Git revision
- `gbrain post-upgrade` moves existing hooks onto the launcher: the turn-rule hook in Claude Code's user settings and Codex's hooks.json, and the hooks of each user-scope `gbrain setup` install whose MCP entry is unchanged. `gbrain setup <harness>` and `gbrain setup <harness> --instructions-only` rewrite them on their next run.
- `gbrain doctor` (`harness_wiring`) warns with the new code `hook_session_cwd` when a hook still starts gbrain in the session directory, or its launcher is missing, changed or shares its directory with a file gbrain did not write, and names the setup command that fixes it. Project-scope installs get the command to run from their project directory.
-- Not covered yet: the capture hooks from `gbrain bootstrap`'s own lanes and the gbrain plugins' hooks, and script-mode commands you run by hand in an untrusted checkout (SECURITY.md).
+- Not covered yet: the stdio MCP server `gbrain setup` registers, which the harness also starts in the session's directory (#8426); the capture hooks from `gbrain bootstrap`'s own lanes and the gbrain plugins' hooks (#8428); and script-mode commands you run by hand in an untrusted checkout (SECURITY.md).
+- The launcher rewrite never leaves a temp file in its own directory, and doctor finds a setup hook whose `_gbrain` marker Claude Code dropped by its receipt hash.
## [0.60.545.0] - 2026-11-02
diff --git a/SECURITY.md b/SECURITY.md
index 4eaf3fe0cc..b08379520d 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -95,8 +95,12 @@ launcher; if anything else appears there, the launcher refuses to start gbrain
and prints one line to stderr. `gbrain post-upgrade` moves hooks written
before the launcher onto it, `gbrain setup` rewrites them on its next run, and
`gbrain doctor` (`harness_wiring`, code `hook_session_cwd`) flags any that are
-left. Hooks from `gbrain bootstrap`'s own capture lanes and from the gbrain
-plugins do not go through the launcher yet.
+left. Not covered yet: the stdio MCP server `gbrain setup` registers, which
+the harness also starts in the session's directory (#8426), and the hooks from
+`gbrain bootstrap`'s own capture lanes and the gbrain plugins (#8428). Until
+those land, a script-mode install still runs a session directory's
+`bunfig.toml` preload once per session through the MCP server; the release
+binary does not.
**The trust boundary.** Security-relevant variables are honored from your
shell environment, from a service `EnvironmentFile`, and from
diff --git a/src/core/bootstrap/codex-hooks.ts b/src/core/bootstrap/codex-hooks.ts
index afcc832ad9..c0e2b7fc16 100644
--- a/src/core/bootstrap/codex-hooks.ts
+++ b/src/core/bootstrap/codex-hooks.ts
@@ -119,8 +119,8 @@ function shellQuote(arg: string): string {
*/
export function buildCodexSessionEndCommand(gbrainBin: string, launcher?: string): string {
const script = launcher
- ? 't="$(mktemp)"; cat >"$t"; GBRAIN_PAYLOAD="$t" GBRAIN_LAUNCHER="$0" GBRAIN_BIN="$1" nohup sh -c ' +
- `'"$GBRAIN_LAUNCHER" "$GBRAIN_BIN" ${CODEX_HOOK_OWNERSHIP_TOKEN} <"$GBRAIN_PAYLOAD"; rm -f "$GBRAIN_PAYLOAD"' >/dev/null 2>&1 &`
+ ? 't="$(mktemp)"; cat >"$t"; GBRAIN_PAYLOAD="$t" GBRAIN_HOOK_LAUNCHER="$0" GBRAIN_BIN="$1" nohup sh -c ' +
+ `'"$GBRAIN_HOOK_LAUNCHER" "$GBRAIN_BIN" ${CODEX_HOOK_OWNERSHIP_TOKEN} <"$GBRAIN_PAYLOAD"; rm -f "$GBRAIN_PAYLOAD"' >/dev/null 2>&1 &`
: 't="$(mktemp)"; cat >"$t"; GBRAIN_PAYLOAD="$t" GBRAIN_BIN="$0" nohup sh -c ' +
`'"$GBRAIN_BIN" ${CODEX_HOOK_OWNERSHIP_TOKEN} <"$GBRAIN_PAYLOAD"; rm -f "$GBRAIN_PAYLOAD"' >/dev/null 2>&1 &`;
// Embed the script into an outer single-quoted argument: ' → '\'' works
diff --git a/src/core/bootstrap/hooks.ts b/src/core/bootstrap/hooks.ts
index ff0f7600bc..08f044d377 100644
--- a/src/core/bootstrap/hooks.ts
+++ b/src/core/bootstrap/hooks.ts
@@ -303,7 +303,7 @@ export function classifyHarnessHook(
const sub = (CLAUDE_HOOK_SUBCOMMAND as Record<string, string | undefined>)[event];
if (!sub || !/(?:^|[\s'])GBRAIN_HOOK_LANE=harness(?=[\s']|$)/.test(e.command) || !/\shook(?:\s|$)/.test(e.command)) return null;
const parsed = parseClaudeHookCommand(e.command);
- if (!parsed || parsed.env.GBRAIN_HOOK_LANE !== 'harness' || parsed.subcommand !== sub) {
+ if (!parsed || parsed.launcher !== undefined || parsed.env.GBRAIN_HOOK_LANE !== 'harness' || parsed.subcommand !== sub) {
return { ownership: 'unowned', why: `not the exact \`hook ${sub}\` command gbrain writes (edited or extended)` };
}
if (identity === 'any') return { ownership: 'command', why: 'harness hook command shape' };
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 45925eedf1..470a51ed67 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -75,7 +75,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'git': ['--abbrev-ref', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--autostash', '--batch-check', '--brain', '--branch', '--cached', '--cacheinfo', '--cherry-mark', '--count', '--dry-run', '--enable', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--force-with-lease', '--format', '--get', '--get-all', '--get-url', '--git-dir', '--git-path', '--hard', '--help', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--name-only', '--name-status', '--no-autostash', '--no-commit-id', '--no-cron', '--no-gpg-sign', '--no-merges', '--no-recurse-submodules', '--no-renames', '--no-tags', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--repo', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--short', '--show-toplevel', '--source', '--staged', '--stat', '--topo-order', '--type', '--uninstall', '--unset-all', '--untracked-files', '--verify', '--write-tree'],
'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--probe', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],
- 'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--gbrain-bin', '--get', '--harness', '--help', '--instructions', '--instructions-only', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--workspace', '--yes'],
+ 'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--gbrain-bin', '--get', '--harness', '--help', '--instructions', '--instructions-only', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--workspace', '--yes'],
'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],
'init': ['--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--as', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
@@ -95,7 +95,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'orphans': ['--accept-pending', '--all', '--as', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--literal-pathspecs', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],
- 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--advertise', '--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],
'protocol': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
@@ -137,7 +137,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],
'trust': ['--accept-all', '--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
- 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
diff --git a/src/core/setup/hook-launcher-refresh.ts b/src/core/setup/hook-launcher-refresh.ts
index 2840da28d9..a90151e394 100644
--- a/src/core/setup/hook-launcher-refresh.ts
+++ b/src/core/setup/hook-launcher-refresh.ts
@@ -17,13 +17,13 @@
*/
import { readFileSync } from 'node:fs';
import { configDir } from '../config.ts';
-import { parseClaudeHookCommand } from '../bootstrap/hooks.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 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 } from './hook-launcher.ts';
+import { hookLauncherInCommand, hookLauncherState, shellWords } from './hook-launcher.ts';
import { localSetupRecords } from './local-receipts.ts';
import { hasTurnRuleHook, isTurnRuleEntry, syncTurnRuleHook, TURN_RULE_LANE_TOKEN } from './turn-hook.ts';
@@ -44,7 +44,7 @@ function claudeHookEntries(path: string): Array<Record<string, unknown>> {
/** The words after \`env\` that are not assignments: [<launcher>] <bin> hook …; GBRAIN_HOME from the assignments. */
function codexCommandParts(command: string): { gbrainBin: string; gbrainHome?: string } | null {
- const words = command.match(/'(?:[^']|'\\'')*'|\S+/g)?.map((w) => (w.startsWith("'") ? w.slice(1, -1).replace(/'\\''/g, "'") : w)) ?? [];
+ const words = shellWords(command) ?? [];
if (words[0] !== 'env') return null;
let i = 1;
let gbrainHome: string | undefined;
@@ -81,7 +81,8 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {
const receipt = readSetupReceipt(record.path).setup;
if (!receipt) continue;
const paths = claudeSetupPaths({ name: receipt.name, scope: receipt.scope, projectDir: receipt.project_dir });
- const ours = claudeHookEntries(paths.settingsPath).filter((e) => e[GBRAIN_HOOK_MARKER_KEY] === GBRAIN_SETUP_MARKER_VALUE).map((e) => e.command as string);
+ 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);
diff --git a/src/core/setup/hook-launcher.ts b/src/core/setup/hook-launcher.ts
index e4b58e30d0..b7d479f442 100644
--- a/src/core/setup/hook-launcher.ts
+++ b/src/core/setup/hook-launcher.ts
@@ -18,9 +18,9 @@
* starting Bun next to a file gbrain did not write. `gbrain hook` reads the
* session directory from GBRAIN_HOOK_CWD where it used process.cwd().
*/
-import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
+import { randomBytes } from 'node:crypto';
+import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
-import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
import { configDir } from '../config.ts';
export const HOOK_LAUNCHER_NAME = 'gbrain-hook';
@@ -82,16 +82,60 @@ export function ensureHookLauncher(path: string = hookLauncherPath()): string {
chmodSync(dir, 0o700);
const other = readdirSync(dir).find((n) => n !== HOOK_LAUNCHER_NAME);
if (other !== undefined) throw new Error(`${dir} holds ${other}, which gbrain did not write; the hook launcher runs gbrain from that directory, so remove it, then run this again`);
- if (hookLauncherState(path).state !== 'current') atomicWriteTextFile(path, HOOK_LAUNCHER_SCRIPT, { forceMode: 0o700 });
+ if (hookLauncherState(path).state === 'current') return path;
+ // The temp file sits beside the directory, never in it: a hook running meanwhile would refuse to start next to it.
+ const tmp = join(dirname(dir), `.${HOOK_LAUNCHER_DIR}.tmp-${randomBytes(6).toString('hex')}`);
+ try {
+ writeFileSync(tmp, HOOK_LAUNCHER_SCRIPT, { mode: 0o700 });
+ chmodSync(tmp, 0o700);
+ renameSync(tmp, path);
+ } catch (e) {
+ rmSync(tmp, { force: true });
+ throw e;
+ }
return path;
}
-const LAUNCHER_WORD = new RegExp(`(?:^|\\s)(?:'(/[^']*/${HOOK_LAUNCHER_DIR}/${HOOK_LAUNCHER_NAME})'|(/[^\\s']*/${HOOK_LAUNCHER_DIR}/${HOOK_LAUNCHER_NAME}))(?=\\s)`);
+/**
+ * Split a hook command into shell words the way /bin/sh would at its top
+ * level: single quotes, double quotes and backslash escapes, so a path the
+ * builders quoted (`'/a/o'\''b/x'`) comes back as the path. Null for an
+ * unterminated quote.
+ */
+export function shellWords(command: string): string[] | null {
+ const words: string[] = [];
+ let word: string | null = null;
+ for (let i = 0; i < command.length; i++) {
+ const c = command[i]!;
+ if (c === ' ' || c === '\t' || c === '\n') { if (word !== null) words.push(word); word = null; continue; }
+ word ??= '';
+ if (c === "'") {
+ const close = command.indexOf("'", i + 1);
+ if (close < 0) return null;
+ word += command.slice(i + 1, close);
+ i = close;
+ } else if (c === '"') {
+ let j = i + 1;
+ for (; j < command.length && command[j] !== '"'; j++) {
+ if (command[j] === '\\' && j + 1 < command.length && '$`"\\\n'.includes(command[j + 1]!)) j++;
+ word += command[j];
+ }
+ if (j >= command.length) return null;
+ i = j;
+ } else if (c === '\\' && i + 1 < command.length) {
+ word += command[++i];
+ } else {
+ word += c;
+ }
+ }
+ if (word !== null) words.push(word);
+ return words;
+}
/** The launcher a hook command runs gbrain through, or null for a command that starts gbrain in the session directory. */
export function hookLauncherInCommand(command: string): string | null {
- const m = LAUNCHER_WORD.exec(command);
- return m ? (m[1] ?? m[2])! : null;
+ const suffix = `/${HOOK_LAUNCHER_DIR}/${HOOK_LAUNCHER_NAME}`;
+ return shellWords(command)?.find((w) => w.startsWith('/') && w.endsWith(suffix)) ?? null;
}
/** The session directory for `gbrain hook`: what the launcher recorded, else this process's directory. */
diff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.ts
index 031870fae5..12ac606a01 100644
--- a/src/core/setup/turn-hook-check.ts
+++ b/src/core/setup/turn-hook-check.ts
@@ -17,7 +17,8 @@ import type { Action } from '../agent-output.ts';
import { bunSpawnSync } from '../spawn.ts';
import { codexHookCensus, codexHookGroupRuns, codexHookTrustHash } from '../bootstrap/codex-hooks.ts';
import { readCodexTomlTable } from '../bootstrap/codex-toml.ts';
-import { classifyHarnessHook } from '../bootstrap/hooks.ts';
+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 { enabledPluginLanes } from '../bootstrap/plugin-lanes.ts';
@@ -130,7 +131,17 @@ export interface HookLauncherProblem {
detail: string;
}
-function claudeLaneCommands(path: string): Array<{ lane: 'setup' | 'turn-rule'; command: string }> {
+/** The hook hashes Claude Code setup receipts own: Claude Code can drop the `_gbrain` marker on a rewrite, and setup owns its entries by hash. */
+function claudeSetupOwnedHashes(): Set<string> {
+ const out = new Set<string>();
+ for (const r of localSetupRecords().filter((x) => x.harness === 'claude-code')) {
+ const hooks = (readJson(r.path) as { hooks?: { owned?: Record<string, unknown>; pending?: Record<string, unknown> } } | null)?.hooks;
+ for (const h of [...Object.values(hooks?.owned ?? {}), ...Object.values(hooks?.pending ?? {})]) if (typeof h === 'string') out.add(h);
+ }
+ return out;
+}
+
+function claudeLaneCommands(path: string, setupOwned: Set<string>): Array<{ lane: 'setup' | 'turn-rule'; command: string }> {
const hooks = readJson(path)?.hooks;
if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) return [];
const out: Array<{ lane: 'setup' | 'turn-rule'; command: string }> = [];
@@ -140,7 +151,7 @@ function claudeLaneCommands(path: string): Array<{ lane: 'setup' | 'turn-rule';
if (!e || typeof e !== 'object' || typeof (e as Record<string, unknown>).command !== 'string') continue;
const entry = e as Record<string, unknown>;
if (isTurnRuleEntry(entry)) out.push({ lane: 'turn-rule', command: entry.command as string });
- else if (entry[GBRAIN_HOOK_MARKER_KEY] === GBRAIN_SETUP_MARKER_VALUE) out.push({ lane: 'setup', command: entry.command as string });
+ else if (entry[GBRAIN_HOOK_MARKER_KEY] === GBRAIN_SETUP_MARKER_VALUE || setupOwned.has(hookEntryHash(entry) ?? '')) out.push({ lane: 'setup', command: entry.command as string });
}
}
return out;
@@ -150,8 +161,9 @@ function claudeLaneCommands(path: string): Array<{ lane: 'setup' | 'turn-rule';
export function hookLauncherProblem(harness: 'claude-code' | 'codex', opts: { projectDir?: string } = {}): HookLauncherProblem | null {
const found: Array<{ lane: 'setup' | 'turn-rule'; command: string; source: string }> = [];
if (harness === 'claude-code') {
+ const setupOwned = claudeSetupOwnedHashes();
for (const source of [claudeUserSettingsPath(), ...(opts.projectDir ? [join(opts.projectDir, CLAUDE_SETTINGS_FILE_RELPATH)] : [])]) {
- found.push(...claudeLaneCommands(source).map((c) => ({ ...c, source })));
+ found.push(...claudeLaneCommands(source, setupOwned).map((c) => ({ ...c, source })));
}
} else {
try {
diff --git a/test/bootstrap-harness-hook-ownership.test.ts b/test/bootstrap-harness-hook-ownership.test.ts
index 55a013c7c9..a861e62af1 100644
--- a/test/bootstrap-harness-hook-ownership.test.ts
+++ b/test/bootstrap-harness-hook-ownership.test.ts
@@ -143,6 +143,12 @@ describe('classifyHarnessHook: grammar is not ownership', () => {
expect(classifyHarnessHook(entry(buildClaudeHookCommand(BIN, 'Stop', { GBRAIN_SOURCE: 'ws' })), 'Stop', ME)).toBeNull();
expect(classifyHarnessHook(entry('echo hi'), 'Stop', ME)).toBeNull();
});
+
+ test('#8424: a wrapper in front of this install\'s binary is the user\'s, never an owned harness command', () => {
+ const wrapped = entry(buildClaudeHookCommand(BIN, 'Stop', HARNESS_ENV, '/opt/example/user-wrapper'));
+ expect(classifyHarnessHook(wrapped, 'Stop', ME)?.ownership).toBe('unowned');
+ expect(classifyHarnessHook(wrapped, 'Stop', 'any')?.ownership).toBe('unowned');
+ });
});
describe('harnessHookIdentity', () => {
diff --git a/test/hook-launcher-bunfig.test.ts b/test/hook-launcher-bunfig.test.ts
index 3923e5e8e5..f07e96d05e 100644
--- a/test/hook-launcher-bunfig.test.ts
+++ b/test/hook-launcher-bunfig.test.ts
@@ -16,7 +16,7 @@ import { buildClaudeHookCommand } from '../src/core/bootstrap/hooks.ts';
import { codexSetupHookGroup } from '../src/core/bootstrap/codex-hooks.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, hookLauncherPath, hookLauncherState } from '../src/core/setup/hook-launcher.ts';
+import { HOOK_LAUNCHER_NAME, ensureHookLauncher, hookLauncherInCommand, hookLauncherPath, hookLauncherState } from '../src/core/setup/hook-launcher.ts';
import { refreshHookLaunchers } from '../src/core/setup/hook-launcher-refresh.ts';
const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');
@@ -133,6 +133,27 @@ describe('the launcher', () => {
expect(() => ensureHookLauncher(b.launcher)).toThrow(/did not write/);
});
+ test('a launcher path with quotes and spaces is found in every command shape, so doctor does not flag a current hook', async () => {
+ const b = box();
+ const odd = join(b.root, "o'example home");
+ mkdirSync(odd);
+ await withEnv({ HOME: b.home, GBRAIN_HOME: odd, CLAUDE_CONFIG_DIR: undefined }, async () => {
+ const launcher = hookLauncherPath();
+ expect(launcher).toContain("o'example home");
+ for (const command of [
+ buildClaudeHookCommand(b.gbrain, 'Stop', { GBRAIN_HOOK_LANE: 'turn-rule' }, launcher),
+ codexSetupHookGroup(b.gbrain, 'UserPromptSubmit', {}, 'setup', launcher).hooks[0]!.command,
+ codexSetupHookGroup(b.gbrain, 'SessionEnd', {}, 'setup', launcher).hooks[0]!.command,
+ ]) expect(hookLauncherInCommand(command)).toBe(launcher);
+ const settings = join(b.home, '.claude', 'settings.json');
+ expect(syncTurnRuleHook({ harness: 'claude-code', gbrainBin: b.gbrain, paths: { claudeSettings: settings }, rerun: 'x' }).action).toBe('write');
+ expect(hookLauncherProblem('claude-code')).toBeNull();
+ const [entry] = readJson(settings).hooks.UserPromptSubmit.flatMap((g: { hooks: unknown[] }) => g.hooks);
+ expect(runHook(b, entry.command).exitCode).toBe(0);
+ expect(existsSync(b.marker)).toBe(false);
+ });
+ });
+
test('ensureHookLauncher rewrites a changed launcher and keeps its directory private', () => {
const b = box();
ensureHookLauncher(b.launcher);
@@ -142,6 +163,17 @@ describe('the launcher', () => {
expect(hookLauncherState(b.launcher).state).toBe('current');
expect(readdirSync(dirname(b.launcher))).toEqual([HOOK_LAUNCHER_NAME]);
});
+
+ test('a rewrite never leaves a temp file in the launcher directory, so a hook running meanwhile still starts', () => {
+ const b = box();
+ ensureHookLauncher(b.launcher);
+ for (let i = 0; i < 20; i++) {
+ writeFileSync(b.launcher, '#!/bin/sh\nexec "$@"\n');
+ ensureHookLauncher(b.launcher);
+ expect(readdirSync(dirname(b.launcher))).toEqual([HOOK_LAUNCHER_NAME]);
+ }
+ expect(readdirSync(dirname(dirname(b.launcher))).filter((n) => n.includes('.tmp-'))).toEqual([]);
+ });
});
describe('hooks written before the launcher: doctor flags them, post-upgrade moves them', () => {
diff --git a/test/setup.test.ts b/test/setup.test.ts
index b8d26c45a7..f1ea12d111 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -867,7 +867,7 @@ describe('hooks written before the hook launcher (#8424): the next setup and pos
const viaLauncher = (b: Box, commands: string[]) => commands.length > 0 && commands.every((c) => c.includes(`${launcher(b)} ${b.bin} hook`));
/** Rewrite setup's Claude Code entries and receipt hashes to what setup wrote before the launcher. */
- function downgradeClaude(b: Box): void {
+ function downgradeClaude(b: Box, stripMarker = false): void {
const s = readJson(settings(b));
const r = readJson(receipt(b));
for (const [event, groups] of Object.entries(s.hooks as Record<string, any[]>)) {
@@ -875,6 +875,7 @@ describe('hooks written before the hook launcher (#8424): the next setup and pos
if (e._gbrain !== 'setup-v1') continue;
e.command = e.command.replace(` ${launcher(b)} `, ' ');
r.hooks.owned[event] = hookEntryHash(e);
+ if (stripMarker) delete e._gbrain;
}
}
writeFileSync(settings(b), JSON.stringify(s, null, 2));
@@ -925,6 +926,21 @@ describe('hooks written before the hook launcher (#8424): the next setup and pos
expect((await setup(b, ['claude-code', '--json'])).doc.steps.map((s: any) => s.action)).toEqual(['keep', 'keep', 'keep']);
});
+ test('claude-code: entries Claude Code rewrote without the _gbrain marker are still found by receipt hash', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);
+ downgradeClaude(b, true);
+ const commands = () => ['SessionStart', 'UserPromptSubmit'].flatMap((e) => entries(b, e).map((x) => x.command as string));
+ expect(entries(b, 'UserPromptSubmit')[0]._gbrain).toBeUndefined();
+ await withEnv(env(b), async () => {
+ expect(hookLauncherProblem('claude-code')).toMatchObject({ lane: 'setup', reason: 'session_cwd' });
+ await refreshHookLaunchers(() => {});
+ expect(hookLauncherProblem('claude-code')).toBeNull();
+ });
+ expect(viaLauncher(b, commands())).toBe(true);
+ expect(['SessionStart', 'UserPromptSubmit'].map((e) => entries(b, e).length)).toEqual([1, 1]);
+ });
+
test('codex: post-upgrade rewrites them with matching trust, and a later setup keeps everything', async () => {
const b = box();
expect((await setup(b, ['codex', '--json'])).exitCode).toBe(0);