Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Codex starts the gbrain MCP server and hooks when bun is not on its PATH (GST-2784) (#9421)
Garry Tan0a4ed211e2b8
diff --git a/behavior-changes.d/launcher_records_bun_gst2784.md b/behavior-changes.d/launcher_records_bun_gst2784.mdnew file mode 100644index 0000000000..4796b73f8f--- /dev/null+++ b/behavior-changes.d/launcher_records_bun_gst2784.md@@ -0,0 +1 @@+gbrain's hook launcher (<config dir>/hook-launcher/gbrain-hook), which every MCP server entry and hook gbrain setup writes starts gbrain through, now records the Bun that installed gbrain and puts it first on PATH. Before, a Codex session started without bun on its PATH (the desktop app, a launcher, a terminal opened before the shell profile changed) could not start gbrain serve or its hooks, and showed no tools. gbrain post-upgrade rewrites the launcher in place, and gbrain setup codex does the same; no config.toml, hooks.json or trust entry changes. gbrain doctor reports a launcher that records no Bun, or a Bun that is gone. The compiled gbrain binary needs no Bun and its launcher does not change.diff --git a/changelog.d/fix-codex-bare-path-bun-runtime.md b/changelog.d/fix-codex-bare-path-bun-runtime.mdnew file mode 100644index 0000000000..11de4f549b--- /dev/null+++ b/changelog.d/fix-codex-bare-path-bun-runtime.md@@ -0,0 +1,13 @@+---+important: blocker+---+**Codex starts the gbrain MCP server and hooks even when bun is not on its PATH.**++<!-- behavior-change: launcher_records_bun_gst2784 -->++### Fixed+- After `gbrain setup codex`, a Codex session started without bun on its PATH (the desktop app, a launcher, a terminal opened before the shell profile changed) failed with `/usr/bin/env: 'bun': No such file or directory` and showed no gbrain tools, with nothing telling you why. gbrain's hook launcher, which every MCP server entry and hook setup writes runs through, now records the Bun that installed gbrain, so those entries start from any PATH. The same gap closes for Claude Code, Hermes and OpenClaw entries that run through the launcher. The compiled binary needs no Bun and is unchanged. (GST-2784)+- `gbrain doctor` reports a launcher that records no Bun, or one whose Bun is gone, instead of calling the wiring healthy.++### To take this fix+- `gbrain upgrade` (its post-upgrade step rewrites the default install's launcher), or rerun `gbrain setup codex`. Neither changes config.toml, hooks.json or Codex's trust entries. A launcher under another gbrain home is rewritten by rerunning the setup that wrote it; `gbrain doctor` names it.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 422f697867..80318c372c 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -32,7 +32,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/setup-brain-layout.ts` — `gbrain setup claude-code|codex --shape personal|company|both [--notes DIR] [--docs DIR] [--team|--solo]` (GST-2731; guide `docs/guides/brain-layout.md`). Every page is written create-only through `gbrain get` then `gbrain put` children, and only when `get` reports `page_not_found` (empty forms, `status: stub`, one "Example (delete me)" line each): `me/facts`, `me/voice`, `me/how-i-decide` in the run's source, and `COMPANY_PAGES` (`company/facts`, `company/decisions`, `company/pricing`, `company/customers`, `company/calls`, `company/playbooks`) in the `company` source. The company source is kept when it exists, else added with `gbrain sources add company --path <dir>` on a gbrain-owned folder beside the default source's content root (never the person's docs folder; a path there that is not an empty folder fails the company part with an `ask_user` `brain_layout_pages_pending` and the block is written without company lines) with no federation flag, so `sources add` federates it only on a one-person brain (#9396); when it reads back unfederated, setup returns `source_not_in_default_search` with `ask_user`. `--notes` and `--docs` import read only with one `gbrain import DIR --no-embed --json` child each (GBRAIN_SOURCE pins the source; over `IMPORT_INLINE_MAX` = 500 markdown files it returns `brain_layout_import_pending` instead), then check keyless search finds the first file's title in the top 5 (company docs through default search when federated). `--team` creates nothing for the company part and returns `brain_layout_team_next`. A `<!-- gbrain:brain-layout:begin/end -->` block (lines per part) goes into the brain-first target only when the brain-first decision is accepted; `--no-instructions` removes it, `--shape none` removes it and keeps pages and source. A brand-new brain set up without `--shape` asks inline only when `isInteractive()`, otherwise `brain_shape` joins the `first_run_decisions` bundle (default none, nothing written). The flag is `--shape` because `--brain` is the global brain-id flag (`cli-options.ts`). Pinned by `test/setup-brain-layout.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 (`underInstructionLedgerLock` holds one lock, `<configDir>/agent-instructions.lock`, shared with `skill-loading.json`, across the ledger read, the file and permission edits and the ledger write, re-reads a recorded decision under it, reports a lock it cannot take within 10 seconds as `preserve`, and a dry run takes none; `test/instruction-ledger-lock.test.ts`, `test/instruction-ledger-lock-timeout.slow.test.ts`), 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 <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; it also reads Claude Code's managed `managed-settings.json` and `managed-settings.d/*.json`, and `turnRuleHookYields` counts a managed gbrain hook, #8057) 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. The stdio MCP entries (`desiredMcpEntry`, `desiredCodexMcpEntry`, `registerClaudeMcp`/`registerCodexMcp` with `hookLauncher`) and the bootstrap, harness and Codex SessionEnd lanes use it too (#8426, #8428); `gbrain serve` captures `GBRAIN_HOOK_CWD` through `src/core/session-cwd.ts` and never changes directory. `src/core/setup/launcher-lanes.ts` (`launcherLaneFindings`) finds those entries for doctor and post-upgrade; post-upgrade rewrites only a Claude Code setup MCP entry setup still owns, under the setup lock, and names every Codex and bootstrap entry. Tests: `test/launcher-lanes-bunfig.serial.test.ts`. Tests: `test/hook-launcher-bunfig.test.ts` (a hostile checkout's preload never runs from any shape), `test/setup.test.ts` (#8424 block).+- `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. A script-mode install's launcher also records the directory of the Bun that wrote it (`launcherRuntimeDir`, preferring the bun on PATH when it is the same file; `hookLauncherScript(dir)`) and puts it first on PATH, so a harness started without bun on PATH still starts gbrain (GST-2784); a compiled gbrain gets the plain launcher (`isScriptRuntime`, exported from cli-preflight.ts). `hookLauncherState` calls a launcher `stale` when it records no Bun that a script install needs, or a Bun that is gone, and `ensureHookLauncher` moves a launcher that records another Bun. 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`, rewrites this install's stale launcher file in place (no entry changes, so no Codex trust moves) and moves the turn-rule entries and each installed user-scope setup receipt's hooks onto the launcher through their own writers. The stdio MCP entries (`desiredMcpEntry`, `desiredCodexMcpEntry`, `registerClaudeMcp`/`registerCodexMcp` with `hookLauncher`) and the bootstrap, harness and Codex SessionEnd lanes use it too (#8426, #8428); `gbrain serve` captures `GBRAIN_HOOK_CWD` through `src/core/session-cwd.ts` and never changes directory. `src/core/setup/launcher-lanes.ts` (`launcherLaneFindings`) finds those entries for doctor and post-upgrade; post-upgrade rewrites only a Claude Code setup MCP entry setup still owns, under the setup lock, and names every Codex and bootstrap entry. Tests: `test/launcher-lanes-bunfig.serial.test.ts`. Tests: `test/hook-launcher-bunfig.test.ts` (a hostile checkout's preload never runs from any shape), `test/setup.test.ts` (#8424 block), `test/setup-codex-bare-path.test.ts` (setup codex's entries start under a PATH with no bun).- `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/repair.md b/docs/guides/repair.mdindex f3de1c8b2b..6f505d965a 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -5230,14 +5230,17 @@ directory in `GBRAIN_HOOK_CWD` and runs gbrain from its own directory. The- `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.+ or not executable, or (on a `bun install -g` install) it records no Bun or a+ Bun that is no longer there, so a harness started without bun on PATH, like+ the Codex app, cannot start gbrain.- `foreign`: the launcher's directory holds a file gbrain did not write. Thelauncher refuses to start gbrain there (the hook exits 1 with one stderrline) 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 except+`gbrain post-upgrade` rewrites a stale launcher file in place (no entry or+trust changes), and moves every user-scope hook it can find except`gbrain setup codex`'s, which only setup rewrites because the rewrite re-truststhem; post-upgrade prints that command instead. A project-scopeinstall is refreshed from its project directory. A setup hook you edited afterdiff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex 8a96d68eb9..52dcf94616 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -122,7 +122,9 @@ table with its `trusted_hash`, otherwise Codex lists it and silently skips it.`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`, startsgbrain from its own directory so the session directory's `bunfig.toml` and- `.env` never load; SECURITY.md)+ `.env` never load, and on a `bun install -g` install puts the Bun setup ran+ under first on PATH, so the Codex app starts gbrain without bun on its PATH;+ 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/stress/iteration-weights.json b/scripts/stress/iteration-weights.jsonindex 2adfa2352f..b958a28a16 100644--- a/scripts/stress/iteration-weights.json+++ b/scripts/stress/iteration-weights.json@@ -692,6 +692,7 @@"test/serve-sync-handoff.serial.test.ts": 4100,"test/setup-brain-first.test.ts": 62000,"test/setup-brain-layout.test.ts": 131300,+ "test/setup-codex-bare-path.test.ts": 90000,"test/setup-serves-several.test.ts": 134100,"test/setup.test.ts": 507300,"test/shared-content-freshness.test.ts": 6900,diff --git a/src/core/cli-preflight.ts b/src/core/cli-preflight.tsindex 2cbf7497ab..a8051ab36a 100644--- a/src/core/cli-preflight.ts+++ b/src/core/cli-preflight.ts@@ -371,7 +371,7 @@ function resolveRuntimePaths(execArgv: readonly string[], cwd: string): string[]* a compiled binary (execPath IS gbrain; the entry is a `/$bunfs/` virtual* path, `~BUN` on Windows).*/-function isScriptRuntime(): boolean {+export function isScriptRuntime(): boolean {const entry = process.argv[1];const bunfsEntry = entry !== undefined && (/^\/\$bunfs\//.test(entry) || /[\\/]~BUN[\\/]/.test(entry));const devRuntime = /[/\\](bun|node)(\.exe)?$/.test(process.execPath);diff --git a/src/core/setup/hook-launcher-refresh.ts b/src/core/setup/hook-launcher-refresh.tsindex 881d43242e..9061f08815 100644--- a/src/core/setup/hook-launcher-refresh.ts+++ b/src/core/setup/hook-launcher-refresh.ts@@ -13,7 +13,8 @@* the receipt, nothing else). Codex setup installs, and anything else, get* 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.+ * from the project directory. This install's launcher file itself is rewritten+ * when stale (no entry changes, so no Codex trust moves). Best-effort; never throws.*/import { readFileSync } from 'node:fs';import { configDir } from '../config.ts';@@ -23,7 +24,7 @@ import { join } from 'node:path';import { GBRAIN_HOOK_MARKER_KEY, GBRAIN_SETUP_MARKER_VALUE, claudeUserSettingsPath, codexHooksPath, type ClaudeHookEvent } from '../bootstrap/host-specs.ts';import { applyClaudeSetup, claudeSetupPaths, inspectClaudeSetup, readSetupReceipt, type ClaudeSetupPlan } from './claude-code.ts';import { codexSetupPaths, readCodexSetupReceipt } from './codex.ts';-import { hookLauncherInCommand, hookLauncherPath, hookLauncherState } from './hook-launcher.ts';+import { ensureHookLauncher, hookLauncherInCommand, hookLauncherPath, hookLauncherState } from './hook-launcher.ts';import { localSetupRecords } from './local-receipts.ts';import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';import { launcherLaneFindings, setupRerunArgv } from './launcher-lanes.ts';@@ -111,6 +112,12 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {/** 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> {+ // A launcher that predates the recorded Bun (GST-2784) is rewritten in place: every entry keeps its command, so Codex trust is untouched.+ try {+ const launcher = hookLauncherPath();+ const before = hookLauncherState(launcher);+ if (before.state === 'stale') { ensureHookLauncher(launcher); log(`Hook launcher: rewrote ${launcher} (${before.detail}).`); }+ } catch (e) { log(`Hook launcher: ${hookLauncherPath()} was not refreshed (${(e as Error).message}); run gbrain doctor --only harness_wiring.`); }try { refreshTurnRule(log); } catch (e) { log(`Hook launcher: the turn-rule hooks were not refreshed (${(e as Error).message}); run gbrain doctor --only harness_wiring.`); }try { await refreshSetup(log); } catch (e) { log(`Hook launcher: setup's hooks were not refreshed (${(e as Error).message}); run gbrain doctor --only harness_wiring.`); }// The other lanes are named, never rewritten here: bootstrap's writers run from the workspace, and their Codex entries move trust.diff --git a/src/core/setup/hook-launcher.ts b/src/core/setup/hook-launcher.tsindex f02cc9c1cb..4d2c239418 100644--- a/src/core/setup/hook-launcher.ts+++ b/src/core/setup/hook-launcher.ts@@ -17,11 +17,18 @@* 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().+ *+ * The script-mode gbrain starts with `#!/usr/bin/env bun`, and a harness may+ * start the launcher with a PATH that has no bun on it (the Codex desktop app,+ * a GUI launcher), so the launcher of a script-mode install puts the directory+ * of the Bun that wrote it first on PATH (GST-2784). A compiled gbrain needs no+ * Bun, and its launcher stays the plain one.*/import { randomBytes } from 'node:crypto';-import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';-import { dirname, join, win32 } from 'node:path';+import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { basename, dirname, isAbsolute, join, win32 } from 'node:path';import { configDir } from '../config.ts';+import { isScriptRuntime } from '../cli-preflight.ts';import { msysToNativePath } from '../path-confine.ts';export const HOOK_LAUNCHER_NAME = 'gbrain-hook';@@ -49,6 +56,36 @@ doneexec "$@"`;+const shellSingleQuote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;+const RUNTIME_LINE = /^PATH='((?:[^']|'\\'')*)':\$PATH$/m;++/** The launcher text: the plain one, or for a script-mode install the same with `runtimeDir` (a shell path) put first on PATH before gbrain starts. */+export function hookLauncherScript(runtimeDir: string | null): string {+ if (runtimeDir === null) return HOOK_LAUNCHER_SCRIPT;+ return HOOK_LAUNCHER_SCRIPT.replace('exec "$@"\n', () => `# gbrain runs under the Bun gbrain setup ran under, so a harness started without bun on PATH still starts it.+PATH=${shellSingleQuote(runtimeDir)}:$PATH+export PATH+exec "$@"+`);+}++const sameFile = (a: string, b: string) => { try { return realpathSync(a) === realpathSync(b); } catch { return false; } };++/**+ * The directory of the Bun this gbrain runs under, as a hook shell path; null for a compiled gbrain, which needs none.+ * The bun on PATH wins when it is this same Bun: execPath is the resolved file, which for Homebrew, mise or asdf sits in+ * a per-version directory that a Bun upgrade deletes, while the PATH entry survives it.+ */+export function launcherRuntimeDir(searchPath?: string): string | null {+ if (!isScriptRuntime() || typeof Bun === 'undefined') return null;+ const self = /^bun(\.exe)?$/i.test(basename(process.execPath)) ? process.execPath : null;+ const onPath = Bun.which('bun', searchPath === undefined ? undefined : { PATH: searchPath });+ const bun = onPath && isAbsolute(onPath) && (self === null || sameFile(onPath, self)) ? onPath : self;+ return bun ? hookShellPath(dirname(bun)) : null;+}++const bunIn = (dir: string) => join(msysToNativePath(dir), process.platform === 'win32' ? 'bun.exe' : 'bun');+/** 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);@@ -56,8 +93,12 @@ export function hookLauncherPath(home: string = configDir()): string {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 } {+/**+ * Files only. `foreign`: the launcher's directory holds something gbrain did not write, so the launcher refuses to run.+ * `runtimeDir`: the Bun directory this gbrain needs (null for a compiled gbrain); a launcher that names a Bun that is+ * gone, or none when one is needed, is stale.+ */+export function hookLauncherState(path: string, runtimeDir: string | null = launcherRuntimeDir()): { 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);@@ -65,8 +106,12 @@ export function hookLauncherState(path: string): { state: HookLauncherState; dettry {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` };+ const text = readFileSync(path, 'utf8');+ const recorded = RUNTIME_LINE.exec(text)?.[1]?.replace(/'\\''/g, "'") ?? null;+ if (text !== hookLauncherScript(recorded)) 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` };+ if (recorded !== null && !existsSync(bunIn(recorded))) return { state: 'stale', detail: `${path} starts gbrain with ${bunIn(recorded)}, which is no longer there, so a harness started without bun on PATH cannot start gbrain` };+ if (recorded === null && runtimeDir !== null) return { state: 'stale', detail: `${path} does not record where bun is, so a harness started without bun on PATH (the Codex app, a GUI launcher) cannot start gbrain` };} catch { return { state: 'missing', detail: `no hook launcher at ${path}` }; }return { state: 'current', detail: `hook launcher ${path}` };}@@ -74,19 +119,20 @@ export function hookLauncherState(path: string): { state: HookLauncherState; det/*** 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.+ * and a hook routed through that directory would refuse anyway. A script-mode+ * gbrain rewrites a launcher that records another Bun, so it starts under this one.*/-export function ensureHookLauncher(path: string = hookLauncherPath()): string {+export function ensureHookLauncher(path: string = hookLauncherPath(), runtimeDir: string | null = launcherRuntimeDir()): 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') return path;+ if (hookLauncherState(path, runtimeDir).state === 'current' && (runtimeDir === null || readFileSync(path, 'utf8') === hookLauncherScript(runtimeDir))) return path;// The temp file sits beside the directory, never in it: a hook running meanwhile would refuse to start next to it.const tmp = join(dirname(dir), `.${HOOK_LAUNCHER_DIR}.tmp-${randomBytes(6).toString('hex')}`);try {- writeFileSync(tmp, HOOK_LAUNCHER_SCRIPT, { mode: 0o700 });+ writeFileSync(tmp, hookLauncherScript(runtimeDir), { mode: 0o700 });chmodSync(tmp, 0o700);renameSync(tmp, path);} catch (e) {diff --git a/test/fixtures/goldens/skill-resolver/off-pin.json b/test/fixtures/goldens/skill-resolver/off-pin.jsonindex 3594e98cd9..b7ae4e8c4a 100644--- a/test/fixtures/goldens/skill-resolver/off-pin.json+++ b/test/fixtures/goldens/skill-resolver/off-pin.json@@ -11,7 +11,7 @@".codex/hooks.json": "sha256:85519b7b2cf4f84208fe47e59bf87224a793bcf303fda59f45d98e541f526eb1",".gbrain/agent-instructions.json": "sha256:4f541f2d3531804b89ca5e2fac1af49b4a77668938580dd0d07e245770866efd",".gbrain/agent-instructions.lock": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",- ".gbrain/hook-launcher/gbrain-hook": "sha256:a194491363199f9b91090e473c6931790b72daaf2ed28d3e23e9c85ef89eec10",+ ".gbrain/hook-launcher/gbrain-hook": "sha256:61f3fb46048ab5cb10986326b04f4ae5e1d84478c526519b9eefadcdce15a009",".gbrain/integrations/hooks/heartbeat.jsonl": "sha256:83625960782a0c6d354105f787839fad3f4883efb3a752fa90c2f7be1805e545"},"userPromptHooks": [diff --git a/test/helpers/skill-resolver-off-capture.ts b/test/helpers/skill-resolver-off-capture.tsindex afca800f9c..7dad0aa773 100644--- a/test/helpers/skill-resolver-off-capture.ts+++ b/test/helpers/skill-resolver-off-capture.ts@@ -10,9 +10,10 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSynimport { tmpdir } from 'node:os';import { join } from 'node:path';-/** Machine and clock parts: the temp root, the bun path, timestamps, durations, and Codex's trust hash (it hashes hooks.json, which is pinned itself). */+/** Machine and clock parts: the temp root, the bun path, the Bun directory the hook launcher records, timestamps, durations, and Codex's trust hash (it hashes hooks.json, which is pinned itself). */function normalize(text: string, root: string): string {return text.split(root).join('<ROOT>').split(process.execPath).join('<BUN>')+ .replace(/^PATH='(?:[^']|'\\'')*':\$PATH$/m, () => "PATH='<BUN_DIR>':$PATH").replace(/"(updated_at|ts)":\s*"[^"]*"/g, '"$1":"<TS>"').replace(/"duration_ms":\s*\d+/g, '"duration_ms":"<MS>"').replace(/trusted_hash = "sha256:[0-9a-f]+"/g, 'trusted_hash = "<HASH>"');diff --git a/test/setup-codex-bare-path.test.ts b/test/setup-codex-bare-path.test.tsnew file mode 100644index 0000000000..485b3ed9ea--- /dev/null+++ b/test/setup-codex-bare-path.test.ts@@ -0,0 +1,192 @@+/**+ * GST-2784: after `gbrain setup codex`, Codex starts gbrain serve through the+ * hook launcher with whatever PATH the Codex process has. The script-mode+ * install's gbrain is src/cli.ts, whose shebang is `#!/usr/bin/env bun`, so a+ * Codex started without bun on its PATH (the desktop app, a launcher) failed+ * with "/usr/bin/env: 'bun': No such file or directory" and showed no tools.+ * Every entry setup writes runs through the launcher, which now carries the+ * Bun that setup ran under; a compiled gbrain needs no Bun and gets none.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import { withEnv } from './helpers/with-env.ts';+import { readCodexTomlTable } from '../src/core/bootstrap/codex-toml.ts';+import { HOOK_LAUNCHER_SCRIPT, ensureHookLauncher, hookLauncherScript, hookLauncherState, launcherRuntimeDir } from '../src/core/setup/hook-launcher.ts';+import { hookLauncherProblem } from '../src/core/setup/turn-hook-check.ts';+import { launcherLaneFindings } from '../src/core/setup/launcher-lanes.ts';+import { refreshHookLaunchers } from '../src/core/setup/hook-launcher-refresh.ts';++const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');+const BARE_PATH = '/usr/bin:/bin';+const SPAWN_TIMEOUT_MS = 60_000;+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 in a bin directory that holds no bun, as `bun install -g` leaves it when bun itself lives elsewhere. */+function box() {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-bare-path-'));+ roots.push(root);+ const home = join(root, 'home');+ const bin = join(root, 'bun-global', 'bin');+ const session = join(root, 'session');+ for (const d of [home, bin, session]) mkdirSync(d, { recursive: true });+ symlinkSync(CLI, join(bin, 'gbrain'));+ const env = { HOME: home, GBRAIN_HOME: home, CODEX_HOME: join(home, '.codex'), CLAUDE_CONFIG_DIR: undefined, XDG_CONFIG_HOME: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, GBRAIN_HOOKS: undefined };+ return { root, home, gbrain: join(bin, 'gbrain'), session, env, launcher: join(home, '.gbrain', 'hook-launcher', 'gbrain-hook') };+}+type Box = ReturnType<typeof box>;++/** The environment a Codex desktop app hands a stdio server or hook: no bun anywhere on PATH. */+function bareEnv(b: Box): Record<string, string> {+ expect(Bun.which('bun', { PATH: BARE_PATH })).toBeNull();+ return { HOME: b.home, GBRAIN_HOME: b.home, PATH: BARE_PATH };+}++async function setupCodex(b: Box) {+ const r = await runCli(['setup', 'codex', '--json', '--gbrain-bin', b.gbrain], { env: b.env });+ expect(r.exitCode).toBe(0);+ return r;+}++/** Start the recorded MCP command from the session directory and send an initialize request; returns the first reply line. */+async function initializeRecordedServer(b: Box): Promise<{ reply: string; stderr: string }> {+ const entry = readCodexTomlTable(join(b.home, '.codex', 'config.toml'), ['mcp_servers', 'gbrain']) as { command: string; args: string[] };+ const proc = Bun.spawn([entry.command, ...entry.args], { cwd: b.session, env: bareEnv(b), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });+ proc.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'bare-path-test', version: '0' } } })}\n`);+ proc.stdin.flush();+ const reader = proc.stdout.getReader();+ let out = '';+ const deadline = Date.now() + SPAWN_TIMEOUT_MS;+ while (!out.includes('\n') && Date.now() < deadline) {+ const chunk = await Promise.race([reader.read(), Bun.sleep(deadline - Date.now()).then(() => null)]);+ if (!chunk || chunk.done) break;+ out += new TextDecoder().decode(chunk.value);+ }+ proc.kill();+ const stderr = await new Response(proc.stderr).text();+ return { reply: out.split('\n')[0] ?? '', stderr };+}++describe('gbrain setup codex: the recorded entries start gbrain without bun on PATH (GST-2784)', () => {+ test('the MCP server entry starts serve and answers initialize under a PATH with no bun', async () => {+ const b = box();+ await setupCodex(b);+ const { reply, stderr } = await initializeRecordedServer(b);+ expect(stderr).not.toContain('No such file or directory');+ expect(JSON.parse(reply)).toMatchObject({ jsonrpc: '2.0', id: 1, result: { serverInfo: expect.any(Object) } });+ }, 120_000);++ test('the hooks setup writes run under a PATH with no bun', async () => {+ const b = box();+ await setupCodex(b);+ const hooks = JSON.parse(readFileSync(join(b.home, '.codex', 'hooks.json'), 'utf8')).hooks as Record<string, Array<{ hooks: Array<{ command: string }> }>>;+ const commands = Object.values(hooks).flat().flatMap((g) => g.hooks.map((h) => h.command)).filter((c) => c.includes(b.launcher) && !c.includes('nohup'));+ expect(commands.length).toBeGreaterThan(0);+ for (const command of commands) {+ const r = Bun.spawnSync(['sh', '-c', command], { cwd: b.session, env: bareEnv(b), stdin: Buffer.from(JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt: 'hi', session_id: 'bare-path', cwd: b.session })), stdout: 'pipe', stderr: 'pipe', timeout: SPAWN_TIMEOUT_MS });+ expect(r.stderr.toString()).not.toContain('No such file or directory');+ expect(r.exitCode).toBe(0);+ }+ }, 120_000);++ test('doctor reports a launcher that does not carry the runtime, and rerunning setup codex repairs it', async () => {+ const b = box();+ await setupCodex(b);+ writeFileSync(b.launcher, HOOK_LAUNCHER_SCRIPT);+ chmodSync(b.launcher, 0o700);+ await withEnv(b.env, async () => {+ expect(hookLauncherState(b.launcher)).toMatchObject({ state: 'stale', detail: expect.stringContaining('bun') });+ expect(hookLauncherProblem('codex')).toMatchObject({ reason: 'stale' });+ expect(launcherLaneFindings().filter((f) => f.harness === 'codex' && f.lane === 'mcp')).toMatchObject([{ reason: 'stale', rerun: expect.arrayContaining(['setup', 'codex']) }]);+ });+ await setupCodex(b);+ await withEnv(b.env, async () => {+ expect(hookLauncherState(b.launcher).state).toBe('current');+ expect(hookLauncherProblem('codex')).toBeNull();+ expect(launcherLaneFindings().filter((f) => f.harness === 'codex')).toEqual([]);+ });+ expect(JSON.parse((await initializeRecordedServer(b)).reply)).toMatchObject({ id: 1, result: expect.any(Object) });+ }, 180_000);++ test('post-upgrade rewrites a launcher that does not carry the runtime, without touching config.toml or hooks.json', async () => {+ const b = box();+ await setupCodex(b);+ const files = [join(b.home, '.codex', 'config.toml'), join(b.home, '.codex', 'hooks.json')];+ const before = files.map((f) => readFileSync(f, 'utf8'));+ writeFileSync(b.launcher, HOOK_LAUNCHER_SCRIPT);+ const lines: string[] = [];+ await withEnv(b.env, async () => {+ await refreshHookLaunchers((l) => lines.push(l));+ expect(hookLauncherState(b.launcher).state).toBe('current');+ expect(hookLauncherProblem('codex')).toBeNull();+ });+ expect(lines.join('\n')).toContain(`rewrote ${b.launcher}`);+ expect(files.map((f) => readFileSync(f, 'utf8'))).toEqual(before);+ expect(JSON.parse((await initializeRecordedServer(b)).reply)).toMatchObject({ id: 1, result: expect.any(Object) });+ }, 180_000);+});++describe('the launcher carries the runtime setup ran under, and only when gbrain needs one', () => {+ test('a Bun in a non-default directory is the one the launcher puts first on PATH', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-launcher-runtime-'));+ roots.push(root);+ const bunDir = join(root, 'opt', "o'dd bun", 'bin');+ mkdirSync(bunDir, { recursive: true });+ symlinkSync(process.execPath, join(bunDir, 'bun'));+ const launcher = join(root, 'home', 'hook-launcher', 'gbrain-hook');+ ensureHookLauncher(launcher, bunDir);+ expect(readFileSync(launcher, 'utf8')).toBe(hookLauncherScript(bunDir));+ expect(hookLauncherState(launcher, bunDir).state).toBe('current');+ const r = Bun.spawnSync([launcher, 'sh', '-c', 'command -v bun'], { cwd: root, env: { PATH: BARE_PATH }, stdout: 'pipe', stderr: 'pipe' });+ expect(r.stdout.toString().trim()).toBe(join(bunDir, 'bun'));+ rmSync(join(bunDir, 'bun'));+ expect(hookLauncherState(launcher, bunDir)).toMatchObject({ state: 'stale', detail: expect.stringContaining(join(bunDir, 'bun')) });+ });++ test('the bun on PATH is recorded when it is this same Bun, so a per-version install directory a Bun upgrade deletes is not', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-launcher-onpath-'));+ roots.push(root);+ const stable = join(root, 'stable', 'bin');+ const other = join(root, 'other', 'bin');+ mkdirSync(stable, { recursive: true });+ mkdirSync(other, { recursive: true });+ symlinkSync(process.execPath, join(stable, 'bun'));+ writeFileSync(join(other, 'bun'), '#!/bin/sh\n');+ chmodSync(join(other, 'bun'), 0o755);+ expect(launcherRuntimeDir(`${stable}:${BARE_PATH}`)).toBe(stable);+ expect(launcherRuntimeDir(`${other}:${BARE_PATH}`)).toBe(resolve(process.execPath, '..'));+ });++ test('setup moves a launcher that records another Bun onto the one it runs under', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-launcher-switch-'));+ roots.push(root);+ const [a, b] = ['a', 'b'].map((n) => join(root, n, 'bin'));+ for (const d of [a!, b!]) { mkdirSync(d, { recursive: true }); symlinkSync(process.execPath, join(d, 'bun')); }+ const launcher = join(root, 'home', 'hook-launcher', 'gbrain-hook');+ ensureHookLauncher(launcher, a!);+ expect(hookLauncherState(launcher, b!).state).toBe('current');+ ensureHookLauncher(launcher, b!);+ expect(readFileSync(launcher, 'utf8')).toBe(hookLauncherScript(b!));+ ensureHookLauncher(launcher, null);+ expect(readFileSync(launcher, 'utf8')).toBe(hookLauncherScript(b!));+ });++ test('a compiled gbrain (no runtime) keeps the launcher it had, which needs no bun', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-launcher-compiled-'));+ roots.push(root);+ const launcher = join(root, 'home', 'hook-launcher', 'gbrain-hook');+ ensureHookLauncher(launcher, null);+ expect(readFileSync(launcher, 'utf8')).toBe(HOOK_LAUNCHER_SCRIPT);+ expect(hookLauncherScript(null)).toBe(HOOK_LAUNCHER_SCRIPT);+ expect(hookLauncherState(launcher, null).state).toBe('current');+ const fake = join(root, 'gbrain');+ writeFileSync(fake, '#!/bin/sh\necho compiled-ok\n');+ chmodSync(fake, 0o755);+ const r = Bun.spawnSync([launcher, fake], { cwd: root, env: { PATH: BARE_PATH }, stdout: 'pipe' });+ expect(r.stdout.toString().trim()).toBe('compiled-ok');+ expect(existsSync(launcher)).toBe(true);+ });+});