Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(security): hooks start gbrain from a trusted launcher directory (#8424)
garrytanc2b2182b66ca
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5785ddf02c..5c661dab04 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,14 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Security: gbrain's hooks no longer let the session directory's bunfig.toml or .env run (#8424).** A script-mode install (`bun install -g`, `bun link`) runs gbrain as a Bun script, and Bun applies the working directory's `bunfig.toml` (a top-level `preload` runs before any gbrain code) and loads its `.env` files first. Claude Code and Codex run hooks in the session's directory, so with the hooks `gbrain setup claude-code|codex` writes, or the per-turn rule hook from `--instructions-only`, `gbrain connect --install` and `gbrain bootstrap harness`, opening a session in a cloned repository ran that repository's code as you on every prompt, with nothing to approve. Each of those hooks now starts gbrain through `<gbrain config dir>/hook-launcher/gbrain-hook`, a small sh script that records the session directory in `GBRAIN_HOOK_CWD`, changes into its own directory and starts gbrain there. Its directory holds only the launcher, and it refuses to start gbrain if anything else appears there.++- `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).+## [0.60.545.0] - 2026-11-02**The hosted gbrain.io install now tells the agent the brain is there.**diff --git a/SECURITY.md b/SECURITY.mdindex ae0ddb28b7..4eaf3fe0cc 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -82,6 +82,22 @@ undo it. Only the compiled binary ignores a cwd `bunfig.toml`; run script-modegbrain from directories you control, or use the release binary in untrustedcheckouts.+Hooks are the exception gbrain closes itself, because a harness runs them in+the session's directory with nothing for you to approve. Every hook that+`gbrain setup claude-code|codex` writes (the read-context and capture hooks,+and the per-turn rule hook that `--instructions-only`, `gbrain connect+--install` and `gbrain bootstrap harness` add) starts gbrain through+`<gbrain config dir>/hook-launcher/gbrain-hook`. That launcher is a small+POSIX `sh` script: it records the session directory in `GBRAIN_HOOK_CWD`,+changes into its own directory and starts gbrain there, so Bun never reads the+session directory's `bunfig.toml` or `.env`. Its directory holds only the+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.+**The trust boundary.** Security-relevant variables are honored from yourshell environment, from a service `EnvironmentFile`, and from`~/.gbrain/.env` (the operator-owned secrets file). They are **never** honoreddiff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 83a7e0d67e..e61c78fb63 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -30,7 +30,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/setup.ts` + `src/cli/commands/setup.ts` — `gbrain setup <harness>` (D8), pre-connect and engine-free (`thinClient: 'none'`, `json: 'document'`): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (`loadConfig`; none → a `gbrain init --pglite --no-embedding --json` child, `--providers` drops `--no-embedding`; setup prints `Brain ready at <path>` and never init's standalone quickstart or `[AGENT]` banners; on the brain it just created it runs the setup migrations init left pending (`finishFreshSetupMigrations`, `src/commands/setup-migrations.ts`: one `apply-migrations --yes --no-autopilot-install --json` child built by `setupMigrationsArgv` in `migrations/fresh-install.ts`, 60 s bound, offline; v0.11.0 is held back when its host phase would edit an existing `~/.claude/AGENTS.md`, `~/.openclaw/AGENTS.md` or OpenClaw cron manifest (`hostRewriteTargets`)) and replaces init's `[init] Migrations:` line with `[setup] Migrations: …` (a failure keeps init's hand-off plus the error code; an existing brain is not touched), and renders a `Memory:` line naming `remember` (#6606: world facts are pushed, private ones are recall-only, capture writes a page) and then `setupFirstRunNotices` once after `Next:` in human output, or under `notices` in `--json`), the source (`--source` > `GBRAIN_SOURCE` > unpinned), the launcher (`--gbrain-bin` > `resolveGbrainBin`), the surface (`--surface` > `GBRAIN_SURFACE` > the receipt's > `REGISTRATION_SURFACE`) and the registration owner, prints them, then refuses before any write with `setup_hosted_connection` (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or `setup_owner_conflict` (`live_serve` from `peekLock` unless the live stdio serve is this registration's own, `unowned_entry`, `other_install` by receipt `gbrain_home`, `harness_lane` for a bootstrap harness receipt or another gbrain marker on a wanted event). Consent is three recorded decisions (`resolveConsent`): wiring scope (`--scope`, `--no-hooks`, `GBRAIN_HOOKS=0`), capture (`--capture`/`--no-capture`; a file-config `memory.auto_writeback: off` wins) and providers; read-context events come from the capability row, capture events only when accepted. Verify reuses `smokeStdioRegistration` from `doctor/checks/harness-wiring.ts`; states are `configured` → `connection-verified` → `native-pending` (`native-verified` is never claimed). `gbrain setup codex` (`runCodexSetup`/`runCodexRemove`, writer in `src/core/setup/codex.ts`) shares the target, consent, refusal and verify steps: user scope only (`--scope project` exits 2), the codex plugin (`codexPluginProvidesName`) skips the MCP table, `harness_lane` also covers a bootstrap harness receipt targeting codex or a bootstrap-lane group on a wanted event, the dry run adds a `trust` step, and the final state is `native-verified` when the codex row's push is verified and the receipt owns the trusted UserPromptSubmit hook. Unsupported harness ids (`openclaw`, `hermes`, unknown) refuse with `setup_harness_unsupported` naming the row's guide (exit 2). `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks` is the crash-injection seam. Pinned by `test/setup.test.ts`.- `src/core/setup/brain-first.ts` + `src/core/managed-block.ts` — the brain-first instruction block every harness install writes by default (`<!-- gbrain:brain-first:begin/end -->`, `BRAIN_FIRST_VERSION`). `brainFirstTarget` names each harness's own instruction file (Claude Code `~/.claude/CLAUDE.md` or `./CLAUDE.local.md`, Codex `AGENTS.md` or an existing `AGENTS.override.md`, opencode global `AGENTS.md`, OpenClaw `<workspace>/AGENTS.md` from JSON5 `agents.defaults.workspace` (several agents need `--workspace`), Hermes `SOUL.md` after the identity text, Cursor `.cursor/rules/gbrain-brain-first.mdc`); other clients get the block printed to paste. `syncBrainFirst` splices only between the markers (idempotent, upgrades in place, preserves a damaged block and reports it), and the decision (`--no-instructions` / `GBRAIN_AGENT_INSTRUCTIONS=0`, `--instructions`, prior) is remembered in `<configDir>/agent-instructions.json` with the writer, so `--remove` on setup, `connect --install` and `bootstrap harness` (lane in `bootstrap/harness-brain-first.ts`) strips only its own blocks. Text varies by access: MCP search surface, verbs surface, or the thin-client CLI launcher (`GBRAIN-INSTRUCTIONS.md` starts with it). doctor `harness_wiring` reads the ledger plus each registered or plugin-served harness's default file and warns on a missing, stale or damaged block with a fix that rewrites only the block (`instructionBlockViews`, `withInstructionBlocks`); `gbrain post-upgrade` prints the same command (`brain-first-upgrade-notice.ts`, `instructionBlockUpgradeHints`). The Claude Code and Codex plugin manifests declare setup's UserPromptSubmit hook with `GBRAIN_HOOK_LANE=plugin`; it yields when another gbrain lane wires the event (`bootstrap/plugin-lanes.ts` `pluginHookYields`; `test/plugin-turn-hook.test.ts`). `managed-block.ts` is the shared marker splice/probe/remove that `bootstrap/instructions-block.ts` also uses (`test/setup-brain-first.test.ts`).-- `src/core/setup/turn-hook.ts` + `src/core/setup/turn-hook-check.ts` — the per-turn rule hook for installs whose MCP came from a plain `mcp add` or another installer: a `turn-rule-v1` Claude Code UserPromptSubmit entry or a Codex `hooks.json` group plus its `config.toml` trust entry, running `GBRAIN_HOOK_LANE=turn-rule gbrain hook user-prompt` (rule only, no local context; it yields to setup, bootstrap and plugin lanes). Written by `setup <claude-code|codex> --instructions-only`, `connect --install`, the hosted `harness connect --install` and `bootstrap harness` (not in registrar mode); with no absolute binary the outcome is `print` with the one-line next step. `inspectTurnHook` (files only) feeds doctor `harness_wiring` (`turnHookViews`, `withTurnHooks`: untrusted, or missing beside a ledger block, warns with code `turn_hook_not_loaded`); `verifyTurnHook` runs the hook (Claude Code, Codex), `openclaw plugins inspect gbrain-turn-rule --runtime --json` or `hermes hooks doctor`, and every install path exits non-zero with `turn_hook_not_loaded` when it fails (`docs/guides/repair.md#turn-hook-not-loaded`). OpenClaw and Hermes rules name the gbrain tools and the `tool_search` route (`renderBrainFirstTurnRule(access, harness)`; `test/brain-first-turn-rule.test.ts`, `test/setup-brain-first.test.ts`).+- `src/core/setup/turn-hook.ts` + `src/core/setup/turn-hook-check.ts` — the per-turn rule hook for installs whose MCP came from a plain `mcp add` or another installer: a `turn-rule-v1` Claude Code UserPromptSubmit entry or a Codex `hooks.json` group plus its `config.toml` trust entry, running `GBRAIN_HOOK_LANE=turn-rule <hook launcher> gbrain hook user-prompt` (rule only, no local context; it yields to setup, bootstrap and plugin lanes). Written by `setup <claude-code|codex> --instructions-only`, `connect --install`, the hosted `harness connect --install` and `bootstrap harness` (not in registrar mode); with no absolute binary the outcome is `print` with the one-line next step. `inspectTurnHook` (files only) feeds doctor `harness_wiring` (`turnHookViews`, `withTurnHooks`: untrusted, or missing beside a ledger block, warns with code `turn_hook_not_loaded`); `verifyTurnHook` runs the hook (Claude Code, Codex), `openclaw plugins inspect gbrain-turn-rule --runtime --json` or `hermes hooks doctor`, and every install path exits non-zero with `turn_hook_not_loaded` when it fails (`docs/guides/repair.md#turn-hook-not-loaded`). OpenClaw and Hermes rules name the gbrain tools and the `tool_search` route (`renderBrainFirstTurnRule(access, harness)`; `test/brain-first-turn-rule.test.ts`, `test/setup-brain-first.test.ts`).+- `src/core/setup/hook-launcher.ts` + `src/core/setup/hook-launcher-refresh.ts` — the trusted-directory hook launcher (#8424): `<config dir>/hook-launcher/gbrain-hook`, a POSIX sh script that records the session directory in `GBRAIN_HOOK_CWD`, changes into its own directory and execs gbrain there, so a script-mode install never lets the session directory's `bunfig.toml` preload or `.env` load; it refuses (exit 1, one stderr line) when its directory holds anything else. Every setup-lane and turn-rule hook command names it (`buildClaudeHookCommand(…, launcher)`, `codexSetupHookGroup(…, launcher)`, `buildCodexSessionEndCommand(bin, launcher)`); `ensureHookLauncher` writes it before any hook that names it, and `gbrain hook` reads the session directory through `hookSessionCwd()`. `hookLauncherProblem` (turn-hook-check.ts) feeds doctor `harness_wiring` (`withHookLaunchers`, code `hook_session_cwd`, reasons `session_cwd|missing|stale|foreign`); `refreshHookLaunchers` runs in `gbrain post-upgrade` and moves the turn-rule entries and each installed user-scope setup receipt's hooks onto the launcher through their own writers. Bootstrap and plugin hook lanes do not use it yet. Tests: `test/hook-launcher-bunfig.test.ts` (a hostile checkout's preload never runs from any shape), `test/setup.test.ts` (#8424 block).- `src/commands/skillify.ts` + `src/core/skillify/{generator,templates}.ts` — `gbrain skillify scaffold <name>` creates all stubs for a new skill: SKILL.md, script, tests, routing-eval.jsonl, resolver entry, filing-rules pointer. `gbrain skillify check <script>` runs the 10-step checklist (LLM evals, routing evals, check-resolvable gate, filing audit) against a candidate skill before it lands.- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — `install`/`uninstall` are not supported (they exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`; strict arguments through the `skillpack reference` row of `src/cli/strict-args.ts` (#5491): `--dry-run=true`, a typo or an unknown flag exits 2 before any write, the per-skill and `--all` grammars print separately, and `--all --apply-clean-hunks` refuses with the three-command update path; pinned by `test/skillpack-reference-strict-args.test.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` remain because `gbrain skillpack diff` uses `diffSkill` from there.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex e635feba87..7fcd001127 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2207,6 +2207,18 @@ More: [docs/guides/write-refusals.md#head-blocked](../../docs/guides/write-refus|---|---|---|---|---|---|---|| Held out required for bundled. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### hook_session_cwd++<a id="hook_session_cwd"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A hook gbrain setup or the turn-rule lane wrote starts gbrain in the session's directory, or the hook launcher it names would not run. | Script-mode gbrain is a Bun script, and Bun runs the working directory's bunfig.toml preload and loads its .env before gbrain starts; harnesses run hooks in the session directory, so a cloned repository could run code on every prompt. | Correct the request using the message above, then retry. Run: gbrain doctor --only harness_wiring --json | agent | `repeat the read that failed` | 1 | no |++Reasons: `session_cwd`, `missing`, `stale`, `foreign`.++More: [docs/guides/repair.md#hook-session-cwd](../../docs/guides/repair.md#hook-session-cwd)+### host_identity_mismatch<a id="host_identity_mismatch"></a>diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 1a3934a05b..5ce7f13a08 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -4341,6 +4341,33 @@ with the harness's own command:harness. opencode and Cursor have no per-turn hook gbrain can install; therule reaches them through their instruction file only.+### Hook starts gbrain in the session directory++<a id="hook-session-cwd"></a>++`hook_session_cwd`: a hook that `gbrain setup <claude-code|codex>` or the+turn-rule lane wrote starts gbrain in the session's working directory. With a+script-mode install (`bun install -g`, `bun link`) Bun reads that directory's+`bunfig.toml` (a top-level `preload` runs before any gbrain code) and its+`.env` files first, so opening a session in a cloned repository would run that+repository's code on every prompt. Current hooks start gbrain through+`<gbrain config dir>/hook-launcher/gbrain-hook`, which records the session+directory in `GBRAIN_HOOK_CWD` and runs gbrain from its own directory. The+`reason` says what doctor found:++- `session_cwd`: the hook was written before the launcher existed.+- `missing` or `stale`: the hook names the launcher, but it is gone, changed+ or not executable.+- `foreign`: the launcher's directory holds a file gbrain did not write. The+ launcher refuses to start gbrain there (the hook exits 1 with one stderr+ line) until you remove it.++Run `fix.argv` (`gbrain setup <harness>` for setup's hooks,+`gbrain setup <harness> --instructions-only` for the turn-rule hook);+`gbrain post-upgrade` moves every user-scope hook it can find. A project-scope+install is refreshed from its project directory. Check with+`gbrain doctor --only harness_wiring`.+## Connection noticesTwo notices tell an agent, on its own MCP connection, why something itdiff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex e8fd119322..6ed6e8c766 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -118,7 +118,10 @@ table with its `trusted_hash`, otherwise Codex lists it and silently skips it.- `[mcp_servers.<name>]` with `command`, `args` and `env` (`GBRAIN_HOME`,`GBRAIN_SOURCE` when set);- one hooks.json group per event, running- `env GBRAIN_HOOK_LANE=setup … <launcher> hook session-start|user-prompt --harness codex`+ `env GBRAIN_HOOK_LANE=setup … <hook launcher> <launcher> hook session-start|user-prompt --harness codex`+ (the hook launcher, `<gbrain config dir>/hook-launcher/gbrain-hook`, starts+ gbrain from its own directory so the session directory's `bunfig.toml` and+ `.env` never load; SECURITY.md)(15 s), plus the detached `hook session-end --harness codex` capture command(3 s) only after `--capture`;- one trust table per group.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 690b47c9d7..61d5580b50 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -34,7 +34,7 @@ src/commands/sources.ts 2100 ratchet +3 G7b-2: sources host-repo dispatch and hesrc/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edgessrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh-src/commands/hook.ts 1987 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts); +13 GBRA-188 per-turn brain-first rule: user-prompt emission and its HookIo seam (rule and ledger read in core/setup/brain-first.ts); +3 GBRA-188 plugin lane: GBRAIN_HOOK_LANE=plugin yields to another gbrain lane wiring the event (import, comment and guard; detection in bootstrap/plugin-lanes.ts otherLaneWiresHook); +5 GBRA-243 turn-rule lane: GBRAIN_HOOK_LANE=turn-rule yields to every other lane and answers rule-only (import, two guards and comments; logic in core/setup/turn-hook.ts), user-prompt passes cwd to the scope-aware rule; +34 #8064/#8016/#8028: the session-speaker banking decision at compact, stop and session-end (logic in context/session-speaker.ts), the harness-prompt skip and the lane-scoped parser_drift clear+src/commands/hook.ts 1988 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts); +13 GBRA-188 per-turn brain-first rule: user-prompt emission and its HookIo seam (rule and ledger read in core/setup/brain-first.ts); +3 GBRA-188 plugin lane: GBRAIN_HOOK_LANE=plugin yields to another gbrain lane wiring the event (import, comment and guard; detection in bootstrap/plugin-lanes.ts otherLaneWiresHook); +5 GBRA-243 turn-rule lane: GBRAIN_HOOK_LANE=turn-rule yields to every other lane and answers rule-only (import, two guards and comments; logic in core/setup/turn-hook.ts), user-prompt passes cwd to the scope-aware rule; +34 #8064/#8016/#8028: the session-speaker banking decision at compact, stop and session-end (logic in context/session-speaker.ts), the harness-prompt skip and the lane-scoped parser_drift clear; +1 #8424: hookSessionCwd import (the session directory the hook launcher records; logic in core/setup/hook-launcher.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeoutsrc/core/config.ts 2016 ratchet +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts)src/core/persistence/sync-run.ts 1695 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1601 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured+src/core/behavior-change-notice.ts 1603 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move)diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.tsindex 7fb00aa335..efd488b94b 100644--- a/src/commands/doctor/checks/harness-wiring.ts+++ b/src/commands/doctor/checks/harness-wiring.ts@@ -34,7 +34,7 @@ import { verifiedStatusMarkers } from '../../../core/serve-http-status-marker.tsimport { agentProcessMarker } from '../../../core/interaction.ts';import { resolveGbrainBin } from '../../../core/gbrain-bin.ts';import { enabledPluginLanes } from '../../../core/bootstrap/plugin-lanes.ts';-import { claudeConfigDir, opencodeProjectConfigPath } from '../../../core/bootstrap/host-specs.ts';+import { claudeConfigDir, claudeUserSettingsPath, opencodeProjectConfigPath } from '../../../core/bootstrap/host-specs.ts';import { readReceipt } from '../../../core/bootstrap/format.ts';import { resolveGbrainHome } from '../../../core/gbrain-home.ts';import type { Action } from '../../../core/agent-output.ts';@@ -42,7 +42,8 @@ import type { Check } from '../../doctor.ts';import { checkError, doctorVerify, infoCheck } from '../check-fix.ts';import type { DoctorContext, DoctorEntry } from '../context.ts';import { VERSION } from '../../../version.ts';-import { TURN_HOOK_NATIVE_INSPECT, inspectTurnHook, turnHookFix, type TurnHookState } from '../../../core/setup/turn-hook-check.ts';+import { TURN_HOOK_NATIVE_INSPECT, hookLauncherProblem, inspectTurnHook, turnHookFix, type HookLauncherProblem, type TurnHookState } from '../../../core/setup/turn-hook-check.ts';+import { localSetupRecords } from '../../../core/setup/local-receipts.ts';import { brainFirstTarget, inspectBrainFirst, isBrainFirstHarness, readBrainFirstLedger, renderBrainFirstBlock, type BrainFirstAccess } from '../../../core/setup/brain-first.ts';export const HARNESS_SMOKE_TIMEOUT_MS = 15_000;@@ -501,11 +502,45 @@ export function withTurnHooks(check: Check, views: InstructionBlockView[], hooksreturn { name: NAME, status: 'warn', message, details: { ...details, code: 'turn_hook_not_loaded', turn_hook_reason: bad.state }, fix };}-/** Registration read (full run) or registration read + smoke (`--only harness_wiring`), plus the brain-first block and its per-turn hook. */+/**+ * The first setup or turn-rule hook that would let a session directory's+ * bunfig.toml or .env load (#8424): Claude Code user scope, every project a+ * setup receipt or a CLAUDE.local.md block names, and Codex. Files only.+ */+export function hookLauncherProblems(views: InstructionBlockView[]): HookLauncherProblem | null {+ const projects = new Set([+ ...localSetupRecords().filter((r) => r.harness === 'claude-code' && r.scope === 'project' && r.projectDir).map((r) => r.projectDir!),+ ...views.filter((v) => v.harness === 'claude-code' && basename(v.path) === 'CLAUDE.local.md').map((v) => dirname(v.path)),+ ]);+ return hookLauncherProblem('claude-code') ?? [...projects].map((projectDir) => hookLauncherProblem('claude-code', { projectDir })).find((p) => p !== null) ?? hookLauncherProblem('codex');+}++/** The setup command that rewrites the lane's hooks through the launcher; a project install or a foreign file needs the user. */+export function hookLauncherFix(p: HookLauncherProblem): Action {+ const project = p.harness === 'claude-code' && p.source !== claudeUserSettingsPath() ? dirname(dirname(p.source)) : null;+ const record = p.lane === 'setup' ? localSetupRecords().find((r) => r.harness === p.harness && r.status === 'installed' && (project ? r.projectDir === project : r.scope !== 'project')) : undefined;+ const argv = ['gbrain', 'setup', p.harness, ...(p.lane === 'turn-rule' ? ['--instructions-only'] : []), ...(record && record.name !== 'gbrain' ? ['--name', record.name] : []), ...(project ? ['--scope', 'project'] : [])];+ const why = "Rewrites gbrain's hooks to start gbrain from its own launcher directory, so a repository's bunfig.toml or .env never runs when a session opens there. `gbrain post-upgrade` refreshes the user-scope hooks too.";+ const verify = doctorVerify(NAME);+ if (p.reason === 'foreign') return { consent: [], actor: 'user', requires_exclusive: false, verify, why, user_message: `${p.detail}. Remove that file (gbrain did not write it), then run: ${argv.join(' ')}` };+ if (project) return { consent: [], actor: 'user', requires_exclusive: false, verify, why, user_message: `gbrain's hooks for ${project} start gbrain in the session's directory. From ${project}, run: ${argv.join(' ')}` };+ return { argv, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify, why };+}++/** A hook that lets the session directory's bunfig.toml or .env load turns an ok or warn check into a warn (code hook_session_cwd). */+export function withHookLaunchers(check: Check, problem: HookLauncherProblem | null): Check {+ if (!problem) return check;+ const message = `${check.message} Hook launcher: ${problem.detail}.`;+ const details = { ...(check.details ?? {}), hook_launcher: problem };+ if (check.status === 'fail') return { ...check, message, details };+ return { name: NAME, status: 'warn', message, details: { ...details, code: 'hook_session_cwd', hook_launcher_reason: problem.reason }, fix: hookLauncherFix(problem) };+}++/** Registration read (full run) or registration read + smoke (`--only harness_wiring`), plus the brain-first block, its per-turn hook and the hook launcher. */export async function harnessWiringCheck(opts: { smoke: boolean }): Promise<Check> {const regs = readHarnessRegistrations();const views = instructionBlockViews(regs);- return withSurfaceNote(withTurnHooks(withInstructionBlocks(await registrationCheck(opts, regs), views), views, turnHookViews(views)), regs);+ return withHookLaunchers(withSurfaceNote(withTurnHooks(withInstructionBlocks(await registrationCheck(opts, regs), views), views, turnHookViews(views)), regs), hookLauncherProblems(views));}/**diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex c6f543128f..39721e9943 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -124,6 +124,7 @@ import { HOOK_SUBCOMMANDS as HOOK_EVENTS, ROUTERS, subcommandHelpRequested } froimport { 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';// ── Tunables ────────────────────────────────────────────────────────────────@@ -200,7 +201,7 @@ export interface HookIo {stdin?: string;/** Injected stdout sink; default process.stdout.write. */write?: (s: string) => void;- /** Workspace dir override; default stdin JSON `cwd` → process.cwd(). */+ /** Workspace dir override; default stdin JSON `cwd` → the session directory (GBRAIN_HOOK_CWD from the hook launcher, else process.cwd()). */cwd?: string;/** TEST SEAM: transcript confinement root (default ~/.claude/projects). */transcriptRoot?: string;@@ -329,7 +330,7 @@ export async function runHook(args: string[], io: HookIo = {}): Promise<number>'session-end': 'SessionEnd',compact: 'PreCompact',}[event];- const dotClaude = join(io.cwd ?? process.cwd(), '.claude');+ const dotClaude = join(io.cwd ?? hookSessionCwd(), '.claude');for (const file of ['settings.local.json', 'settings.json']) {const p = join(dotClaude, file);if (!existsSync(p)) continue;@@ -348,9 +349,9 @@ export async function runHook(args: string[], io: HookIo = {}): Promise<number>}}// Plugin lane (the Claude Code and Codex plugin manifests): yields to any other gbrain lane wiring this event.- if (process.env.GBRAIN_HOOK_LANE === 'plugin' && pluginHookYields(io.harness ?? 'claude-code', event, io.cwd ?? process.cwd())) return 0;+ if (process.env.GBRAIN_HOOK_LANE === 'plugin' && pluginHookYields(io.harness ?? 'claude-code', event, io.cwd ?? hookSessionCwd())) return 0;// Turn-rule lane (src/core/setup/turn-hook.ts): rule only, and only when no other gbrain lane wires this event.- if (process.env.GBRAIN_HOOK_LANE === TURN_RULE_LANE && event === 'user-prompt' && turnRuleHookYields(io.harness ?? 'claude-code', io.cwd ?? process.cwd())) return 0;+ if (process.env.GBRAIN_HOOK_LANE === TURN_RULE_LANE && event === 'user-prompt' && turnRuleHookYields(io.harness ?? 'claude-code', io.cwd ?? hookSessionCwd())) return 0;switch (event) {case 'session-start':@@ -519,7 +520,7 @@ async function hookSessionStart(io: HookIo): Promise<number> {try {const j = await readStdinJson(io, 250);- const ws = io.cwd ?? (typeof j?.cwd === 'string' ? (j.cwd as string) : process.cwd());+ const ws = io.cwd ?? (typeof j?.cwd === 'string' ? (j.cwd as string) : hookSessionCwd());const awaitServe = sessionStartAwaitsServe(j?.source, io.harness ?? 'claude-code', ws);const deadlineMs = awaitServe ? SESSION_START_SERVE_WAIT_DEADLINE_MS : SESSION_START_DEADLINE_MS;let serveNotReady = false;@@ -1136,7 +1137,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {// Push failure wins the single banner slot; the monthly backup notice// rides the same rail (systemMessage + additionalContext) when no push// failure is pending. Both are cache/file readers, budgeted by the race.- turnRule = io.turnRule !== undefined ? io.turnRule : brainFirstTurnRule(io.harness ?? 'claude-code', io.cwd ?? process.cwd());+ turnRule = io.turnRule !== undefined ? io.turnRule : brainFirstTurnRule(io.harness ?? 'claude-code', io.cwd ?? hookSessionCwd());// The turn-rule lane's connection may reach another brain, so it never reads this machine's context or banners.if (process.env.GBRAIN_HOOK_LANE === TURN_RULE_LANE) return { outcome: 'ok', reason: 'rule_only' };banner = io.disablePushBanner ? null : (pendingPushFailureBanner() ?? pendingBackupBanner());@@ -1205,7 +1206,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {// keying material at all (no config, thin-client remote) — ENGINE-FREE// means no direct-engine fallback here; pull-mode covers it.const sessionId = typeof j.session_id === 'string' ? j.session_id : undefined;- const sourceId = await contextSource(io, cfg, sessionId, io.cwd ?? (typeof j.cwd === 'string' ? j.cwd : process.cwd()));+ const sourceId = await contextSource(io, cfg, sessionId, io.cwd ?? (typeof j.cwd === 'string' ? j.cwd : hookSessionCwd()));const socketPath = await hookResolveSocketForConfig(cfg, sourceId);if (!socketPath) {return { outcome: 'degraded', reason: 'no_pglite_path' };@@ -1401,7 +1402,7 @@ async function hookCompact(io: HookIo): Promise<number> {// any IPC. Written for EVERY engine config (the sweep backstop harvests it// when serve/IPC is unavailable). Per-step deadline degrades — a scan that// can't finish skips the segment ENTIRELY (never write unscanned content).- const { dir, stamp, source } = await sessionCorpus(io, cfg, sessionId, io.cwd ?? (typeof j.cwd === 'string' ? j.cwd : process.cwd()));+ const { dir, stamp, source } = await sessionCorpus(io, cfg, sessionId, io.cwd ?? (typeof j.cwd === 'string' ? j.cwd : hookSessionCwd()));const speaker = hookSpeaker(io, dir, sessionId);if (speaker.bank !== true) { if (speaker.bank === 'failed') outcome = 'degraded'; reason = speaker.reason; return; }seatReasons = [...speaker.reasons, ...captureSeat(io, dir, sessionId, transcriptPath)];@@ -1516,7 +1517,7 @@ async function hookStop(io: HookIo): Promise<number> {// #5820: the SessionEnd guard's fingerprint (#5413) — a turn from// gbrain's own claude-cli subprocess is never banked, or extracting it// spawns another claude-cli call that banks again.- const ws = io.cwd ?? (typeof j?.cwd === 'string' ? j.cwd : process.cwd());+ const ws = io.cwd ?? (typeof j?.cwd === 'string' ? j.cwd : hookSessionCwd());if (isClaudeCliSelfTranscriptPath(conf.path) || isClaudeCliSelfTranscriptPath(ws)) return 'self_capture';const findLastUser = (parsed: ReturnType<typeof parseTranscript>): WindowTurn | undefined => {const index = parsed.genuineUserTurnIndexes.at(-1);@@ -1612,7 +1613,7 @@ async function hookStop(io: HookIo): Promise<number> {// buffer append above and the heartbeat below are never at risk.let pushReason: string | undefined;try {- const ws = io.cwd ?? (typeof j?.cwd === 'string' ? (j.cwd as string) : process.cwd());+ const ws = io.cwd ?? (typeof j?.cwd === 'string' ? (j.cwd as string) : hookSessionCwd());const raced = await withDeadline(STOP_PUSH_DEADLINE_MS, stopPushIfDue(ws, io));pushReason = raced === DEADLINE ? 'push_unavailable' : raced;} catch {@@ -1725,7 +1726,7 @@ async function hookSessionEnd(io: HookIo): Promise<number> {try {const j = await readStdinJson(io, 500);sessionId = sanitizeSessionId(j?.session_id);- ws = io.cwd ?? (typeof j?.cwd === 'string' ? (j.cwd as string) : process.cwd());+ ws = io.cwd ?? (typeof j?.cwd === 'string' ? (j.cwd as string) : hookSessionCwd());const cfg = loadConfig();// ONE gate for the whole Memorable integration (memorableGateAllowed —// shared with the openclaw lane and doctor). Answered BEFORE the parse so@@ -1805,7 +1806,7 @@ async function hookSessionEnd(io: HookIo): Promise<number> {// Whole-file reads only: a bounded tail of a long agentic run can// legitimately hold assistant turns alone.if (parsed.genuineUserTurnIndexes.length === 0 && bytesN >= conf.size) degrade('no_user_turns');- const { root, dir, stamp, source } = await sessionCorpus(io, cfg, sessionId, ws ?? process.cwd());+ const { root, dir, stamp, source } = await sessionCorpus(io, cfg, sessionId, ws ?? hookSessionCwd());const speaker = hookSpeaker(io, dir, sessionId);if (speaker.bank !== true) {segmentMode = speaker.reason;@@ -1883,7 +1884,7 @@ async function hookSessionEnd(io: HookIo): Promise<number> {corpus_path: corpusFile,content_hash: segmentHash(text),turn_count: turnsN,- workspace_root: ws ?? process.cwd(),+ workspace_root: ws ?? hookSessionCwd(),tool_calls_json: toolCallsJson,secret_scan_ok: true, // scanner ran — the unscanned case took the branch above}, { trimRelayFile: true }); // both capture lanes trim memorable-relay.jsonl (converging newest-keeping trims)diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex c512a2d86a..17ed30ad58 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -26,7 +26,7 @@ import { realpathSync } from 'node:fs';import { dirname, join } from 'node:path';import { removeHermesTurnHook, syncHermesTurnHook } from '../core/setup/hermes-turn-hook.ts';import { removeOpenclawTurnPlugin, syncOpenclawTurnPlugin } from '../core/setup/openclaw-turn-plugin.ts';-import { isTurnRuleHarness, removeTurnRuleHook, syncTurnRuleHook, type TurnHookOutcome, type TurnRuleHarness } from '../core/setup/turn-hook.ts';+import { hasTurnRuleHook, isTurnRuleHarness, removeTurnRuleHook, syncTurnRuleHook, type TurnHookOutcome, type TurnRuleHarness } from '../core/setup/turn-hook.ts';import { inspectTurnHook, TURN_HOOK_NATIVE_INSPECT, turnHookFix, verifyTurnHook, type TurnHookVerdict } from '../core/setup/turn-hook-check.ts';import { opError, OperationError } from '../core/ops/contract.ts';import { cliRenderContext, renderCliError, renderNotice, type Action, type Notice } from '../core/agent-output.ts';@@ -789,7 +789,8 @@ function turnRuleHookFor(harness: TurnRuleHarness, off: boolean, flags: SetupFlaif (off || flags.noHooks) return removeTurnRuleHook({ harness, paths, dryRun: flags.dryRun });if (process.env.GBRAIN_HOOKS === '0') return { harness, action: 'skip', path: '', detail: 'GBRAIN_HOOKS=0 is set: no per-turn hook installed' };const carried = inspectTurnHook(harness, { projectDir });- if (carried.state !== 'missing' && carried.via !== 'turn-rule') return { harness, action: 'skip', path: '', detail: `per-turn rule already carried: ${carried.detail}` };+ // An entry of this lane beside another carrier still runs gbrain on every turn (it yields after starting), so it is refreshed, never left on an old launcher.+ if (carried.state !== 'missing' && carried.via !== 'turn-rule' && !hasTurnRuleHook(harness, paths)) return { harness, action: 'skip', path: '', detail: `per-turn rule already carried: ${carried.detail}` };return syncTurnRuleHook({ harness, gbrainBin: flags.gbrainBin ?? resolveGbrainBin(), gbrainHome: process.env.GBRAIN_HOME?.trim() || undefined, paths, dryRun: flags.dryRun, rerun });}diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 62e0d0b316..145ab35d22 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -934,6 +934,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {}(await import('../core/setup/brain-first-upgrade-notice.ts')).printBrainFirstUpgradeNotice(); // GBRA-188: the command that writes a missing brain-first block+ await (await import('../core/setup/hook-launcher-refresh.ts')).refreshHookLaunchers(); // #8424: hooks that start gbrain in the session's directory move onto the launcher(await import('../core/post-upgrade-notice.ts')).writePostUpgradeCliNotice(); // F7: safety notice ([AGENT] block for agents)// Mechanical: run every outstanding migration. Idempotent; exits 0 quickly// when nothing is pending. Stays inside the same process so a long Phase Fdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex b8057e8a82..7bb688e15f 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1403,6 +1403,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.539.0', id: 'remote_quotes_followups_8384', text: 'Agents connected over MCP now get a timeline entry\'s free-text source quoted with its summary and detail (get_timeline, the chronicle reads, volunteer_chronicle), and ontology values (volunteer_chronicle, ontology_get, ontology_conflicts) quoted by their fact\'s trust tier; add_timeline_entry and ontology_propose store text copied out of those reads without the fence. A remote put_page of a whole-markdown read keeps a code block the agent added inside, in place of or after the read, and keeps the frontmatter when blank lines were added before the marker. A remote get_page or fetch of a page quoted only because its origin is unverified carries a quoted_unverified_origin notice naming gbrain trust claim-sources and gbrain trust backfill, once per session. Local reads are unchanged.' },// #8384 (GBRA-269) quote fence follow-ups 3. since stamped at the merge slot.{ since: '0.60.541.0', id: 'remote_quotes_followups_8384b', text: 'Agents connected over MCP now get a quoted page\'s title quoted on search, query, assemble_evidence and recall rows, its tags quoted on get_page, fetch and get_tags (add_tag and remove_tag take a copied tag without the fence), and a chronicle row\'s kind quoted by its event page\'s tier; a context_pack card below "your notes" carries its title under the card\'s trust label. A remote put_page of a whole-markdown read saved with CRLF line endings stores the page, not its fence, and a fenced value pasted into frontmatter leaves the other keys as sent. Facts from a quarantined page, or awaiting re-derivation after a purge, no longer appear in entity-fact reads, local ones included: recall, search and query entity facts, find_trajectory, the entity card\'s fact count and consolidate; standing-question evidence also skips such facts, takes and timeline entries. Other local reads are unchanged.' },+ // #8424 (GBRA-277) hook launcher. since stamped at the merge slot.+ { since: '0.60.545.0', id: 'hook_launcher_8424', text: 'The hooks `gbrain setup claude-code|codex` writes, and the per-turn rule hook from `--instructions-only`, `gbrain connect --install` and `gbrain bootstrap harness`, now start gbrain through `<gbrain config dir>/hook-launcher/gbrain-hook`, so a session opened in a cloned repository never runs that repository\'s bunfig.toml preload or loads its .env. `gbrain post-upgrade` moves existing hooks onto it, and doctor `harness_wiring` warns with `hook_session_cwd` on any that still start gbrain in the session directory.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/bootstrap/codex-hooks.ts b/src/core/bootstrap/codex-hooks.tsindex f4f4127505..afcc832ad9 100644--- a/src/core/bootstrap/codex-hooks.ts+++ b/src/core/bootstrap/codex-hooks.ts@@ -113,14 +113,19 @@ function shellQuote(arg: string): string {* invocation and only /bin/sh ever parses the POSIX script. The outer sh's* $0 is the gbrain binary (no nested quoting of the path); the grandchild* inherits GBRAIN_BIN/GBRAIN_PAYLOAD through the env-prefix assignments.+ * With `launcher` (src/core/setup/hook-launcher.ts) the outer $0 is the+ * launcher and $1 the binary, so the grandchild starts gbrain from the+ * launcher's directory instead of the session's.*/-export function buildCodexSessionEndCommand(gbrainBin: string): string {- const script =- '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 &`;+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_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// identically in POSIX shells AND fish (escaped-quote outside quotes).- return `sh -c '${script.replace(/'/g, "'\\''")}' ${shellQuote(gbrainBin)}`;+ return `sh -c '${script.replace(/'/g, "'\\''")}' ${[...(launcher ? [launcher] : []), gbrainBin].map(shellQuote).join(' ')}`;}/** Compact JSON with recursively-sorted keys — codex's canonical form. */@@ -372,13 +377,13 @@ const SETUP_EVENT_SPECS: Record<CodexSetupEvent, { stateName: string; timeout: nexport interface CodexHookGroup { hooks: Array<{ type: 'command'; command: string; timeout: number }> }-/** Setup's group for one event (or the turn-rule lane's, src/core/setup/turn-hook.ts). `env` is POSIX `env` (any $SHELL parses it); the values pin this install. */-export function codexSetupHookGroup(gbrainBin: string, event: CodexSetupEvent, env: { GBRAIN_HOME?: string; GBRAIN_SOURCE?: string }, lane = 'setup'): CodexHookGroup {+/** Setup's group for one event (or the turn-rule lane's, src/core/setup/turn-hook.ts). `env` is POSIX `env` (any $SHELL parses it); the values pin this install. `launcher`: the trusted-directory hook launcher gbrain starts through (src/core/setup/hook-launcher.ts). */+export function codexSetupHookGroup(gbrainBin: string, event: CodexSetupEvent, env: { GBRAIN_HOME?: string; GBRAIN_SOURCE?: string }, lane = 'setup', launcher?: string): CodexHookGroup {const assignments = [`GBRAIN_HOOK_LANE=${lane}`, ...(env.GBRAIN_HOME ? [`GBRAIN_HOME=${env.GBRAIN_HOME}`] : []), ...(env.GBRAIN_SOURCE ? [`GBRAIN_SOURCE=${env.GBRAIN_SOURCE}`] : [])];const spec = SETUP_EVENT_SPECS[event];const command = event === 'SessionEnd'- ? ['env', ...assignments].map(shellQuote).join(' ') + ' ' + buildCodexSessionEndCommand(gbrainBin)- : ['env', ...assignments, gbrainBin, 'hook', spec.subcommand, '--harness', 'codex'].map(shellQuote).join(' ');+ ? ['env', ...assignments].map(shellQuote).join(' ') + ' ' + buildCodexSessionEndCommand(gbrainBin, launcher)+ : ['env', ...assignments, ...(launcher ? [launcher] : []), gbrainBin, 'hook', spec.subcommand, '--harness', 'codex'].map(shellQuote).join(' ');return { hooks: [{ type: 'command', command, timeout: spec.timeout }] };}diff --git a/src/core/bootstrap/hooks.ts b/src/core/bootstrap/hooks.tsindex be3affdb37..ff0f7600bc 100644--- a/src/core/bootstrap/hooks.ts+++ b/src/core/bootstrap/hooks.ts@@ -75,6 +75,8 @@ export interface ClaudeHookEnv {export interface WriteClaudeHooksOpts {/** Absolute path to the gbrain binary (GUI hosts inherit no PATH) [CX-P1.4]. */gbrainBin: string;+ /** Absolute trusted-directory launcher each command starts gbrain through (src/core/setup/hook-launcher.ts). */+ hookLauncher?: string;env: ClaudeHookEnv;/** Per-event timeout override (SECONDS — the settings-file unit). */timeoutSecs?: Partial<Record<ClaudeHookEvent, number>>;@@ -218,33 +220,36 @@ function shellQuote(arg: string): string {return `'${arg.replace(/'/g, "'\\''")}'`;}-/** Render the hook command string: `env K=V… <bin> hook <subcommand>`. The- * harness lane recognizes its unmarked entries by parsing exactly this shape- * back (parseClaudeHookCommand), so the two change together. */+/** Render the hook command string: `env K=V… [<launcher>] <bin> hook <subcommand>`.+ * `launcher` is the trusted-directory hook launcher (src/core/setup/hook-launcher.ts)+ * the setup and turn-rule lanes start gbrain through. The harness lane+ * recognizes its unmarked entries by parsing exactly this shape back+ * (parseClaudeHookCommand), so the two change together. */export function buildClaudeHookCommand(gbrainBin: string,event: ClaudeHookEvent,env: ClaudeHookEnv,+ launcher?: string,): string {const assignments: string[] = [];if (env.GBRAIN_SOURCE !== undefined) assignments.push(`GBRAIN_SOURCE=${env.GBRAIN_SOURCE}`);if (env.GBRAIN_HOME) assignments.push(`GBRAIN_HOME=${env.GBRAIN_HOME}`);if (env.GBRAIN_HOOK_LANE) assignments.push(`GBRAIN_HOOK_LANE=${env.GBRAIN_HOOK_LANE}`);if (env.GBRAIN_SEAT) assignments.push(`GBRAIN_SEAT=${env.GBRAIN_SEAT}`);- const parts = ['env', ...assignments, gbrainBin, 'hook', CLAUDE_HOOK_SUBCOMMAND[event]];+ const parts = ['env', ...assignments, ...(launcher ? [launcher] : []), gbrainBin, 'hook', CLAUDE_HOOK_SUBCOMMAND[event]];return parts.map(shellQuote).join(' ');}const HOOK_ENV_KEYS: ReadonlySet<string> = new Set(['GBRAIN_SOURCE', 'GBRAIN_HOME', 'GBRAIN_HOOK_LANE', 'GBRAIN_SEAT']);/**- * The inverse of buildClaudeHookCommand: `env K=V… <abs bin> hook <sub>` with+ * The inverse of buildClaudeHookCommand: `env K=V… [<abs launcher>] <abs bin> hook <sub>` with* nothing before or after, words split the way shellQuote joins them, env keys* limited to the ones the builder writes (each at most once), and a final* check that re-rendering the parse yields the exact input. Null for anything* else (an appended pipe, an extra flag, hand quoting, a relative launcher).*/-export function parseClaudeHookCommand(command: string): { gbrainBin: string; subcommand: string; env: ClaudeHookEnv } | null {+export function parseClaudeHookCommand(command: string): { gbrainBin: string; subcommand: string; env: ClaudeHookEnv; launcher?: string } | null {const words: string[] = [];const word = /([A-Za-z0-9_.:/@=-]+|'(?:[^']|'\\'')*')(?: |$)/y;while (word.lastIndex < command.length) {@@ -262,11 +267,13 @@ export function parseClaudeHookCommand(command: string): { gbrainBin: string; suif (!HOOK_ENV_KEYS.has(key) || key in env) return null;env[key] = words[i]!.slice(eq + 1);}- const [gbrainBin, verb, subcommand] = words.slice(i) as [string, string, string];- if (words.length - i !== 3 || verb !== 'hook' || !isAbsolute(gbrainBin)) return null;+ const rest = words.slice(i);+ const launcher = rest.length === 4 ? rest.shift()! : undefined;+ const [gbrainBin, verb, subcommand] = rest as [string, string, string];+ if (rest.length !== 3 || verb !== 'hook' || !isAbsolute(gbrainBin) || (launcher !== undefined && !isAbsolute(launcher))) return null;const event = CLAUDE_HOOK_EVENTS.find((e) => CLAUDE_HOOK_SUBCOMMAND[e] === subcommand);- if (!event || buildClaudeHookCommand(gbrainBin, event, env) !== command) return null;- return { gbrainBin, subcommand, env };+ if (!event || buildClaudeHookCommand(gbrainBin, event, env, launcher) !== command) return null;+ return { gbrainBin, subcommand, env, ...(launcher ? { launcher } : {}) };}/**@@ -710,7 +717,7 @@ export function writeClaudeHooksAt(continue;}- const command = buildClaudeHookCommand(opts.gbrainBin, event, env);+ const command = buildClaudeHookCommand(opts.gbrainBin, event, env, opts.hookLauncher);const timeout = opts.timeoutSecs?.[event] ?? CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS[event];const entry: HookCommandEntry = {type: 'command',diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 567554ce0a..adaab9a9a7 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -131,6 +131,7 @@ export const ERROR_CATALOGUE = {setup_owner_conflict: { code: 'setup_owner_conflict', docs: 'docs/guides/repair.md#setup-owner-conflict' },setup_hosted_connection: { code: 'setup_hosted_connection', docs: 'docs/guides/repair.md#setup-hosted-connection' },turn_hook_not_loaded: { code: 'turn_hook_not_loaded', docs: 'docs/guides/repair.md#turn-hook-not-loaded' },+ hook_session_cwd: { code: 'hook_session_cwd', docs: 'docs/guides/repair.md#hook-session-cwd' },} as const satisfies Record<string, CatalogueEntry>;export type CatalogueName = keyof typeof ERROR_CATALOGUE;diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex d44964b187..48a34a24d0 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -667,6 +667,7 @@ export const CODES = {setup_harness_unsupported: { class: 'caller', summary: "gbrain setup does not wire this harness yet; its guide has the manual connection steps.", why: 'Only harnesses with a supported row in the setup capability table are wired automatically, so setup never guesses another host\'s config format.', docs: 'docs/guides/repair.md#setup-harness-unsupported', exit: 2, fix: { argv: ['gbrain', 'setup', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the harnesses setup wires and the guide for each.' } },setup_hosted_connection: { class: 'caller', summary: "This machine already reaches a hosted brain, so gbrain setup will not create a second, local brain.", why: 'A new local brain would split memory: sessions would read and write the empty local brain while useful memory stays on the hosted one.', docs: 'docs/guides/repair.md#setup-hosted-connection', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the harness registration reaches.' } },setup_owner_conflict: { class: 'caller', summary: "Another owner holds what gbrain setup would change: a live server owns this PGLite brain, or the harness configuration holds an entry setup did not write.", why: 'A PGLite brain has one writer, so a second server would fail on its lock; an entry setup did not record by hash is the user\'s or another install\'s and is never overwritten.', reasons: ['live_serve', 'unowned_entry', 'other_install', 'harness_lane'], docs: 'docs/guides/repair.md#setup-owner-conflict', fix: { argv: ['gbrain', 'setup', 'claude-code', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolved target and which owner blocks it, without writing anything.' } },+ hook_session_cwd: { class: 'caller', summary: "A hook gbrain setup or the turn-rule lane wrote starts gbrain in the session's directory, or the hook launcher it names would not run.", why: 'Script-mode gbrain is a Bun script, and Bun runs the working directory\'s bunfig.toml preload and loads its .env before gbrain starts; harnesses run hooks in the session directory, so a cloned repository could run code on every prompt.', reasons: ['session_cwd', 'missing', 'stale', 'foreign'], docs: 'docs/guides/repair.md#hook-session-cwd', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Names the hook and the setup command that rewrites it through the launcher.' } },turn_hook_not_loaded: { class: 'caller', summary: "The per-turn hook that puts \"check gbrain first\" next to every user turn is missing, untrusted, or does not load in the harness.", why: 'Agents use the brain when that rule reaches them on every turn; registering the MCP server or writing an instruction file alone leaves them answering without it.', reasons: ['missing', 'untrusted', 'hook_failed', 'no_rule', 'not_loaded'], docs: 'docs/guides/repair.md#turn-hook-not-loaded', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which harness has no working per-turn hook and the command that wires it.' } },shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },shared_skills_unsupported: { class: 'unavailable', summary: "The server does not expose the shared-skills protocol." },diff --git a/src/core/setup/claude-code.ts b/src/core/setup/claude-code.tsindex 6f36e549d6..4ad4f083c2 100644--- a/src/core/setup/claude-code.ts+++ b/src/core/setup/claude-code.ts@@ -38,6 +38,7 @@ import {} from '../bootstrap/host-specs.ts';import { stdioServeArgv } from '../mcp-registration.ts';import { isTurnRuleEntry } from './turn-hook.ts';+import { ensureHookLauncher, hookLauncherPath } from './hook-launcher.ts';import type { McpSurface } from '../../mcp/surface.ts';export type WiringScope = 'user' | 'project';@@ -184,7 +185,7 @@ export function desiredMcpEntry(plan: ClaudeSetupPlan): Record<string, unknown>export function desiredHookHashes(plan: ClaudeSetupPlan): HookHashes {const out: HookHashes = {};for (const event of plan.events) {- out[event] = hookEntryHash({ type: 'command', command: buildClaudeHookCommand(plan.launcher, event, hookEnv(plan)), timeout: CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS[event] })!;+ out[event] = hookEntryHash({ type: 'command', command: buildClaudeHookCommand(plan.launcher, event, hookEnv(plan), hookLauncherPath(plan.brainHome)), timeout: CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS[event] })!;}return out;}@@ -274,6 +275,8 @@ export async function applyClaudeSetup(const paths = claudeSetupPaths(plan);const lock = await acquireBootstrapLock(dirname(paths.configPath));try {+ // 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);const now = new Date().toISOString();const desired = desiredMcpEntry(plan);@@ -333,7 +336,7 @@ export async function applyClaudeSetup(} else {const ownedHashes = new Set([...values(prior?.hooks.owned), ...values(prior?.hooks.pending), ...values(receipt.hooks.pending)]);writeClaudeHooksAt(paths.settingsPath, {- gbrainBin: plan.launcher, env: hookEnv(plan), events: writeEvents, marker: GBRAIN_SETUP_MARKER_VALUE,+ gbrainBin: plan.launcher, hookLauncher: hookLauncherPath(plan.brainHome), env: hookEnv(plan), events: writeEvents, marker: GBRAIN_SETUP_MARKER_VALUE,ownedEntryHashes: ownedHashes, freshMode: 0o600,});steps.push({ step: 'hooks', action: 'write', detail: writeEvents.length ? `${writeEvents.join(', ')} in ${paths.settingsPath}` : `removed setup's hooks from ${paths.settingsPath}` });diff --git a/src/core/setup/codex.ts b/src/core/setup/codex.tsindex 9127e4118e..0d632f1a61 100644--- a/src/core/setup/codex.ts+++ b/src/core/setup/codex.ts@@ -51,6 +51,7 @@ import {import { stdioServeArgv } from '../mcp-registration.ts';import type { McpSurface } from '../../mcp/surface.ts';import { SetupAbortInjected, type SetupConsent, type SetupStep } from './claude-code.ts';+import { ensureHookLauncher, hookLauncherPath } from './hook-launcher.ts';export const CODEX_SETUP_RECEIPT_VERSION = 2;@@ -144,7 +145,7 @@ export function desiredCodexMcpEntry(plan: Pick<CodexSetupPlan, 'launcher' | 'sufunction desiredGroups(plan: CodexSetupPlan): Partial<Record<CodexSetupEvent, CodexHookGroup>> {const env = { GBRAIN_HOME: plan.gbrainHomeEnv, GBRAIN_SOURCE: plan.sourceId ?? undefined };- return Object.fromEntries(plan.events.map((e) => [e, codexSetupHookGroup(plan.launcher, e, env)]));+ return Object.fromEntries(plan.events.map((e) => [e, codexSetupHookGroup(plan.launcher, e, env, 'setup', hookLauncherPath(plan.brainHome))]));}const hashes = (groups: Partial<Record<CodexSetupEvent, CodexHookGroup>>): Hashes =>@@ -238,6 +239,8 @@ export async function applyCodexSetup(mkdirSync(dirname(paths.configPath), { recursive: true, mode: 0o700 });const lock = await acquireBootstrapLock(dirname(paths.configPath));try {+ // 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);const prior = found.prior;const now = new Date().toISOString();diff --git a/src/core/setup/hook-launcher-refresh.ts b/src/core/setup/hook-launcher-refresh.tsnew file mode 100644index 0000000000..2840da28d9--- /dev/null+++ b/src/core/setup/hook-launcher-refresh.ts@@ -0,0 +1,116 @@+/**+ * hook-launcher-refresh.ts — \`gbrain post-upgrade\` moves hooks written before+ * the hook launcher existed onto it (#8424), so an upgrade alone closes the+ * hole: a hook that starts gbrain in the session's directory lets that+ * directory's bunfig.toml or .env run code on every prompt.+ *+ * Only gbrain's own entries move, through the writers that own them:+ * - the turn-rule lane (Claude Code user settings, Codex hooks.json):+ * syncTurnRuleHook with the binary and GBRAIN_HOME its old command names;+ * - each installed \`gbrain setup\` receipt of this install: the same apply+ * setup runs, with the plan the receipt records, and only when the MCP+ * entry is still exactly setup's (so the apply rewrites hooks, trust and+ * the receipt, nothing else). Anything else gets a line naming the+ * command that fixes it.+ * Project-scope setup installs are listed, never rewritten: setup writes those+ * from the project directory. Best-effort; never throws.+ */+import { readFileSync } from 'node:fs';+import { configDir } from '../config.ts';+import { 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 { localSetupRecords } from './local-receipts.ts';+import { hasTurnRuleHook, isTurnRuleEntry, syncTurnRuleHook, TURN_RULE_LANE_TOKEN } from './turn-hook.ts';++/** True when this command starts gbrain somewhere other than a current launcher. */+function needsLauncher(command: string): boolean {+ const launcher = hookLauncherInCommand(command);+ return !launcher || hookLauncherState(launcher).state !== 'current';+}++function claudeHookEntries(path: string): Array<Record<string, unknown>> {+ let hooks: unknown;+ try { hooks = (JSON.parse(readFileSync(path, 'utf8')) as { hooks?: unknown })?.hooks; } catch { return []; }+ if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) return [];+ return Object.values(hooks as Record<string, unknown>).filter(Array.isArray)+ .flatMap((groups) => (groups as unknown[]).flatMap((g) => (Array.isArray((g as { hooks?: unknown })?.hooks) ? (g as { hooks: unknown[] }).hooks : [])))+ .filter((e): e is Record<string, unknown> => !!e && typeof e === 'object' && typeof (e as Record<string, unknown>).command === 'string');+}++/** 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)) ?? [];+ if (words[0] !== 'env') return null;+ let i = 1;+ let gbrainHome: string | undefined;+ for (; i < words.length && /^[A-Z_]+=/.test(words[i]!); i++) if (words[i]!.startsWith('GBRAIN_HOME=')) gbrainHome = words[i]!.slice('GBRAIN_HOME='.length);+ const rest = words.slice(i);+ const at = rest.indexOf('hook');+ const gbrainBin = at > 0 ? rest[at - 1]! : undefined;+ return gbrainBin?.startsWith('/') ? { gbrainBin, ...(gbrainHome ? { gbrainHome } : {}) } : null;+}++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' });+ 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);+ 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' });+ 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}` : ''})`}.`);+}++async function refreshSetup(log: (line: string) => void): Promise<void> {+ const home = configDir();+ for (const record of localSetupRecords(home).filter((r) => r.status === 'installed')) {+ const rerun = `gbrain setup ${record.harness}${record.name === 'gbrain' ? '' : ` --name ${record.name}`}`;+ try {+ if (record.harness === 'claude-code') {+ 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);+ if (!ours.some(needsLauncher)) continue;+ if (receipt.scope === 'project') { log(`Hook launcher: gbrain's hooks in ${paths.settingsPath} start gbrain in the session's directory; from ${receipt.project_dir}, run ${rerun} --scope project.`); continue; }+ const homeEnv = ours.map((c) => parseClaudeHookCommand(c)?.env.GBRAIN_HOME).find((h) => h !== undefined);+ const plan: ClaudeSetupPlan = { name: receipt.name, scope: receipt.scope, launcher: receipt.launcher, brainHome: receipt.gbrain_home, ...(homeEnv ? { gbrainHomeEnv: homeEnv } : {}),+ 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; }+ await applyClaudeSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false });+ log(`Hook launcher: gbrain setup's claude-code hooks in ${paths.settingsPath} now start gbrain from its own directory.`);+ } else if (record.harness === 'codex') {+ const receipt = readCodexSetupReceipt(record.path).setup;+ if (!receipt) continue;+ const paths = codexSetupPaths(receipt.name);+ const ours = codexHookCensus(paths.hooksPath).filter((g) => g.lane === 'setup').flatMap((g) => g.commands);+ if (!ours.some(needsLauncher)) continue;+ 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; }+ await applyCodexSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false });+ log(`Hook launcher: gbrain setup's codex hooks in ${paths.hooksPath} now start gbrain from its own directory.`);+ }+ } catch (e) {+ log(`Hook launcher: gbrain's ${record.harness} hooks were not refreshed (${(e as Error).message}); run ${rerun}.`);+ }+ }+}++/** post-upgrade: move every gbrain-written hook this install can find onto the launcher. */+export async function refreshHookLaunchers(log: (line: string) => void = console.log): Promise<void> {+ try { refreshTurnRule(log); } catch (e) { log(`Hook launcher: the turn-rule hooks were not refreshed (${(e as Error).message}); run gbrain doctor --only harness_wiring.`); }+ try { await refreshSetup(log); } catch (e) { log(`Hook launcher: setup's hooks were not refreshed (${(e as Error).message}); run gbrain doctor --only harness_wiring.`); }+}+diff --git a/src/core/setup/hook-launcher.ts b/src/core/setup/hook-launcher.tsnew file mode 100644index 0000000000..e4b58e30d0--- /dev/null+++ b/src/core/setup/hook-launcher.ts@@ -0,0 +1,101 @@+/**+ * hook-launcher.ts — the trusted-directory launcher that the per-turn hooks+ * `gbrain setup <claude-code|codex>` and the turn-rule lane write run gbrain+ * through (#8424).+ *+ * Why: the script-mode install (`bun install -g`, `bun link`) maps the+ * `gbrain` bin to src/cli.ts, so Bun reads the working directory's+ * bunfig.toml (a top-level `preload` runs before any gbrain code) and its+ * .env files. Harnesses start hooks in the session's directory, so a hook+ * that ran gbrain directly would run a cloned repository's code as the user+ * on every prompt, with nothing for the user to approve.+ *+ * The launcher is a POSIX sh script at <config dir>/hook-launcher/gbrain-hook.+ * It records the session directory in GBRAIN_HOOK_CWD, moves into its own+ * directory and execs its arguments (the absolute gbrain binary and the hook+ * subcommand) there. That directory holds only the launcher: when anything+ * else is in it, the launcher refuses (exit 1, one stderr line) instead of+ * 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 { dirname, join } from 'node:path';+import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';+import { configDir } from '../config.ts';++export const HOOK_LAUNCHER_NAME = 'gbrain-hook';+export const HOOK_LAUNCHER_DIR = 'hook-launcher';+export const HOOK_CWD_ENV = 'GBRAIN_HOOK_CWD';++export const HOOK_LAUNCHER_SCRIPT = `#!/bin/sh+# gbrain hook launcher v1, written by gbrain setup (#8424); gbrain setup rewrites it.+# Bun reads bunfig.toml and .env from the working directory before gbrain runs,+# so hooks start gbrain from this directory, which holds only this file, and+# pass the session directory on in GBRAIN_HOOK_CWD.+GBRAIN_HOOK_CWD=$PWD+export GBRAIN_HOOK_CWD+case $0 in+ /*/${HOOK_LAUNCHER_NAME}) d=\${0%/*} ;;+ *) echo "gbrain hook launcher: run it by its absolute path, not $0" >&2; exit 1 ;;+esac+cd "$d" || exit 1+for f in * .*; do+ case $f in .|..|${HOOK_LAUNCHER_NAME}) continue ;; esac+ if [ -e "$f" ] || [ -L "$f" ]; then+ echo "gbrain hook launcher: refused: $d holds $f, which gbrain did not write and Bun would read. Remove it, then run: gbrain doctor --only harness_wiring" >&2+ exit 1+ fi+done+exec "$@"+`;++/** The launcher path for an install whose config dir is `home` (default: this process's). */+export function hookLauncherPath(home: string = configDir()): string {+ return join(home, HOOK_LAUNCHER_DIR, HOOK_LAUNCHER_NAME);+}++export type HookLauncherState = 'current' | 'missing' | 'stale' | 'foreign';++/** Files only. `foreign`: the launcher's directory holds something gbrain did not write, so the launcher refuses to run. */+export function hookLauncherState(path: string): { state: HookLauncherState; detail: string } {+ let names: string[];+ try { names = readdirSync(dirname(path)); } catch { return { state: 'missing', detail: `no hook launcher at ${path}` }; }+ const other = names.find((n) => n !== HOOK_LAUNCHER_NAME);+ if (other !== undefined) return { state: 'foreign', detail: `${dirname(path)} holds ${other}, which gbrain did not write, so the hook launcher refuses to start gbrain there` };+ try {+ const st = lstatSync(path);+ if (!st.isFile()) return { state: 'stale', detail: `${path} is not a regular file` };+ if (readFileSync(path, 'utf8') !== HOOK_LAUNCHER_SCRIPT) return { state: 'stale', detail: `${path} differs from the launcher this gbrain writes` };+ if ((st.mode & 0o100) === 0) return { state: 'stale', detail: `${path} is not executable` };+ } catch { return { state: 'missing', detail: `no hook launcher at ${path}` }; }+ return { state: 'current', detail: `hook launcher ${path}` };+}++/**+ * Write (or refresh) the launcher and return its path. Throws when its+ * directory holds anything else: gbrain never deletes a file it did not write,+ * and a hook routed through that directory would refuse anyway.+ */+export function ensureHookLauncher(path: string = hookLauncherPath()): string {+ const dir = dirname(path);+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ 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 });+ return path;+}++const LAUNCHER_WORD = new RegExp(`(?:^|\\s)(?:'(/[^']*/${HOOK_LAUNCHER_DIR}/${HOOK_LAUNCHER_NAME})'|(/[^\\s']*/${HOOK_LAUNCHER_DIR}/${HOOK_LAUNCHER_NAME}))(?=\\s)`);++/** 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;+}++/** 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();+}diff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.tsindex f7afbeb741..031870fae5 100644--- a/src/core/setup/turn-hook-check.ts+++ b/src/core/setup/turn-hook-check.ts@@ -18,7 +18,8 @@ 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 { GBRAIN_HOOK_MARKER_KEY, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.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';import { brainFirstTarget, openclawConfigPath, parseJson5ish } from './brain-first.ts';import { inspectHermesTurnHook } from './hermes-turn-hook.ts';@@ -112,6 +113,65 @@ export function inspectTurnHook(harness: string, opts: { projectDir?: string } =return { harness, state: 'not_supported', detail: `${harness} has no per-turn hook gbrain can install; the rule reaches it only through its instruction file` };}+/**+ * A hook the setup or turn-rule lane wrote that would let the session+ * directory's bunfig.toml or .env load (#8424): its command starts gbrain in+ * the session's directory (written before the hook launcher existed), or the+ * launcher it names is missing, changed, or shares its directory with a file+ * gbrain did not write.+ */+export interface HookLauncherProblem {+ harness: 'claude-code' | 'codex';+ lane: 'setup' | 'turn-rule';+ /** The settings or hooks file holding the entry. */+ source: string;+ /** session_cwd: no launcher in the command; otherwise the launcher's state. */+ reason: 'session_cwd' | Exclude<HookLauncherState, 'current'>;+ detail: string;+}++function claudeLaneCommands(path: 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 }> = [];+ for (const groups of Object.values(hooks as Record<string, unknown>)) {+ if (!Array.isArray(groups)) continue;+ for (const e of groups.flatMap((g) => (Array.isArray((g as { hooks?: unknown })?.hooks) ? (g as { hooks: unknown[] }).hooks : []))) {+ 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 });+ }+ }+ return out;+}++/** Files only. Every event's setup and turn-rule entries, user scope plus `projectDir`'s settings.local.json (Claude Code). */+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') {+ for (const source of [claudeUserSettingsPath(), ...(opts.projectDir ? [join(opts.projectDir, CLAUDE_SETTINGS_FILE_RELPATH)] : [])]) {+ found.push(...claudeLaneCommands(source).map((c) => ({ ...c, source })));+ }+ } else {+ try {+ for (const g of codexHookCensus(codexHooksPath())) {+ if (g.lane === 'setup' || g.lane === 'turn-rule') found.push(...g.commands.map((command) => ({ lane: g.lane as 'setup' | 'turn-rule', command, source: codexHooksPath() })));+ }+ } catch { /* unparseable: Codex runs none of it */ }+ }+ for (const f of found) {+ const launcher = hookLauncherInCommand(f.command);+ if (!launcher) {+ return { harness, lane: f.lane, source: f.source, reason: 'session_cwd',+ detail: `gbrain's ${f.lane} hook in ${f.source} starts gbrain in the session's directory, so Bun loads that directory's bunfig.toml and .env before gbrain runs` };+ }+ const s = hookLauncherState(launcher);+ if (s.state !== 'current') return { harness, lane: f.lane, source: f.source, reason: s.state, detail: `gbrain's ${f.lane} hook in ${f.source} runs through ${launcher}, but ${s.detail}` };+ }+ return null;+}+type Run = (argv: string[], stdin?: string) => { ok: boolean; output: string };/** Only what a hook needs to find the brain and the rule; never provider keys. */function hookEnv(): Record<string, string> {diff --git a/src/core/setup/turn-hook.ts b/src/core/setup/turn-hook.tsindex 8a007ed13d..e2a420af11 100644--- a/src/core/setup/turn-hook.ts+++ b/src/core/setup/turn-hook.ts@@ -11,7 +11,9 @@* rides only the MCP tool list (2 of 99) or a startup file (0 of 80).** The hook is one UserPromptSubmit entry running- * `env GBRAIN_HOOK_LANE=turn-rule <gbrain> hook user-prompt`. In that lane the+ * `env GBRAIN_HOOK_LANE=turn-rule <launcher> <gbrain> hook user-prompt`, where+ * <launcher> starts gbrain from its own directory so the session directory's+ * bunfig.toml and .env never load (#8424, hook-launcher.ts). In that lane the* hook adds only the rule (read from the brain-first ledger, so an opt-out or* GBRAIN_AGENT_INSTRUCTIONS=0 silences it) and never reads local context: the* connection may point at another brain. It yields when another gbrain lane@@ -36,6 +38,7 @@ import { codexHookCensus, codexHookGroupRuns, codexHookTrustHash, codexSetupHookimport { appendCodexTomlTable, readCodexTomlTable, removeCodexTomlTable } from '../bootstrap/codex-toml.ts';import { buildClaudeHookCommand, classifyHarnessHook, hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../bootstrap/hooks.ts';import { CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS, GBRAIN_HOOK_MARKER_KEY, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';+import { ensureHookLauncher, hookLauncherPath, hookLauncherState } from './hook-launcher.ts';export const TURN_RULE_LANE = 'turn-rule';export const TURN_RULE_MARKER = 'turn-rule-v1';@@ -52,6 +55,8 @@ export interface TurnHookPaths {/** Codex hooks.json and config.toml (default: CODEX_HOME's). */codexHooks?: string;codexConfig?: string;+ /** The trusted-directory hook launcher (default: this install's, hook-launcher.ts). */+ hookLauncher?: string;}export interface TurnHookOutcome {@@ -66,12 +71,12 @@ export interface TurnHookOutcome {const claudePath = (p: TurnHookPaths) => p.claudeSettings ?? claudeUserSettingsPath();const codexPaths = (p: TurnHookPaths) => ({ hooks: p.codexHooks ?? codexHooksPath(), config: p.codexConfig ?? codexConfigPath() });-export function claudeTurnRuleCommand(gbrainBin: string, gbrainHome?: string): string {- return buildClaudeHookCommand(gbrainBin, EVENT, { ...(gbrainHome ? { GBRAIN_HOME: gbrainHome } : {}), GBRAIN_HOOK_LANE: TURN_RULE_LANE });+export function claudeTurnRuleCommand(gbrainBin: string, gbrainHome: string | undefined, launcher: string): string {+ return buildClaudeHookCommand(gbrainBin, EVENT, { ...(gbrainHome ? { GBRAIN_HOME: gbrainHome } : {}), GBRAIN_HOOK_LANE: TURN_RULE_LANE }, launcher);}-export function codexTurnRuleGroup(gbrainBin: string, gbrainHome?: string): CodexHookGroup {- return codexSetupHookGroup(gbrainBin, EVENT, gbrainHome ? { GBRAIN_HOME: gbrainHome } : {}, TURN_RULE_LANE);+export function codexTurnRuleGroup(gbrainBin: string, gbrainHome: string | undefined, launcher: string): CodexHookGroup {+ return codexSetupHookGroup(gbrainBin, EVENT, gbrainHome ? { GBRAIN_HOME: gbrainHome } : {}, TURN_RULE_LANE, launcher);}/** A Claude Code hook entry that is this lane's: marked, or (marker dropped) its command shape. */@@ -127,15 +132,20 @@ export function syncTurnRuleHook(opts: { harness: TurnRuleHarness; gbrainBin: stconst print = (why: string): TurnHookOutcome => ({ harness: opts.harness, action: 'print', path: where, detail: `per-turn rule hook not installed: ${why}`, next: opts.rerun });if (!opts.gbrainBin || !opts.gbrainBin.startsWith('/')) return print('no absolute gbrain binary was found (harnesses inherit no PATH); install gbrain globally or pass --gbrain-bin');try {- return opts.harness === 'codex' ? syncCodex(opts.gbrainBin, opts.gbrainHome, codexPaths(paths), !!opts.dryRun, print)- : syncClaude(opts.gbrainBin, opts.gbrainHome, claudePath(paths), !!opts.dryRun);+ const launcher = paths.hookLauncher ?? hookLauncherPath();+ // The launcher goes down first: a hook that names it must find it.+ const launcherFresh = hookLauncherState(launcher).state === 'current';+ if (!opts.dryRun) ensureHookLauncher(launcher);+ const outcome = opts.harness === 'codex' ? syncCodex(opts.gbrainBin, opts.gbrainHome, launcher, codexPaths(paths), !!opts.dryRun, print)+ : syncClaude(opts.gbrainBin, opts.gbrainHome, launcher, claudePath(paths), !!opts.dryRun);+ return outcome.action === 'keep' && !launcherFresh ? { ...outcome, action: 'write', detail: `${outcome.detail}; hook launcher ${launcher}` } : outcome;} catch (e) {return print((e as Error).message);}}-function syncClaude(bin: string, home: string | undefined, path: string, dryRun: boolean): TurnHookOutcome {- const command = claudeTurnRuleCommand(bin, home);+function syncClaude(bin: string, home: string | undefined, launcher: string, path: string, dryRun: boolean): TurnHookOutcome {+ const command = claudeTurnRuleCommand(bin, home, launcher);const want = { type: 'command', command, timeout: CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS[EVENT] };const wantHash = hookEntryHash(want)!;const ours = claudePromptEntries(path).filter(isTurnRuleEntry);@@ -144,7 +154,7 @@ function syncClaude(bin: string, home: string | undefined, path: string, dryRun:if (dryRun) return { harness: 'claude-code', action: 'write', path, detail };mkdirSync(dirname(path), { recursive: true });const owned = new Set([wantHash, ...ours.map((e) => hookEntryHash(e)).filter((h): h is string => !!h)]);- writeClaudeHooksAt(path, { gbrainBin: bin, env: { ...(home ? { GBRAIN_HOME: home } : {}), GBRAIN_HOOK_LANE: TURN_RULE_LANE, GBRAIN_SEAT: '' },+ writeClaudeHooksAt(path, { gbrainBin: bin, hookLauncher: launcher, env: { ...(home ? { GBRAIN_HOME: home } : {}), GBRAIN_HOOK_LANE: TURN_RULE_LANE, GBRAIN_SEAT: '' },events: [EVENT], marker: TURN_RULE_MARKER, ownedEntryHashes: owned, freshMode: 0o600 });return { harness: 'claude-code', action: 'write', path, detail };}@@ -164,8 +174,8 @@ function dropOurTrust(config: string, key: string, commands: string[]): void {removeCodexTomlTable(config, trustPath(key));}-function syncCodex(bin: string, home: string | undefined, paths: { hooks: string; config: string }, dryRun: boolean, print: (why: string) => TurnHookOutcome): TurnHookOutcome {- const group = codexTurnRuleGroup(bin, home);+function syncCodex(bin: string, home: string | undefined, launcher: string, paths: { hooks: string; config: string }, dryRun: boolean, print: (why: string) => TurnHookOutcome): TurnHookOutcome {+ const group = codexTurnRuleGroup(bin, home, launcher);const hash = ownedEntryFingerprint(group);const ours = codexOurs(paths);const detail = `per-turn rule hook (UserPromptSubmit) in ${paths.hooks}, trusted in ${paths.config}`;@@ -187,6 +197,11 @@ function syncCodex(bin: string, home: string | undefined, paths: { hooks: stringreturn { harness: 'codex', action: 'write', path: paths.hooks, detail };}+/** This lane's own entry is present (Claude Code settings file, or Codex hooks.json); false for an unreadable file. */+export function hasTurnRuleHook(harness: TurnRuleHarness, paths: TurnHookPaths = {}): boolean {+ try { return harness === 'codex' ? codexOurs(codexPaths(paths)).length > 0 : claudePromptEntries(claudePath(paths)).some(isTurnRuleEntry); } catch { return false; }+}+/** Remove the turn-rule hook (opt-out or uninstall). Never throws. */export function removeTurnRuleHook(opts: { harness: TurnRuleHarness; paths?: TurnHookPaths; dryRun?: boolean }): TurnHookOutcome {const paths = opts.paths ?? {};diff --git a/test/hook-launcher-bunfig.test.ts b/test/hook-launcher-bunfig.test.tsnew file mode 100644index 0000000000..3923e5e8e5--- /dev/null+++ b/test/hook-launcher-bunfig.test.ts@@ -0,0 +1,200 @@+/**+ * #8424: the hooks gbrain writes never let the session directory's bunfig.toml+ * or .env run. The script-mode install maps the gbrain bin to src/cli.ts, and+ * Bun applies a top-level bunfig.toml preload from the working directory+ * before any gbrain code; harnesses start hooks in the session's directory.+ * Every hook here is installed by the real writer, then run with sh -c from a+ * directory whose bunfig.toml preload drops a marker file, the way Claude Code+ * 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 { 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 { 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 { refreshHookLaunchers } from '../src/core/setup/hook-launcher-refresh.ts';++const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');+const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++/** A temp HOME with a script-mode gbrain (a symlink to src/cli.ts, as bun install -g makes it) and a hostile checkout. */+function box() {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-hook-launcher-'));+ roots.push(root);+ const home = join(root, 'home');+ const bin = join(root, 'bin');+ const hostile = join(root, 'hostile-checkout');+ const tmp = join(root, 'tmp');+ for (const d of [home, bin, join(hostile, 'tooling'), tmp]) mkdirSync(d, { recursive: true });+ symlinkSync(process.execPath, join(bin, 'bun'));+ symlinkSync(CLI, join(bin, 'gbrain'));+ const marker = join(root, 'PRELOAD_RAN');+ 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');+ const launcher = hookLauncherPath(join(home, '.gbrain'));+ const env: Record<string, string> = { HOME: home, GBRAIN_HOME: home, PATH: `${bin}:/usr/bin:/bin`, TMPDIR: tmp, GBRAIN_AGENT_INSTRUCTIONS: '0' };+ return { root, home, gbrain: join(bin, 'gbrain'), hostile, tmp, marker, launcher, env };+}+type Box = ReturnType<typeof box>;++/** Run a hook command the way the harness does: sh -c from the session directory, the event JSON on stdin. */+function runHook(b: Box, command: string, cwd = b.hostile) {+ const r = Bun.spawnSync(['sh', '-c', command], { cwd, env: b.env, stdin: Buffer.from(JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt: 'hi', session_id: 'hook-launcher-test', cwd })), stdout: 'pipe', stderr: 'pipe', timeout: 60_000 });+ return { exitCode: r.exitCode, stdout: r.stdout.toString(), stderr: r.stderr.toString() };+}++/** SessionEnd detaches a grandchild that removes its payload file when it exits; wait for that. */+async function waitForDetached(b: Box) {+ for (let i = 0; i < 300 && readdirSync(b.tmp).length > 0; i++) await Bun.sleep(100);+ expect(readdirSync(b.tmp)).toEqual([]);+}++const readJson = (p: string) => JSON.parse(readFileSync(p, 'utf8'));++describe('a hook run from a checkout whose bunfig.toml preloads code never runs that preload', () => {+ test('control: script-mode gbrain started in that checkout runs the preload (the hole the launcher closes)', () => {+ const b = box();+ const r = runHook(b, `${b.gbrain} --version`);+ expect(r.exitCode).toBe(0);+ expect(existsSync(b.marker)).toBe(true);+ });++ test('claude-code turn-rule hook (setup --instructions-only, connect --install, bootstrap harness)', () => {+ const b = box();+ const settings = join(b.home, '.claude', 'settings.json');+ const o = syncTurnRuleHook({ harness: 'claude-code', gbrainBin: b.gbrain, paths: { claudeSettings: settings, hookLauncher: b.launcher }, rerun: 'x' });+ expect(o.action).toBe('write');+ const [entry] = readJson(settings).hooks.UserPromptSubmit.flatMap((g: { hooks: unknown[] }) => g.hooks);+ expect(entry._gbrain).toBe(TURN_RULE_MARKER);+ const r = runHook(b, entry.command);+ expect(r.stderr).toBe('');+ expect(r.exitCode).toBe(0);+ expect(existsSync(b.marker)).toBe(false);+ });++ test('codex turn-rule hook', () => {+ const b = box();+ const hooks = join(b.home, '.codex', 'hooks.json');+ const o = syncTurnRuleHook({ harness: 'codex', gbrainBin: b.gbrain, paths: { codexHooks: hooks, codexConfig: join(b.home, '.codex', 'config.toml'), hookLauncher: b.launcher }, rerun: 'x' });+ expect(o.action).toBe('write');+ const command = readJson(hooks).hooks.UserPromptSubmit[0].hooks[0].command;+ const r = runHook(b, command);+ expect(r.stderr).toBe('');+ expect(r.exitCode).toBe(0);+ expect(existsSync(b.marker)).toBe(false);+ });++ test('gbrain setup claude-code hook shape, every event', () => {+ const b = box();+ ensureHookLauncher(b.launcher);+ for (const event of ['SessionStart', 'UserPromptSubmit', 'Stop', 'PreCompact'] as const) {+ const command = buildClaudeHookCommand(b.gbrain, event, { GBRAIN_SOURCE: 'default', GBRAIN_HOME: b.home, GBRAIN_SEAT: '' }, b.launcher);+ expect(runHook(b, command).exitCode).toBe(0);+ expect(existsSync(b.marker)).toBe(false);+ }+ });++ test('gbrain setup codex hook shape: SessionStart, UserPromptSubmit and the detached SessionEnd', async () => {+ const b = box();+ ensureHookLauncher(b.launcher);+ for (const event of ['SessionStart', 'UserPromptSubmit', 'SessionEnd'] as const) {+ const command = codexSetupHookGroup(b.gbrain, event, { GBRAIN_HOME: b.home }, 'setup', b.launcher).hooks[0]!.command;+ expect(runHook(b, command).exitCode).toBe(0);+ if (event === 'SessionEnd') await waitForDetached(b);+ expect(existsSync(b.marker)).toBe(false);+ }+ });+});++describe('the launcher', () => {+ test('passes the session directory on in GBRAIN_HOOK_CWD and runs from its own directory', () => {+ const b = box();+ ensureHookLauncher(b.launcher);+ const r = runHook(b, `${b.launcher} /bin/sh -c 'printf "%s|%s" "$GBRAIN_HOOK_CWD" "$(pwd)"'`);+ expect(r.stdout).toBe(`${b.hostile}|${dirname(b.launcher)}`);+ });++ test('refuses to start anything when its directory holds a file gbrain did not write', () => {+ const b = box();+ ensureHookLauncher(b.launcher);+ writeFileSync(join(dirname(b.launcher), 'bunfig.toml'), `preload = [${JSON.stringify(join(b.hostile, 'tooling', 'pre.ts'))}]\n`);+ const r = runHook(b, `${b.launcher} ${b.gbrain} --version`);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain('refused');+ expect(existsSync(b.marker)).toBe(false);+ expect(hookLauncherState(b.launcher).state).toBe('foreign');+ expect(() => ensureHookLauncher(b.launcher)).toThrow(/did not write/);+ });++ test('ensureHookLauncher rewrites a changed launcher and keeps its directory private', () => {+ const b = box();+ ensureHookLauncher(b.launcher);+ writeFileSync(b.launcher, '#!/bin/sh\nexec "$@"\n');+ expect(hookLauncherState(b.launcher).state).toBe('stale');+ ensureHookLauncher(b.launcher);+ expect(hookLauncherState(b.launcher).state).toBe('current');+ expect(readdirSync(dirname(b.launcher))).toEqual([HOOK_LAUNCHER_NAME]);+ });+});++describe('hooks written before the launcher: doctor flags them, post-upgrade moves them', () => {+ const env = (b: Box) => ({ HOME: b.home, GBRAIN_HOME: b.home, CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: join(b.home, '.codex'), XDG_CONFIG_HOME: undefined });++ test('claude-code: an old turn-rule entry is flagged session_cwd, then refreshed onto the launcher', async () => {+ const b = box();+ const settings = join(b.home, '.claude', 'settings.json');+ const old = buildClaudeHookCommand(b.gbrain, 'UserPromptSubmit', { GBRAIN_HOOK_LANE: 'turn-rule' });+ mkdirSync(dirname(settings), { recursive: true });+ writeFileSync(settings, JSON.stringify({ hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: old, timeout: 15, _gbrain: TURN_RULE_MARKER }] }] } }));+ expect(runHook(b, old).exitCode).toBe(0);+ expect(existsSync(b.marker)).toBe(true);+ rmSync(b.marker);+ await withEnv(env(b), async () => {+ expect(hookLauncherProblem('claude-code')).toMatchObject({ lane: 'turn-rule', reason: 'session_cwd' });+ const lines: string[] = [];+ await refreshHookLaunchers((l) => lines.push(l));+ expect(lines.join('\n')).toContain('claude-code turn-rule hook now starts gbrain from its own directory');+ expect(hookLauncherProblem('claude-code')).toBeNull();+ });+ const entries = readJson(settings).hooks.UserPromptSubmit.flatMap((g: { hooks: unknown[] }) => g.hooks);+ expect(entries).toHaveLength(1);+ expect(runHook(b, entries[0].command).exitCode).toBe(0);+ expect(existsSync(b.marker)).toBe(false);+ });++ test('codex: an old turn-rule group is flagged, then refreshed with a matching trust entry', async () => {+ const b = box();+ const hooks = join(b.home, '.codex', 'hooks.json');+ const config = join(b.home, '.codex', 'config.toml');+ await withEnv(env(b), async () => {+ const old = codexSetupHookGroup(b.gbrain, 'UserPromptSubmit', {}, 'turn-rule');+ mkdirSync(dirname(hooks), { recursive: true });+ writeFileSync(hooks, JSON.stringify({ hooks: { UserPromptSubmit: [old] } }));+ expect(hookLauncherProblem('codex')).toMatchObject({ lane: 'turn-rule', reason: 'session_cwd' });+ await refreshHookLaunchers(() => {});+ expect(hookLauncherProblem('codex')).toBeNull();+ });+ const command = readJson(hooks).hooks.UserPromptSubmit[0].hooks[0].command;+ expect(readFileSync(config, 'utf8')).toContain('user_prompt_submit');+ expect(runHook(b, command).exitCode).toBe(0);+ expect(existsSync(b.marker)).toBe(false);+ });++ test('a launcher whose directory gained a foreign file is flagged foreign', async () => {+ const b = box();+ await withEnv(env(b), async () => {+ const settings = join(b.home, '.claude', 'settings.json');+ syncTurnRuleHook({ harness: 'claude-code', gbrainBin: b.gbrain, paths: { claudeSettings: settings }, rerun: 'x' });+ expect(hookLauncherProblem('claude-code')).toBeNull();+ writeFileSync(join(dirname(hookLauncherPath()), '.env'), 'X=1\n');+ expect(hookLauncherProblem('claude-code')).toMatchObject({ reason: 'foreign' });+ });+ });+});diff --git a/test/setup.test.ts b/test/setup.test.tsindex 688d55ee03..b8d26c45a7 100644--- a/test/setup.test.ts+++ b/test/setup.test.ts@@ -29,6 +29,10 @@ import { codexHookTrustHash, codexTrustHash, removeCodexHooks, writeCodexHooks }import { appendCodexTomlTable, removeCodexTomlTable } from '../src/core/bootstrap/codex-toml.ts';import { defineNormalizer, expectGolden, scrubTimestamps } from './helpers/golden.ts';import { VERSION } from '../src/version.ts';+import { withEnv } from './helpers/with-env.ts';+import { ownedEntryFingerprint } from '../src/core/bootstrap/adopted-connections.ts';+import { hookLauncherProblem, inspectTurnHook } from '../src/core/setup/turn-hook-check.ts';+import { refreshHookLaunchers } from '../src/core/setup/hook-launcher-refresh.ts';const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');const roots: string[] = [];@@ -550,7 +554,7 @@ describe('gbrain setup codex: install lifecycle', () => {expect(toml(b).mcp_servers.gbrain).toEqual({ command: b.bin, args: ['serve', '--surface', 'starter', '--advertise', 'verbs'], env: { GBRAIN_HOME: b.gbrainHome } });expect(Object.keys(readJson(hooksJson(b)).hooks).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);expect(groups(b, 'UserPromptSubmit')).toEqual([{ hooks: [{ type: 'command', timeout: 15,- command: `env GBRAIN_HOOK_LANE=setup GBRAIN_HOME=${b.gbrainHome} ${b.bin} hook user-prompt --harness codex` }] }]);+ command: `env GBRAIN_HOOK_LANE=setup GBRAIN_HOME=${b.gbrainHome} ${b.gbrainHome}/.gbrain/hook-launcher/gbrain-hook ${b.bin} hook user-prompt --harness codex` }] }]);expect(trustKeys(b)).toEqual([trustKey(b, 'session_start', 0), trustKey(b, 'user_prompt_submit', 0)]);const r = readJson(codexReceipt(b));expect(r).toMatchObject({ harness: 'codex', connection: 'local-stdio', setup_receipt_version: 2, status: 'installed' });@@ -856,3 +860,83 @@ describe('codex trust hash and hash-owned TOML tables', () => {expect(readFileSync(path, 'utf8')).toBe(split);});});++describe('hooks written before the hook launcher (#8424): the next setup and post-upgrade move them', () => {+ const launcher = (b: Box) => join(b.gbrainHome, '.gbrain', 'hook-launcher', 'gbrain-hook');+ const env = (b: Box) => ({ ...CLEAN, HOME: b.home, GBRAIN_HOME: b.gbrainHome, CODEX_HOME: join(b.home, '.codex'), XDG_CONFIG_HOME: undefined });+ 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 {+ const s = readJson(settings(b));+ const r = readJson(receipt(b));+ for (const [event, groups] of Object.entries(s.hooks as Record<string, any[]>)) {+ for (const e of groups.flatMap((g) => g.hooks)) {+ if (e._gbrain !== 'setup-v1') continue;+ e.command = e.command.replace(` ${launcher(b)} `, ' ');+ r.hooks.owned[event] = hookEntryHash(e);+ }+ }+ writeFileSync(settings(b), JSON.stringify(s, null, 2));+ writeFileSync(receipt(b), JSON.stringify(r, null, 2));+ }++ /** The same for Codex: hooks.json groups, their trust tables and the receipt's fingerprints. */+ function downgradeCodex(b: Box): void {+ const hooks = readJson(hooksJson(b));+ const r = readJson(codexReceipt(b));+ const states: Record<string, string> = { SessionStart: 'session_start', UserPromptSubmit: 'user_prompt_submit' };+ for (const event of Object.keys(states)) {+ (hooks.hooks[event] as any[]).forEach((group, index) => {+ const h = group.hooks[0];+ if (!h.command.includes('GBRAIN_HOOK_LANE=setup')) return;+ h.command = h.command.replace(` ${launcher(b)} `, ' ');+ r.hooks.owned[event] = ownedEntryFingerprint(group);+ const key = `${hooksJson(b)}:${states[event]}:${index}:0`;+ const table = { trusted_hash: codexHookTrustHash(states[event]!, h.command, h.timeout) };+ removeCodexTomlTable(codexToml(b), ['hooks', 'state', key]);+ appendCodexTomlTable(codexToml(b), ['hooks', 'state', key], table, 'gbrain setup: trust');+ r.trust.owned[event] = { key, hash: ownedEntryFingerprint({ key, table }) };+ });+ }+ writeFileSync(hooksJson(b), JSON.stringify(hooks, null, 2));+ writeFileSync(codexReceipt(b), JSON.stringify(r, null, 2));+ }+ const codexSetupCommands = (b: Box) => ['SessionStart', 'UserPromptSubmit'].flatMap((e) => setupGroups(b, e).map((g: any) => g.hooks[0].command as string));++ test('claude-code: doctor flags them, a setup re-run rewrites them, and so does post-upgrade', async () => {+ const b = box();+ expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);+ const claudeCommands = () => ['SessionStart', 'UserPromptSubmit'].flatMap((e) => entries(b, e).map((x) => x.command as string));+ expect(viaLauncher(b, claudeCommands())).toBe(true);+ downgradeClaude(b);+ await withEnv(env(b), async () => { expect(hookLauncherProblem('claude-code')).toMatchObject({ lane: 'setup', reason: 'session_cwd' }); });+ expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);+ expect(viaLauncher(b, claudeCommands())).toBe(true);++ downgradeClaude(b);+ await withEnv(env(b), async () => {+ const lines: string[] = [];+ await refreshHookLaunchers((l) => lines.push(l));+ expect(lines.join('\n')).toContain("gbrain setup's claude-code hooks");+ expect(hookLauncherProblem('claude-code')).toBeNull();+ });+ expect(viaLauncher(b, claudeCommands())).toBe(true);+ expect((await setup(b, ['claude-code', '--json'])).doc.steps.map((s: any) => s.action)).toEqual(['keep', 'keep', 'keep']);+ });++ 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);+ downgradeCodex(b);+ expect(viaLauncher(b, codexSetupCommands(b))).toBe(false);+ await withEnv(env(b), async () => {+ expect(hookLauncherProblem('codex')).toMatchObject({ lane: 'setup', reason: 'session_cwd' });+ await refreshHookLaunchers(() => {});+ expect(hookLauncherProblem('codex')).toBeNull();+ expect(inspectTurnHook('codex')).toMatchObject({ state: 'wired', via: 'setup' });+ });+ expect(viaLauncher(b, codexSetupCommands(b))).toBe(true);+ expect((await setup(b, ['codex', '--json'])).doc.steps.map((s: any) => s.action)).toEqual(['keep', 'keep', 'keep', 'keep']);+ });+});