Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(security): review round 1 for #8426/#8428, plus #8435 (opencode) and #8436 (docs)

garrytan2b9961e966d7
diff --git a/.agents/gbrain-launcher b/.agents/gbrain-launcher
index 711ee51ba1..d75ad101a1 100755
--- a/.agents/gbrain-launcher
+++ b/.agents/gbrain-launcher
@@ -23,16 +23,16 @@
# launcher's directory with the session directory in GBRAIN_HOOK_CWD, and on a miss it exits 0
# with no output, so a plugin-first install without the CLI shows no hook
# error on every turn. With GBRAIN_HOOK_LANE=plugin it also exits 0 silently
-# when the binary predates the plugin lane (PLUGIN_LANE_MIN): such a CLI
-# ignores the lane and would fire the rule a second time next to setup's own
-# hook. The version probe runs once per binary: its verdict is cached under
+# when the binary predates the plugin lane or GBRAIN_HOOK_CWD (PLUGIN_LANE_MIN):
+# such a CLI ignores the lane, or reads this directory as the session's, and
+# would fire the rule a second time next to setup's own hook. The version probe runs once per binary: its verdict is cached under
# <GBRAIN_HOME or HOME>/.gbrain/cache/plugin-hook-cli, keyed by the resolved
# path and valid while the cache is newer than the binary (`test -nt`, a
# shell builtin), so a cached turn starts no extra process.
set -eu
-PLUGIN_LANE_MIN=0.60.498.0
+PLUGIN_LANE_MIN=0.60.547.0
HOOK=0
[ "${1:-}" = "hook" ] && HOOK=1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 23e5ab7a46..f73020d12e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,13 +12,13 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased]
-**Security: the stdio MCP server and the remaining hook lanes no longer let the session directory's bunfig.toml or .env run, and the hook's git probes no longer run a checkout's core.fsmonitor (#8426, #8428, #8427).** Claude Code and Codex start user-scope stdio MCP servers in the session's directory, just as they run hooks there, so with a script-mode install the `gbrain serve` entry `gbrain setup` and `gbrain bootstrap hooks` registered ran a cloned repository's `bunfig.toml` preload once per session, with nothing to approve. Those entries now start serve through the same `<gbrain config dir>/hook-launcher/gbrain-hook` the setup hooks use, and `gbrain serve` reads `.gbrain-source` and the upload root from the session directory the launcher records, without changing its own directory.
+**Security: the stdio MCP server and the remaining hook lanes no longer let the session directory's bunfig.toml or .env run, and the hook's git probes no longer run a checkout's core.fsmonitor (#8426, #8428, #8427, #8435, #8436).** Claude Code, Codex and opencode start user-scope stdio MCP servers in the session's directory, just as they run hooks there, so with a script-mode install the `gbrain serve` entry `gbrain setup` and `gbrain bootstrap hooks` registered ran a cloned repository's `bunfig.toml` preload once per session, with nothing to approve. The user-global opencode entry `gbrain bootstrap hooks --harness opencode` writes did the same. Those entries now start serve through the same `<gbrain config dir>/hook-launcher/gbrain-hook` the setup hooks use, and `gbrain serve` reads `.gbrain-source`, a mounted brain's persistence socket, relative `file_upload` paths and the upload root from the session directory the launcher records, without changing its own directory.
-- The hooks from `gbrain bootstrap hooks` (the workspace lane), `gbrain bootstrap harness` and the Codex `SessionEnd` capture both write now start gbrain through the launcher too, and the gbrain plugins' per-turn hook changes into the plugin directory before it starts gbrain.
-- `gbrain post-upgrade` moves a user-scope `gbrain setup claude-code` MCP entry setup still owns onto the launcher, checking it again under setup's lock. It rewrites no Codex entry: for `gbrain setup codex`'s MCP table it prints the `gbrain setup codex` command, and for every `gbrain bootstrap` entry the bootstrap command that rewrites it, run from the workspace. An entry you edited after setup wrote it is kept and named.
-- `gbrain doctor` (`harness_wiring`, `hook_session_cwd`) now also covers the stdio MCP entries and the bootstrap, harness and Codex capture lanes, with the command that fixes each; only a user-scope entry setup owns gets an agent-runnable fix.
+- The hooks from `gbrain bootstrap hooks` (the workspace lane), `gbrain bootstrap harness` and the Codex `SessionEnd` capture both write now start gbrain through the launcher too, and the gbrain plugins' per-turn hook changes into the plugin directory before it starts gbrain. The plugin hook now needs gbrain 0.60.547.0 or newer (it exits silently on an older CLI, which would read the plugin directory as the session's).
+- `gbrain post-upgrade` moves a user-scope `gbrain setup claude-code` MCP entry setup still owns onto the launcher, checking it again under setup's lock. It rewrites no Codex entry, the turn-rule hook included (a rewrite recomputes the trust of every install's groups in the shared hooks.json): for `gbrain setup codex`'s MCP table and hooks it prints the `gbrain setup codex` command, and for every `gbrain bootstrap` entry the bootstrap command that rewrites it, run from the workspace. An entry you edited after setup wrote it is kept and named, and the refresh stops when another install replaced the receipt it planned from.
+- `gbrain doctor` (`harness_wiring`, `hook_session_cwd`) now also covers the stdio MCP entries and the bootstrap, harness and Codex capture lanes, with the command that fixes each; only a user-scope entry setup owns gets an agent-runnable fix, and it carries the install's recorded `--no-hooks` and `--source`, so the rerun turns nothing on.
- `gbrain hook`'s git probes run with `-c core.fsmonitor=false`, and a session outside the workspace the install receipt names runs no git at all, so a `.git/config` from an extracted archive or shared folder cannot run a command at session start.
-- The readiness fix for an unwired Claude Code or Codex now names `gbrain setup <harness> --no-hooks --no-instructions` instead of `claude mcp add` / `codex mcp add`, so the entry it writes goes through the launcher. A project-scope `.mcp.json` and committed `.claude/settings.json` hooks stay PATH-resolved: they belong to the repository.
+- The readiness fix for an unwired Claude Code or Codex now names `gbrain setup <harness> --no-hooks` instead of `claude mcp add` / `codex mcp add`, so the entry it writes goes through the launcher; it also writes the brain-first block and records hooks as off. The install docs now teach `gbrain setup claude-code` / `gbrain setup codex` instead of a bare stdio `mcp add`. A project-scope `.mcp.json` and committed `.claude/settings.json` hooks stay PATH-resolved: they belong to the repository.
## [0.60.547.0] - 2026-11-02
diff --git a/README.md b/README.md
index ea203209d9..7068f21b77 100644
--- a/README.md
+++ b/README.md
@@ -165,7 +165,7 @@ The repo is not a complete backup; see the [bootstrap guide](docs/guides/bootstr
### Connect GBrain to your AI client (MCP)
-- **Local stdio client:** `claude mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs` (lists the memory verbs; `--surface full` lists every tool); Codex, Cursor, Windsurf and other stdio clients take the same command. Then run `gbrain setup <harness> --instructions-only`: agents seldom call a brain nobody told them about.
+- **Local stdio client:** `gbrain setup claude-code` or `gbrain setup codex` registers `gbrain serve` (lists the memory verbs; `--surface full` lists every tool) behind gbrain's launcher, so a session opened in a cloned repository never loads that repository's `bunfig.toml` or `.env`, and adds the brain-first instructions: agents seldom call a brain nobody told them about. Cursor, Windsurf and other stdio clients take `"$(command -v gbrain)" serve --surface starter --advertise verbs`.
- **Plugins with curated skills:** Codex `codex plugin marketplace add garrytan/gbrain@codex-plugin` + `codex plugin add gbrain@gbrain`; Claude Code `/plugin marketplace add garrytan/gbrain` + `/plugin install gbrain@gbrain`.
- **This brain from anywhere:** `gbrain mcp expose` publishes it on your Tailscale tailnet as a user service (`--funnel` for cloud agents such as Grok Bot, Muse and ChatGPT). [Guide](docs/guides/remote-mcp.md).
- **A brain on another host:** `gbrain connect https://your-host/mcp --token gbrain_xxx --install` (add `--agent codex` for Codex). Hosted brains use [native OAuth or a private handoff](docs/guides/hosted-harness-access.md); dashboard, clients and permissions live in [MCP administration](docs/mcp/ADMIN.md).
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 9cced5ec42..825cafe941 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -130,11 +130,11 @@ gbrain autopilot --install # background daemon for nightly enrichment
**Wire this same local brain into your coding agent** — zero server, zero token:
```bash
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs # Claude Code
-codex mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs # Codex
+gbrain setup claude-code # Claude Code
+gbrain setup codex # Codex
```
-The agent spawns `gbrain serve` as a stdio subprocess against your local brain. `--surface starter --advertise verbs` is what every registration gbrain writes: the daily-driver set (40 ops) stays callable, and the tool list shows the seven memory verbs ([MEMORY_VERBS v1](protocol/MEMORY_VERBS_v1.md)) plus `request_tools`, which lists the other tools, returns any tool's full schema and reaches a left-out one. Drop `--advertise verbs` to list the whole starter set, or register `--surface full` (every operation) or `--surface verbs` (only the seven verbs, nothing else callable). Full walkthrough (both this local path and connecting to a remote brain), plus the brain-first protocol to paste into `CLAUDE.md` / `AGENTS.md`: **[Give your coding agent a memory](tutorials/connect-coding-agent.md)**.
+The agent spawns `gbrain serve` as a stdio subprocess against your local brain. Setup registers it behind gbrain's launcher (`<gbrain config dir>/hook-launcher/gbrain-hook`), because both harnesses start a stdio server in the session's directory and a script-mode Bun install would otherwise load that directory's `bunfig.toml` and `.env`; `--no-hooks` registers the server without hooks. `--surface starter --advertise verbs` is what every registration gbrain writes: the daily-driver set (40 ops) stays callable, and the tool list shows the seven memory verbs ([MEMORY_VERBS v1](protocol/MEMORY_VERBS_v1.md)) plus `request_tools`, which lists the other tools, returns any tool's full schema and reaches a left-out one. Drop `--advertise verbs` to list the whole starter set, or register `--surface full` (every operation) or `--surface verbs` (only the seven verbs, nothing else callable). Full walkthrough (both this local path and connecting to a remote brain), plus the brain-first protocol to paste into `CLAUDE.md` / `AGENTS.md`: **[Give your coding agent a memory](tutorials/connect-coding-agent.md)**.
## 3. MCP server (any MCP client)
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index 7390a73810..6f04e3daab 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -602,10 +602,12 @@ that inserted it. Everything else stays `unrecorded`; nothing is inferred.
## Read-only stdio serve
**Say to your agent:** *"Connect this agent to my brain read-only."* The agent
-registers `gbrain serve --access read-only` as its stdio MCP command.
+registers `gbrain serve --access read-only` as its stdio MCP command, through
+gbrain's launcher (any `gbrain setup` run writes it), so the session
+directory's `bunfig.toml` and `.env` never load.
```bash
-claude mcp add gbrain -- "$(command -v gbrain)" serve --access read-only
+claude mcp add gbrain-ro -- "${GBRAIN_HOME:-$HOME}/.gbrain/hook-launcher/gbrain-hook" "$(command -v gbrain)" serve --access read-only
gbrain serve --access read-only # bare serve: the full surface, read-only
```
diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.md
index 1898696b27..b4ac3a0a14 100644
--- a/docs/mcp/CLAUDE_CODE.md
+++ b/docs/mcp/CLAUDE_CODE.md
@@ -80,12 +80,16 @@ without output, so each turn gets it once. `GBRAIN_HOOKS=0`, or a recorded `gbra
## Option 1: Local (recommended, zero server needed)
```bash
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs
-gbrain setup claude-code --instructions-only
+gbrain setup claude-code
```
-(`gbrain setup claude-code` alone does both, plus hooks and a smoke test.)
-The second line adds the [brain-first instructions](#brain-first-instructions).
+Setup registers `gbrain serve --surface starter --advertise verbs`, adds the
+[brain-first instructions](#brain-first-instructions) and hooks, and runs a
+smoke test; `--no-hooks` skips the hooks. The MCP entry starts serve through
+gbrain's launcher (`<gbrain config dir>/hook-launcher/gbrain-hook`): Claude
+Code starts a stdio server in the session's directory, where a script-mode Bun
+install would load that directory's `bunfig.toml` and `.env`. Don't register
+`gbrain serve` with a bare `claude mcp add` for that reason.
Claude Code spawns `gbrain serve` as a stdio subprocess. No server, no
tunnel, no token needed. Works with both PGLite and Supabase engines.
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index 2e1383e69a..bbc8494f2b 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -266,7 +266,9 @@ codex mcp remove gbrain
- The token is a long-lived, full-access secret. Keep `GBRAIN_REMOTE_TOKEN` out of
version control and prefer a scoped token if your host supports one.
- Local stdio also works if you run the brain on the same machine:
- `codex mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs`, the
+ `gbrain setup codex` registers `serve --surface starter --advertise verbs` behind
+ gbrain's launcher, so the session directory's `bunfig.toml` and `.env` never load
+ (`gbrain serve` registered with a bare `codex mcp add` loads them). That is the
daily-driver tool list every new registration gbrain writes pins (`request_tools`
reaches the rest; `--surface full` is the opt-in for every operation). A
`GBRAIN_SURFACE` value in the Codex server entry's `env` table overrides the flag.
diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.md
index 4894ad3bd7..b584c9b938 100644
--- a/docs/protocol/AGENT_OPERATOR_v1.md
+++ b/docs/protocol/AGENT_OPERATOR_v1.md
@@ -1215,8 +1215,10 @@ Relay the bundle's one `user_message` ("Reply 'defaults' to accept …"); apply
each answer with the decision's `argv`. Then:
1. Register gbrain with the harness using the `harness_wiring` fix. The
- registration always uses the absolute gbrain path and `--surface starter`
- (for example `claude mcp add gbrain -- /abs/path/gbrain serve --surface starter`;
+ registration always uses the absolute gbrain path and `--surface starter`,
+ started through gbrain's launcher (for example `gbrain setup claude-code
+ --no-hooks --gbrain-bin /abs/path/gbrain`, which registers
+ `<config dir>/hook-launcher/gbrain-hook /abs/path/gbrain serve --surface starter`;
`gbrain init --surface <verbs|starter|full>` changes the surface it prints).
2. Run `gbrain doctor --only harness_wiring --json`, a read-only smoke check:
it reads the registration, then either finds the registered server already
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index c6d5ec078b..12a9c9ebc6 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -49,7 +49,7 @@ the same registry.
```bash
gbrain init --pglite # 2-second local brain
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs # lists the verbs; the daily-driver tools stay callable
+gbrain setup claude-code # registers serve behind gbrain's launcher; lists the verbs, the daily-driver tools stay callable
gbrain remember "gbrain install check" --provenance install-check
gbrain recall --query "gbrain install check" # …now ask your agent in a NEW session
```
@@ -64,7 +64,7 @@ If `claude` is not found: install Claude Code first, or use a block below.
**Codex**
```bash
-codex mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs
+gbrain setup codex
```
**Grok Build** (verify with `grok mcp doctor gbrain` — the add is lazy)
diff --git a/docs/tutorials/connect-coding-agent.md b/docs/tutorials/connect-coding-agent.md
index 363147c7c4..9cb2f32e21 100644
--- a/docs/tutorials/connect-coding-agent.md
+++ b/docs/tutorials/connect-coding-agent.md
@@ -83,15 +83,17 @@ Configure the agent you are using:
```bash
# Claude Code
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs
+gbrain setup claude-code
# Codex
-codex mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs
+gbrain setup codex
```
-These launch a local stdio MCP process. Use the same intended brain and source
+These register a local stdio MCP process that starts through gbrain's
+launcher, so a session opened in a cloned repository never loads its
+`bunfig.toml` or `.env` (pass `--no-hooks` to skip setup's hooks). Use the same intended brain and source
you inspected above; if an isolated installation already provided an absolute
-launcher, use that command in place of the bare `gbrain`.
+launcher, pass it as `--gbrain-bin <that launcher>`.
The full surface serves every operation, including the seven memory verbs
(`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`,
diff --git a/llms-full.txt b/llms-full.txt
index a25983f8cd..653fd6bba9 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -4762,8 +4762,10 @@ Relay the bundle's one `user_message` ("Reply 'defaults' to accept …"); apply
each answer with the decision's `argv`. Then:
1. Register gbrain with the harness using the `harness_wiring` fix. The
- registration always uses the absolute gbrain path and `--surface starter`
- (for example `claude mcp add gbrain -- /abs/path/gbrain serve --surface starter`;
+ registration always uses the absolute gbrain path and `--surface starter`,
+ started through gbrain's launcher (for example `gbrain setup claude-code
+ --no-hooks --gbrain-bin /abs/path/gbrain`, which registers
+ `<config dir>/hook-launcher/gbrain-hook /abs/path/gbrain serve --surface starter`;
`gbrain init --surface <verbs|starter|full>` changes the surface it prints).
2. Run `gbrain doctor --only harness_wiring --json`, a read-only smoke check:
it reads the registration, then either finds the registered server already
@@ -5193,7 +5195,7 @@ The repo is not a complete backup; see the [bootstrap guide](docs/guides/bootstr
### Connect GBrain to your AI client (MCP)
-- **Local stdio client:** `claude mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs` (lists the memory verbs; `--surface full` lists every tool); Codex, Cursor, Windsurf and other stdio clients take the same command. Then run `gbrain setup <harness> --instructions-only`: agents seldom call a brain nobody told them about.
+- **Local stdio client:** `gbrain setup claude-code` or `gbrain setup codex` registers `gbrain serve` (lists the memory verbs; `--surface full` lists every tool) behind gbrain's launcher, so a session opened in a cloned repository never loads that repository's `bunfig.toml` or `.env`, and adds the brain-first instructions: agents seldom call a brain nobody told them about. Cursor, Windsurf and other stdio clients take `"$(command -v gbrain)" serve --surface starter --advertise verbs`.
- **Plugins with curated skills:** Codex `codex plugin marketplace add garrytan/gbrain@codex-plugin` + `codex plugin add gbrain@gbrain`; Claude Code `/plugin marketplace add garrytan/gbrain` + `/plugin install gbrain@gbrain`.
- **This brain from anywhere:** `gbrain mcp expose` publishes it on your Tailscale tailnet as a user service (`--funnel` for cloud agents such as Grok Bot, Muse and ChatGPT). [Guide](docs/guides/remote-mcp.md).
- **A brain on another host:** `gbrain connect https://your-host/mcp --token gbrain_xxx --install` (add `--agent codex` for Codex). Hosted brains use [native OAuth or a private handoff](docs/guides/hosted-harness-access.md); dashboard, clients and permissions live in [MCP administration](docs/mcp/ADMIN.md).
@@ -8419,7 +8421,7 @@ the same registry.
```bash
gbrain init --pglite # 2-second local brain
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs # lists the verbs; the daily-driver tools stay callable
+gbrain setup claude-code # registers serve behind gbrain's launcher; lists the verbs, the daily-driver tools stay callable
gbrain remember "gbrain install check" --provenance install-check
gbrain recall --query "gbrain install check" # …now ask your agent in a NEW session
```
@@ -8434,7 +8436,7 @@ If `claude` is not found: install Claude Code first, or use a block below.
**Codex**
```bash
-codex mcp add gbrain -- "$(command -v gbrain)" serve --surface starter --advertise verbs
+gbrain setup codex
```
**Grok Build** (verify with `grok mcp doctor gbrain` — the add is lazy)
diff --git a/plugin-variants/gbrain-coding/.agents/gbrain-launcher b/plugin-variants/gbrain-coding/.agents/gbrain-launcher
index 711ee51ba1..d75ad101a1 100755
--- a/plugin-variants/gbrain-coding/.agents/gbrain-launcher
+++ b/plugin-variants/gbrain-coding/.agents/gbrain-launcher
@@ -23,16 +23,16 @@
# launcher's directory with the session directory in GBRAIN_HOOK_CWD, and on a miss it exits 0
# with no output, so a plugin-first install without the CLI shows no hook
# error on every turn. With GBRAIN_HOOK_LANE=plugin it also exits 0 silently
-# when the binary predates the plugin lane (PLUGIN_LANE_MIN): such a CLI
-# ignores the lane and would fire the rule a second time next to setup's own
-# hook. The version probe runs once per binary: its verdict is cached under
+# when the binary predates the plugin lane or GBRAIN_HOOK_CWD (PLUGIN_LANE_MIN):
+# such a CLI ignores the lane, or reads this directory as the session's, and
+# would fire the rule a second time next to setup's own hook. The version probe runs once per binary: its verdict is cached under
# <GBRAIN_HOME or HOME>/.gbrain/cache/plugin-hook-cli, keyed by the resolved
# path and valid while the cache is newer than the binary (`test -nt`, a
# shell builtin), so a cached turn starts no extra process.
set -eu
-PLUGIN_LANE_MIN=0.60.498.0
+PLUGIN_LANE_MIN=0.60.547.0
HOOK=0
[ "${1:-}" = "hook" ] && HOOK=1
diff --git a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
index 650011bb05..54caaebcb8 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
@@ -1217,8 +1217,10 @@ Relay the bundle's one `user_message` ("Reply 'defaults' to accept …"); apply
each answer with the decision's `argv`. Then:
1. Register gbrain with the harness using the `harness_wiring` fix. The
- registration always uses the absolute gbrain path and `--surface starter`
- (for example `claude mcp add gbrain -- /abs/path/gbrain serve --surface starter`;
+ registration always uses the absolute gbrain path and `--surface starter`,
+ started through gbrain's launcher (for example `gbrain setup claude-code
+ --no-hooks --gbrain-bin /abs/path/gbrain`, which registers
+ `<config dir>/hook-launcher/gbrain-hook /abs/path/gbrain serve --surface starter`;
`gbrain init --surface <verbs|starter|full>` changes the surface it prints).
2. Run `gbrain doctor --only harness_wiring --json`, a read-only smoke check:
it reads the registration, then either finds the registered server already
diff --git a/plugin-variants/gbrain-daily/.agents/gbrain-launcher b/plugin-variants/gbrain-daily/.agents/gbrain-launcher
index 711ee51ba1..d75ad101a1 100755
--- a/plugin-variants/gbrain-daily/.agents/gbrain-launcher
+++ b/plugin-variants/gbrain-daily/.agents/gbrain-launcher
@@ -23,16 +23,16 @@
# launcher's directory with the session directory in GBRAIN_HOOK_CWD, and on a miss it exits 0
# with no output, so a plugin-first install without the CLI shows no hook
# error on every turn. With GBRAIN_HOOK_LANE=plugin it also exits 0 silently
-# when the binary predates the plugin lane (PLUGIN_LANE_MIN): such a CLI
-# ignores the lane and would fire the rule a second time next to setup's own
-# hook. The version probe runs once per binary: its verdict is cached under
+# when the binary predates the plugin lane or GBRAIN_HOOK_CWD (PLUGIN_LANE_MIN):
+# such a CLI ignores the lane, or reads this directory as the session's, and
+# would fire the rule a second time next to setup's own hook. The version probe runs once per binary: its verdict is cached under
# <GBRAIN_HOME or HOME>/.gbrain/cache/plugin-hook-cli, keyed by the resolved
# path and valid while the cache is newer than the binary (`test -nt`, a
# shell builtin), so a cached turn starts no extra process.
set -eu
-PLUGIN_LANE_MIN=0.60.498.0
+PLUGIN_LANE_MIN=0.60.547.0
HOOK=0
[ "${1:-}" = "hook" ] && HOOK=1
diff --git a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
index 650011bb05..54caaebcb8 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
@@ -1217,8 +1217,10 @@ Relay the bundle's one `user_message` ("Reply 'defaults' to accept …"); apply
each answer with the decision's `argv`. Then:
1. Register gbrain with the harness using the `harness_wiring` fix. The
- registration always uses the absolute gbrain path and `--surface starter`
- (for example `claude mcp add gbrain -- /abs/path/gbrain serve --surface starter`;
+ registration always uses the absolute gbrain path and `--surface starter`,
+ started through gbrain's launcher (for example `gbrain setup claude-code
+ --no-hooks --gbrain-bin /abs/path/gbrain`, which registers
+ `<config dir>/hook-launcher/gbrain-hook /abs/path/gbrain serve --surface starter`;
`gbrain init --surface <verbs|starter|full>` changes the surface it prints).
2. Run `gbrain doctor --only harness_wiring --json`, a read-only smoke check:
it reads the registration, then either finds the registered server already
diff --git a/plugin/skills/conventions/agent-operator-protocol.md b/plugin/skills/conventions/agent-operator-protocol.md
index 650011bb05..54caaebcb8 100644
--- a/plugin/skills/conventions/agent-operator-protocol.md
+++ b/plugin/skills/conventions/agent-operator-protocol.md
@@ -1217,8 +1217,10 @@ Relay the bundle's one `user_message` ("Reply 'defaults' to accept …"); apply
each answer with the decision's `argv`. Then:
1. Register gbrain with the harness using the `harness_wiring` fix. The
- registration always uses the absolute gbrain path and `--surface starter`
- (for example `claude mcp add gbrain -- /abs/path/gbrain serve --surface starter`;
+ registration always uses the absolute gbrain path and `--surface starter`,
+ started through gbrain's launcher (for example `gbrain setup claude-code
+ --no-hooks --gbrain-bin /abs/path/gbrain`, which registers
+ `<config dir>/hook-launcher/gbrain-hook /abs/path/gbrain serve --surface starter`;
`gbrain init --surface <verbs|starter|full>` changes the surface it prints).
2. Run `gbrain doctor --only harness_wiring --json`, a read-only smoke check:
it reads the registration, then either finds the registered server already
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 3a5a4a7125..b76121fd97 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -6,8 +6,8 @@
# fewer. Raising a row or adding one needs an issue/TODO id in the justification.
# docs/TESTING.md#function-size-ratchet
path name lines justification
-src/commands/bootstrap.ts runHooks 601 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #4618: --seat/--no-seat parse + refusal/note (logic in core/bootstrap/hooks.ts parseSeatFlags); +1 #8426: the user-scope MCP registration writes the hook launcher before naming it (logic in core/setup/hook-launcher.ts)
-src/commands/bootstrap.ts runHooks>withLock(#1) 449 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/commands/bootstrap.ts runHooks 603 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #4618: --seat/--no-seat parse + refusal/note (logic in core/bootstrap/hooks.ts parseSeatFlags); +1 #8426: the user-scope MCP registration writes the hook launcher before naming it (logic in core/setup/hook-launcher.ts); +2 #8435: the user-global opencode entry starts serve through the hook launcher
+src/commands/bootstrap.ts runHooks>withLock(#1) 451 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #8435: the user-global opencode entry starts serve through the hook launcher (logic in core/setup/hook-launcher.ts)
src/commands/config.ts runConfig 782 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5232: persistence.write_wait_ms dispatch line (logic in setFileWriteWait); wave 10 collector: master and the #4907/#5958 config-set range refusals compose at 775; re-summed at the #6015 merge (767 master baseline + 4 integration lines); re-summed at the wave 10 merge on actual lines; +1 C4: dream.auto_think.* replacement note (logic in questions/auto-think-migration.ts); +5 wave 15 P7.4 #5461: set-time refusal of think.pages_budget_chars / think.excerpt_ceiling_chars (range text from think/pages-budget.ts pagesBudgetConfigError); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig)
src/commands/doctor/bootstrap-checks.ts bootstrapDoctorChecks 476 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/doctor/checks/extraction-sync.ts checkSyncFreshness 333 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 328a23da68..f8d5d7dc2d 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -28,7 +28,7 @@ src/core/minions/queue.ts 2547 ratchet grown #4078 + megawave probe-liveness unl
src/commands/init.ts 1892 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts); +1 GBRA-199: --surface help line names the default verbs listing; +7 GBRA-248 W0b: the implicit-keyless marker on both zero-key fallbacks, the deferred-hint gate on both engine paths and the kept-identity call in both (logic in commands/init-embedding-plane.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
-src/commands/bootstrap.ts 2151 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts); +4 #8426/#8428: the user-scope MCP registration, its verify and the workspace and Codex SessionEnd hooks start gbrain through the hook launcher (logic in core/setup/hook-launcher.ts)
+src/commands/bootstrap.ts 2153 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts); +4 #8426/#8428: the user-scope MCP registration, its verify and the workspace and Codex SessionEnd hooks start gbrain through the hook launcher (logic in core/setup/hook-launcher.ts); +2 #8435: the user-global opencode entry starts serve through the hook launcher (logic in core/setup/hook-launcher.ts)
src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)
src/commands/sources.ts 2100 ratchet +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured)
src/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 edges
diff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.md
index 650011bb05..54caaebcb8 100644
--- a/skills/conventions/agent-operator-protocol.md
+++ b/skills/conventions/agent-operator-protocol.md
@@ -1217,8 +1217,10 @@ Relay the bundle's one `user_message` ("Reply 'defaults' to accept …"); apply
each answer with the decision's `argv`. Then:
1. Register gbrain with the harness using the `harness_wiring` fix. The
- registration always uses the absolute gbrain path and `--surface starter`
- (for example `claude mcp add gbrain -- /abs/path/gbrain serve --surface starter`;
+ registration always uses the absolute gbrain path and `--surface starter`,
+ started through gbrain's launcher (for example `gbrain setup claude-code
+ --no-hooks --gbrain-bin /abs/path/gbrain`, which registers
+ `<config dir>/hook-launcher/gbrain-hook /abs/path/gbrain serve --surface starter`;
`gbrain init --surface <verbs|starter|full>` changes the surface it prints).
2. Run `gbrain doctor --only harness_wiring --json`, a read-only smoke check:
it reads the registration, then either finds the registered server already
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index e26dba920f..b8ab455c92 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -44,7 +44,7 @@
"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e",
"context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207",
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
- "conventions/agent-operator-protocol.md": "86ed21dfdd5e4b34cb7d5eb88532966c4e64a07d0401123421a9b33bd643c0a2",
+ "conventions/agent-operator-protocol.md": "e51683cbb4521378fbc96d8fc6ec14023cc69306d134426f876194efeae0ce9d",
"conventions/brain-first.md": "e0e4d7c4b760213325dffd286baf934720816a0b6aac5338538a0463e8fe77d2",
"conventions/brain-routing.md": "f11c3e7c4f98163aa6c68aa7d8f09a7acb7b6a8695f42eb7d92d4ee5787d428a",
"conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index 04ab13d4ce..92932d4974 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -1281,12 +1281,13 @@ async function runHooks(
if (harness === 'opencode') {
// Direct-writer lane (no exec): registrations land via the JSONC
// writer whose 4-state fingerprint is the [FIX7] check. Scope resolves
- // to a FILE here — user → global config (absolute binary path),
+ // to a FILE here — user → global config (hook launcher + absolute binary, #8435),
// project → committed-candidate opencode.json (PATH-resolved command;
// no absolute machine paths in a file that travels, and no fail-open
// analog exists — the sharing warning below is the mitigation).
const configPath = mcpScope === 'project' ? opencodeProjectConfigPath(ws) : opencodeGlobalConfigPath();
- const command = stdioServeArgv(mcpScope === 'project' ? 'gbrain' : gbrainBin, surfaceFlag ?? undefined, registrationAdvertise({ userChoseSurface: surfaceFlag !== null }));
+ const ocLauncher = mcpScope === 'project' ? [] : [hookLauncherPath(home)];
+ const command = [...ocLauncher, ...stdioServeArgv(mcpScope === 'project' ? 'gbrain' : gbrainBin, surfaceFlag ?? undefined, registrationAdvertise({ userChoseSurface: surfaceFlag !== null }))];
const entry = {
kind: 'local' as const,
name: 'gbrain',
@@ -1317,7 +1318,8 @@ async function runHooks(
const existingKind = opencodeEntryKind(existing, 'gbrain', { sourceId });
const priorCommand = ((existing.mcp as Record<string, { command?: unknown }> | undefined)?.gbrain)?.command;
const prior = existingKind !== 'absent' && !surfaceFlag && Array.isArray(priorCommand) ? registeredSurface(priorCommand.join(' ')) : undefined;
- if (prior !== undefined) entry.command = stdioServeArgv(command[0], prior, registeredAdvertise((priorCommand as unknown[]).join(' ')));
+ if (prior !== undefined) entry.command = [...ocLauncher, ...stdioServeArgv(command[ocLauncher.length]!, prior, registeredAdvertise((priorCommand as unknown[]).join(' ')))];
+ if (ocLauncher.length) ensureHookLauncher(ocLauncher[0]!);
if (existingKind === 'ours-other-source') {
console.error(`existing 'gbrain' opencode entry targets a DIFFERENT workspace — replacing it.`);
}
diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.ts
index a22fa27d96..9d934d0474 100644
--- a/src/commands/doctor/checks/harness-wiring.ts
+++ b/src/commands/doctor/checks/harness-wiring.ts
@@ -44,7 +44,9 @@ import type { DoctorContext, DoctorEntry } from '../context.ts';
import { VERSION } from '../../../version.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 { launcherLaneFindings } from '../../../core/setup/launcher-lanes.ts';
+import { launcherLaneFindings, setupRerunArgv } from '../../../core/setup/launcher-lanes.ts';
+import { readSetupReceipt } from '../../../core/setup/claude-code.ts';
+import { readCodexSetupReceipt } from '../../../core/setup/codex.ts';
import { brainFirstTarget, inspectBrainFirst, isBrainFirstHarness, readBrainFirstLedger, renderBrainFirstBlock, type BrainFirstAccess } from '../../../core/setup/brain-first.ts';
export const HARNESS_SMOKE_TIMEOUT_MS = 15_000;
@@ -521,17 +523,20 @@ export function hookLauncherProblems(views: InstructionBlockView[]): HookLaunche
/** 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 setupHarness = p.lane === 'setup' && p.harness !== 'opencode' ? p.harness : null;
+ const record = setupHarness ? localSetupRecords().find((r) => r.harness === setupHarness && r.status === 'installed' && (project ? r.projectDir === project : r.scope !== 'project')) : undefined;
+ const receipt = record && (() => { try { return (setupHarness === 'claude-code' ? readSetupReceipt(record.path) : readCodexSetupReceipt(record.path)).setup; } catch { return null; } })();
+ const argv = receipt && setupHarness ? setupRerunArgv(setupHarness, receipt, project ?? undefined)
+ : ['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, except `gbrain setup codex`'s.";
const verify = doctorVerify(NAME);
if (p.rerun) {
const run = `${p.rerunFrom ? `from ${p.rerunFrom}, ` : ''}run: ${p.rerun.join(' ')}`;
- const laneWhy = "Rewrites the entry to start gbrain from its own launcher directory, so a repository's bunfig.toml or .env never runs when a session or MCP server starts there.";
+ const laneWhy = `Rewrites the entry to start gbrain from its own launcher directory, so a repository's bunfig.toml or .env never runs when a session or MCP server starts there.${p.harness === 'codex' && p.rerun[1] === 'setup' ? " gbrain setup codex repeats the install's recorded decisions and re-trusts setup's own hook groups." : ''}`;
if (p.reason === 'foreign') return { consent: [], actor: 'user', requires_exclusive: false, verify, why: laneWhy, user_message: `${p.detail}. Remove that file (gbrain did not write it), then ${run}` };
if (p.edited) return { consent: [], actor: 'user', requires_exclusive: false, verify, why: laneWhy, user_message: `${p.detail}. Remove or rewrite that entry in ${p.source} (setup never overwrites an edit), then ${run}` };
if (p.setupOwned) return { argv: p.rerun, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify, why: laneWhy };
- return { consent: [], actor: 'user', requires_exclusive: false, verify, why: laneWhy, user_message: `${p.detail}. To move it onto gbrain's launcher, ${p.lane === 'mcp' && p.rerun[1] === 'setup' ? `remove that entry from ${p.source} (gbrain setup never overwrites an MCP entry it did not write), then ` : ''}${run}` };
+ return { consent: [], actor: 'user', requires_exclusive: false, verify, why: laneWhy, user_message: `${p.detail}. To move it onto gbrain's launcher, ${p.lane === 'mcp' && p.owner === 'none' ? `remove that entry from ${p.source} (gbrain never overwrites an MCP entry it did not write), then ` : ''}${run}` };
}
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 (p.edited) return { consent: [], actor: 'user', requires_exclusive: false, verify, why, user_message: `${p.detail}. Remove or rewrite that entry in ${p.source} (setup never overwrites an edit), then ${project ? `from ${project}, ` : ''}run: ${argv.join(' ')}` };
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 9626147070..29201740fa 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1409,7 +1409,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #8424 (GBRA-277) hook launcher. since stamped at the merge slot.
{ since: '0.60.547.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, except `gbrain setup codex`\'s, which the next `gbrain setup codex` rewrites, and doctor `harness_wiring` warns with `hook_session_cwd` on any that still start gbrain in the session directory.' },
// #8426, #8428, #8427 (GBRA-279) MCP and lane launcher, hook git fsmonitor. since stamped at the merge slot.
- { since: '0.60.549.0', id: 'mcp_lane_launcher_8426', text: 'The stdio MCP entry `gbrain setup claude-code|codex` and `gbrain bootstrap hooks` register now starts `gbrain serve` through `<gbrain config dir>/hook-launcher/gbrain-hook`, and the hooks from `gbrain bootstrap hooks`, `gbrain bootstrap harness`, the Codex SessionEnd capture and the gbrain plugins start gbrain from the launcher\'s or the plugin\'s own directory, so a session opened in a cloned repository never runs that repository\'s bunfig.toml preload or loads its .env; serve still reads .gbrain-source from the session directory. `gbrain post-upgrade` moves a Claude Code setup MCP entry setup still owns and names the command for every Codex and bootstrap entry, doctor `hook_session_cwd` covers them, and `gbrain hook` git probes skip core.fsmonitor and run only in the workspace the install receipt names.' },
+ { since: '0.60.549.0', id: 'mcp_lane_launcher_8426', text: 'The stdio MCP entry `gbrain setup claude-code|codex` and `gbrain bootstrap hooks` (opencode\'s user-global entry included) register now starts `gbrain serve` through `<gbrain config dir>/hook-launcher/gbrain-hook`, and the hooks from `gbrain bootstrap hooks`, `gbrain bootstrap harness`, the Codex SessionEnd capture and the gbrain plugins start gbrain from the launcher\'s or the plugin\'s own directory, so a session opened in a cloned repository never runs that repository\'s bunfig.toml preload or loads its .env; serve still reads .gbrain-source from the session directory. `gbrain post-upgrade` moves a Claude Code setup MCP entry setup still owns and names the command for every Codex (the turn-rule hook included) and bootstrap entry, doctor `hook_session_cwd` covers them, and `gbrain hook` git probes skip core.fsmonitor and run only in the workspace the install receipt names.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/bootstrap/opencode-json.ts b/src/core/bootstrap/opencode-json.ts
index e9a9b07763..8e06482c9c 100644
--- a/src/core/bootstrap/opencode-json.ts
+++ b/src/core/bootstrap/opencode-json.ts
@@ -45,6 +45,7 @@
*/
import { randomBytes } from 'node:crypto';
+import { isHookLauncherPath } from '../setup/hook-launcher.ts';
import { chmodSync, copyFileSync, existsSync, readFileSync } from 'node:fs';
import { applyEdits, modify, parse as parseJsonc, printParseErrorCode, type ParseError } from 'jsonc-parser';
import { atomicWriteTextFile } from './atomic-write.ts';
@@ -164,6 +165,7 @@ function isGbrainShapedCommand(command: unknown): boolean {
if (!Array.isArray(command) || command.length === 0) return false;
const head = command[0];
if (typeof head !== 'string') return false;
+ if (isHookLauncherPath(head)) return isGbrainShapedCommand(command.slice(1)); // user scope through the hook launcher (#8435)
if (head === 'gbrain') return true; // PATH-resolved (project scope)
if (/[\\/]gbrain$/.test(head)) return true; // absolute binary path
// bun-run wrapper shim lane: `bun run <...>/gbrain/src/cli.ts` etc. The
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 3ac3a0bcf5..970c63eefd 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -42,7 +42,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
'compile-context': ['--brain', '--budget', '--check', '--error-unmatch', '--git-path', '--help', '--include', '--include-core', '--json', '--out', '--remove-core', '--revision', '--show-toplevel', '--source', '--stdout', '--target'],
- 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--apply', '--as', '--background', '--brain', '--budget-ms', '--call-site', '--confirm-quiesced', '--coverage-override', '--dataset', '--db-url', '--diff-filter', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--exclude', '--expected-state', '--explain', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-hidden', '--include-withdrawals', '--input', '--items-out', '--json', '--limit', '--markdown', '--min', '--name-only', '--no-accept-pending', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-extract', '--no-hard-deadline', '--no-hooks', '--no-llm', '--no-pull', '--no-renames', '--no-schema-pack', '--only', '--out', '--path', '--pattern', '--phase', '--probe', '--progress-interval', '--progress-json', '--provider', '--publish', '--query', '--quiet', '--raw', '--recommended', '--remediate', '--remediation-plan', '--remove', '--repo', '--revision', '--session', '--shadow', '--since', '--slot', '--source', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--suite', '--surface', '--target', '--threshold', '--tier', '--timeout', '--timings', '--to', '--url', '--wait', '--what-if-threshold', '--working-tree', '--yes'],
+ 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--apply', '--as', '--background', '--brain', '--budget-ms', '--call-site', '--confirm-quiesced', '--coverage-override', '--dataset', '--db-url', '--diff-filter', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--exclude', '--expected-state', '--explain', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--gbrain-bin', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-hidden', '--include-withdrawals', '--input', '--items-out', '--json', '--limit', '--markdown', '--min', '--name-only', '--no-accept-pending', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-extract', '--no-hard-deadline', '--no-hooks', '--no-llm', '--no-pull', '--no-renames', '--no-schema-pack', '--only', '--out', '--path', '--pattern', '--phase', '--probe', '--progress-interval', '--progress-json', '--provider', '--publish', '--query', '--quiet', '--raw', '--recommended', '--remediate', '--remediation-plan', '--remove', '--repo', '--revision', '--session', '--shadow', '--since', '--slot', '--source', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--suite', '--surface', '--target', '--threshold', '--tier', '--timeout', '--timings', '--to', '--url', '--wait', '--what-if-threshold', '--working-tree', '--yes'],
'connect': ['--advertise', '--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--gbrain-bin', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-instructions', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--only', '--public-url', '--pure', '--register', '--remove', '--root', '--runtime', '--scope', '--scopes', '--show-token', '--source', '--source-ids', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--workspace', '--yes'],
'connectors': ['--accept-pending', '--all', '--as', '--background', '--brain', '--cookie', '--deadline', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--max-requests', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--token', '--try-oauth', '--wait', '--window-days', '--workers', '--yes'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
@@ -51,11 +51,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
- 'embed': ['--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--section', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--timings', '--to', '--wait', '--yes'],
+ 'embed': ['--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--gbrain-bin', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--section', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--timings', '--to', '--wait', '--yes'],
'embeddings': ['--accept-pending', '--as', '--background', '--brain', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--wait', '--yes'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--legacy-lock', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--timings', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
diff --git a/src/core/ops/files.ts b/src/core/ops/files.ts
index dd819dd041..7d8bdb0c14 100644
--- a/src/core/ops/files.ts
+++ b/src/core/ops/files.ts
@@ -70,10 +70,11 @@ const file_upload: Operation = {
if (ctx.dryRun) return { dry_run: true, action: 'file_upload', path: p.path };
const { statSync } = await import('fs');
- const { basename, extname } = await import('path');
+ const { basename, extname, resolve } = await import('path');
const { hashStorageFile, uploadUnchangedFile } = await import('../storage.ts');
- const filePath = p.path as string;
+ // A relative path means the session directory a launcher-started serve records, the same root it is confined to (#8426).
+ const filePath = resolve(hookSessionCwd(), p.path as string);
const pageSlug = (p.page_slug as string) || null;
// Fix 1 / B5 / H5 / M4: validate path, slug, filename before any filesystem read.
diff --git a/src/core/persistence/local-client.ts b/src/core/persistence/local-client.ts
index 35b39af5f6..03cf6dbc35 100644
--- a/src/core/persistence/local-client.ts
+++ b/src/core/persistence/local-client.ts
@@ -1,5 +1,6 @@
/** Engine-free CLI routing to the process that already owns a PGLite brain. */
import { randomUUID } from 'node:crypto';
+import { hookSessionCwd } from '../session-cwd.ts';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { configDir, type GBrainConfig } from '../config.ts';
@@ -50,7 +51,7 @@ export function persistenceConfigForBrain(
* path), so a mounted serve binds the owner socket the CLI probes (#5237).
* Host-level settings stay; only the datastore identity follows the mount.
*/
-export function residentPersistenceConfig(hostConfig: GBrainConfig | null, cwd = process.cwd()): GBrainConfig | null {
+export function residentPersistenceConfig(hostConfig: GBrainConfig | null, cwd = hookSessionCwd()): GBrainConfig | null {
const brainId = resolveBrainId(getCliOptions().brain, cwd);
if (brainId === 'host') return hostConfig;
const brain = persistenceConfigForBrain(hostConfig, brainId, loadMounts())!;
diff --git a/src/core/readiness.ts b/src/core/readiness.ts
index 0578472c2d..9926f0294a 100644
--- a/src/core/readiness.ts
+++ b/src/core/readiness.ts
@@ -415,11 +415,12 @@ const SURFACE_GLOSS: Record<McpSurface, string> = {
function stdioRegistration(h: ReadinessHarness, bin: string, chosen?: McpSurface): Action {
const surface = chosen ?? REGISTRATION_SURFACE;
const advertise = registrationAdvertise({ userChoseSurface: chosen !== undefined });
- // Claude Code and Codex start stdio servers in the session's directory, so setup registers serve behind its launcher (#8426).
- const serve = h === 'opencode' ? stdioServeArgv(bin, surface, advertise) : [hookLauncherPath(), ...stdioServeArgv(bin, surface, advertise)];
+ // Each harness starts a user-scope stdio server in the session's directory, so its writer registers serve behind gbrain's launcher (#8426, #8435).
+ const serve = [hookLauncherPath(), ...stdioServeArgv(bin, surface, advertise)];
const argv = h === 'opencode' ? ['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks', ...(chosen ? ['--surface', chosen] : [])]
- : ['gbrain', 'setup', h, '--no-hooks', '--no-instructions', '--gbrain-bin', bin, ...(chosen ? ['--surface', chosen] : [])];
- const hooks = h === 'opencode' ? ' No lifecycle hooks are installed (--no-hooks); it must run inside an initialized agent workspace.' : ' No hooks, instruction blocks, tool pre-approvals or tokens are added.';
+ : ['gbrain', 'setup', h, '--no-hooks', '--gbrain-bin', bin, ...(chosen ? ['--surface', chosen] : [])];
+ const hooks = h === 'opencode' ? ' No lifecycle hooks are installed (--no-hooks); it must run inside an initialized agent workspace.'
+ : ' It also writes gbrain\'s brain-first instruction block, and records hooks as off (--no-hooks), so gbrain\'s per-turn hooks (setup\'s and the plugin\'s) stay off until setup runs again without it. No tool pre-approvals or tokens are added.';
return {
argv, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false,
why: `Registers gbrain as a stdio MCP server (${serve.join(' ')}, ${advertise ? `listing ${SURFACE_GLOSS[advertise]} and request_tools; ${SURFACE_GLOSS[surface]} stays callable` : SURFACE_GLOSS[surface]}) in ${HARNESS_DESTINATION[h]}, so new ${HARNESS_LABEL[h]} sessions get memory tools.${hooks}`,
diff --git a/src/core/setup/claude-code.ts b/src/core/setup/claude-code.ts
index 4a9678d702..6dfd094a79 100644
--- a/src/core/setup/claude-code.ts
+++ b/src/core/setup/claude-code.ts
@@ -271,7 +271,7 @@ export interface ApplyResult { steps: SetupStep[]; receipt: ClaudeSetupReceipt;
export async function applyClaudeSetup(
plan: ClaudeSetupPlan,
consent: SetupConsent,
- opts: { pluginOwner: string | null; brainCreated: boolean; beforeMcp?: () => Promise<void>; abortAfter?: string; mcpMustBeSetups?: boolean },
+ opts: { pluginOwner: string | null; brainCreated: boolean; beforeMcp?: () => Promise<void>; abortAfter?: string; refreshOf?: ClaudeSetupReceipt },
): Promise<ApplyResult> {
const paths = claudeSetupPaths(plan);
const lock = await acquireBootstrapLock(dirname(paths.configPath));
@@ -279,8 +279,9 @@ export async function applyClaudeSetup(
// The MCP entry and every hook command start gbrain through the launcher, so it goes down before anything names it (#8424, #8426).
ensureHookLauncher(hookLauncherPath(plan.brainHome));
const found = inspectClaudeSetup(plan);
- // post-upgrade's refresh: the MCP entry moves only while it is still setup's, read again under the lock (#8426).
- if (opts.mcpMustBeSetups && opts.pluginOwner === null && found.mcp.state !== 'current' && found.mcp.state !== 'owned') throw new Error(`the '${plan.name}' MCP entry changed before setup's entries were rewritten`);
+ // post-upgrade's refresh: it rewrites only the install it planned from, and the MCP entry only while it is still setup's, both read again under the lock (#8426).
+ if (opts.refreshOf && JSON.stringify(found.prior) !== JSON.stringify(opts.refreshOf)) throw new Error(`the '${plan.name}' setup receipt changed before setup's entries were rewritten`);
+ if (opts.refreshOf && opts.pluginOwner === null && found.mcp.state !== 'current' && found.mcp.state !== 'owned') throw new Error(`the '${plan.name}' MCP entry changed before setup's entries were rewritten`);
const now = new Date().toISOString();
const desired = desiredMcpEntry(plan);
const desiredHash = entryHash(desired);
diff --git a/src/core/setup/hook-launcher-refresh.ts b/src/core/setup/hook-launcher-refresh.ts
index 21b21e287d..9a92e6a700 100644
--- a/src/core/setup/hook-launcher-refresh.ts
+++ b/src/core/setup/hook-launcher-refresh.ts
@@ -18,12 +18,12 @@
import { readFileSync } from 'node:fs';
import { configDir } from '../config.ts';
import { hookEntryHash, parseClaudeHookCommand } from '../bootstrap/hooks.ts';
-import { codexHookCensus, codexHookGroupRuns, type CodexHookCensusGroup } from '../bootstrap/codex-hooks.ts';
+import { codexHookCensus } from '../bootstrap/codex-hooks.ts';
import { join } from 'node:path';
-import { GBRAIN_HOOK_MARKER_KEY, GBRAIN_SETUP_MARKER_VALUE, claudeUserSettingsPath, codexConfigPath, codexHooksPath, type ClaudeHookEvent } from '../bootstrap/host-specs.ts';
+import { 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, shellWords } from './hook-launcher.ts';
+import { hookLauncherInCommand, hookLauncherPath, hookLauncherState } from './hook-launcher.ts';
import { localSetupRecords } from './local-receipts.ts';
import { launcherLaneFindings } from './launcher-lanes.ts';
import { hasTurnRuleHook, isTurnRuleEntry, syncTurnRuleHook, TURN_RULE_LANE_TOKEN } from './turn-hook.ts';
@@ -43,19 +43,6 @@ function claudeHookEntries(path: string): Array<Record<string, unknown>> {
.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 = shellWords(command) ?? [];
- 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;
-}
-
/** The launcher of the install the hook's GBRAIN_HOME names, so a hook never depends on another install's directory. */
const launcherFor = (gbrainHome: string | undefined) => (gbrainHome ? { hookLauncher: hookLauncherPath(join(gbrainHome, '.gbrain')) } : {});
@@ -67,15 +54,10 @@ function refreshTurnRule(log: (line: string) => void): void {
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 group: CodexHookCensusGroup | undefined;
- try { group = codexHookCensus(codexHooksPath()).find((g) => g.lane === 'turn-rule' && g.commands.some((c) => c.includes(TURN_RULE_LANE_TOKEN) && needsLauncher(c))); } catch { return; }
- if (!group) return;
- // Rewriting re-trusts the group, so only a group Codex already runs moves: an untrusted or disabled one keeps Codex's approval gate.
- if (!codexHookGroupRuns(codexHooksPath(), codexConfigPath(), group)) { log('Hook launcher: Codex does not run the codex turn-rule hook (not trusted, or disabled), so it is left as is; run `gbrain setup codex --instructions-only` to rewrite it.'); return; }
- const parts = codexCommandParts(group.commands.find((c) => c.includes(TURN_RULE_LANE_TOKEN))!);
- if (!parts) { log('Hook launcher: the codex turn-rule hook could not be read, so it is left as is; run `gbrain setup codex --instructions-only` to rewrite it.'); return; }
- const o = syncTurnRuleHook({ harness: 'codex', gbrainBin: parts.gbrainBin, gbrainHome: parts.gbrainHome, paths: launcherFor(parts.gbrainHome), rerun: 'gbrain setup codex --instructions-only' });
- log(`Hook launcher: codex turn-rule hook ${o.action === 'write' ? 'now starts gbrain from its own directory' : `left as is (${o.detail}${o.next ? `; run ${o.next}` : ''})`}.`);
+ let stale = false;
+ try { stale = codexHookCensus(codexHooksPath()).some((g) => g.lane === 'turn-rule' && g.commands.some((c) => c.includes(TURN_RULE_LANE_TOKEN) && needsLauncher(c))); } catch { return; }
+ // Every install shares one hooks.json and a rewrite recomputes every turn-rule group's trust, so the codex hook is only named here.
+ if (stale) log('Hook launcher: the codex turn-rule hook starts gbrain in the session\'s directory, so it is left as is (a rewrite moves Codex trust); run `gbrain setup codex --instructions-only` to rewrite it.');
}
async function refreshSetup(log: (line: string) => void): Promise<void> {
@@ -97,7 +79,7 @@ async function refreshSetup(log: (line: string) => void): Promise<void> {
if (!ours.some(needsLauncher) && mcp !== 'owned') continue;
if (receipt.scope === 'project') { log(`Hook launcher: gbrain setup's entries for ${receipt.project_dir} start gbrain in the session's directory; from ${receipt.project_dir}, run ${rerun} --scope project.`); continue; }
if (mcp !== 'plugin' && mcp !== 'current' && mcp !== 'owned') { log(`Hook launcher: gbrain's claude-code hooks start gbrain in the session's directory; run ${rerun} to rewrite them.`); continue; }
- const applied = await applyClaudeSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false, mcpMustBeSetups: true });
+ const applied = await applyClaudeSetup(plan, receipt.consent, { pluginOwner: receipt.mcp_plugin ?? null, brainCreated: false, refreshOf: receipt });
const left = new Set(claudeHookEntries(paths.settingsPath).filter((e) => needsLauncher(e.command as string)).map((e) => hookEntryHash(e) ?? ''));
const kept = Object.entries(applied.edited).filter(([, hash]) => left.has(hash)).map(([event]) => event);
log(kept.length > 0
@@ -125,7 +107,7 @@ export async function refreshHookLaunchers(log: (line: string) => void = console
try { await refreshSetup(log); } catch (e) { log(`Hook launcher: setup's hooks were not refreshed (${(e as Error).message}); run gbrain doctor --only harness_wiring.`); }
// The other lanes are named, never rewritten here: bootstrap's writers run from the workspace, and their Codex entries move trust.
try {
- for (const f of launcherLaneFindings().filter((x) => x.owner !== 'setup')) log(`Hook launcher: ${f.detail}; ${f.edited ? 'it was edited after setup wrote it, so it is kept as is; remove or rewrite it, then ' : f.owner === 'none' ? 'gbrain setup did not write it, so remove it, then ' : ''}${f.rerunFrom ? `from ${f.rerunFrom}, ` : ''}run ${f.rerun.join(' ')} to move it onto gbrain's launcher.`);
+ for (const f of launcherLaneFindings().filter((x) => x.owner !== 'setup')) log(`Hook launcher: ${f.detail}; ${f.edited ? 'it was edited after setup wrote it, so it is kept as is; remove or rewrite it, then ' : f.owner === 'none' ? 'gbrain did not write it, so remove it, then ' : ''}${f.rerunFrom ? `from ${f.rerunFrom}, ` : ''}run ${f.rerun.join(' ')} to move it onto gbrain's launcher.`);
} catch (e) { log(`Hook launcher: the bootstrap lanes were not checked (${(e as Error).message}); run gbrain doctor --only harness_wiring.`); }
}
diff --git a/src/core/setup/launcher-lanes.ts b/src/core/setup/launcher-lanes.ts
index 6b4bb79ba3..0b8fe70ead 100644
--- a/src/core/setup/launcher-lanes.ts
+++ b/src/core/setup/launcher-lanes.ts
@@ -13,18 +13,19 @@ import { classifyHarnessHook } from '../bootstrap/hooks.ts';
import { codexHookCensus } from '../bootstrap/codex-hooks.ts';
import { readCodexTomlTable } from '../bootstrap/codex-toml.ts';
import { readReceipt } from '../bootstrap/format.ts';
-import { CLAUDE_SETTINGS_FILE_RELPATH, GBRAIN_HOOK_MARKER_KEY, GBRAIN_HOOK_MARKER_VALUE, claudeUserMcpConfigPath, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';
+import { CLAUDE_SETTINGS_FILE_RELPATH, GBRAIN_HOOK_MARKER_KEY, GBRAIN_HOOK_MARKER_VALUE, claudeUserMcpConfigPath, claudeUserSettingsPath, codexConfigPath, codexHooksPath, opencodeConfigDir } from '../bootstrap/host-specs.ts';
+import { parseOpencodeConfig } from '../bootstrap/opencode-json.ts';
import { resolveGbrainHome } from '../gbrain-home.ts';
import { hookLauncherInCommand, hookLauncherState, isHookLauncherPath, type HookLauncherState } from './hook-launcher.ts';
import { localSetupRecords } from './local-receipts.ts';
import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';
-import { readSetupReceipt } from './claude-code.ts';
+import { readSetupReceipt, type ClaudeSetupReceipt } from './claude-code.ts';
import { readCodexSetupReceipt } from './codex.ts';
export type LauncherLane = 'mcp' | 'harness' | 'bootstrap';
export interface LauncherLaneFinding {
- harness: 'claude-code' | 'codex';
+ harness: 'claude-code' | 'codex' | 'opencode';
lane: LauncherLane;
/** The config, settings or hooks file holding the entry. */
source: string;
@@ -68,17 +69,32 @@ function state(launcher: string | null): { reason: LauncherLaneFinding['reason']
return s.state === 'current' ? null : { reason: s.state, why: `runs through ${launcher}, but ${s.detail}` };
}
+/**
+ * The `gbrain setup` command that rewrites an install's entries with what its receipt records. Setup keeps the recorded
+ * capture and providers decisions on its own; a hooks opt-out and a source pin only come from flags, so the rerun carries them.
+ */
+export function setupRerunArgv(harness: 'claude-code' | 'codex', receipt: Pick<ClaudeSetupReceipt, 'name' | 'consent' | 'source_id'>, projectDir?: string): string[] {
+ return ['gbrain', 'setup', harness, ...(receipt.name === 'gbrain' ? [] : ['--name', receipt.name]), ...(projectDir ? ['--scope', 'project'] : []),
+ ...(receipt.consent.wiring_scope.value.hooks === 'none' ? ['--no-hooks'] : []), ...(receipt.source_id ? ['--source', receipt.source_id] : [])];
+}
+
function mcpFindings(): LauncherLaneFinding[] {
const out: LauncherLaneFinding[] = [];
const setup = localSetupRecords().filter((r) => r.status === 'installed');
const bootstrap = (() => { try { return readReceipt(resolveGbrainHome()); } catch { return null; } })();
+ // bootstrap writes a user-scope entry only for a 'user' registration (Claude Code's default writes .mcp.json instead); its rerun keeps a --no-hooks install hook-free.
+ const bootstrapRerun = (harness: 'claude-code' | 'codex' | 'opencode'): Pick<LauncherLaneFinding, 'rerun' | 'rerunFrom' | 'setupOwned' | 'owner'> | null => {
+ const reg = bootstrap?.registrations.find((r) => r.host === harness && r.scope === 'user' && (r.detail?.split('+') ?? []).includes('mcp'));
+ return reg ? { rerun: ['gbrain', 'bootstrap', 'hooks', '--harness', harness, ...(reg.detail!.split('+').includes('hooks') ? [] : ['--no-hooks']), '--repair'], rerunFrom: bootstrap!.workspace_dir, setupOwned: false, owner: 'bootstrap' } : null;
+ };
const rerunFor = (harness: 'claude-code' | 'codex', name: string, entry: unknown, projectDir?: string): Pick<LauncherLaneFinding, 'rerun' | 'rerunFrom' | 'setupOwned' | 'owner' | 'edited'> => {
const record = setup.find((r) => r.harness === harness && r.name === name && (projectDir ? r.projectDir === projectDir : r.scope !== 'project'));
// Setup owns the entry only while it is still what setup wrote; an edited one stays the user's, and setup refuses to overwrite it.
const receipt = record && (() => { try { return (harness === 'claude-code' ? readSetupReceipt(record.path) : readCodexSetupReceipt(record.path)).setup; } catch { return null; } })();
const owner = receipt && [receipt.entry_hash, receipt.pending_entry_hash].includes(ownedEntryFingerprint(entry as Record<string, unknown>)) ? record : undefined;
- if (owner) return { rerun: ['gbrain', 'setup', harness, ...(name === 'gbrain' ? [] : ['--name', name]), ...(projectDir ? ['--scope', 'project'] : [])], ...(projectDir ? { rerunFrom: projectDir } : {}), setupOwned: !projectDir, owner: 'setup' };
- if (bootstrap?.registrations.some((r) => r.host === harness && (r.detail?.split('+') ?? []).includes('mcp'))) return { rerun: ['gbrain', 'bootstrap', 'hooks', '--harness', harness, '--repair'], rerunFrom: bootstrap.workspace_dir, setupOwned: false, owner: 'bootstrap' };
+ if (owner && receipt) return { rerun: setupRerunArgv(harness, receipt, projectDir), ...(projectDir ? { rerunFrom: projectDir } : {}), setupOwned: !projectDir, owner: 'setup' };
+ const boot = projectDir || name !== 'gbrain' ? null : bootstrapRerun(harness);
+ if (boot) return boot;
return { rerun: ['gbrain', 'setup', harness, ...(name === 'gbrain' ? [] : ['--name', name]), ...(projectDir ? ['--scope', 'project'] : [])], ...(projectDir ? { rerunFrom: projectDir } : {}), setupOwned: false, owner: 'none', ...(record ? { edited: true } : {}) };
};
const names = [...new Set(['gbrain', ...setup.map((r) => r.name)])];
@@ -104,6 +120,17 @@ function mcpFindings(): LauncherLaneFinding[] {
if (!s) continue;
out.push({ harness: 'codex', lane: 'mcp', source: codexPath, reason: s.reason, ...rerunFor('codex', name, table), detail: `[mcp_servers.${name}] in ${codexPath} ${s.why}` });
}
+ // opencode merges both user-global filenames, and starts a local server in each directory it opens (#8435).
+ for (const file of ['opencode.jsonc', 'opencode.json'].map((f) => join(opencodeConfigDir(), f))) {
+ let entry: Record<string, unknown> | null;
+ try { entry = existsSync(file) ? record(record(parseOpencodeConfig(readFileSync(file, 'utf8'), file).mcp)?.gbrain) : null; } catch { continue; }
+ const argv = entry?.type === 'local' && Array.isArray(entry.command) ? entry.command.filter((a): a is string => typeof a === 'string') : [];
+ const serve = argv.length > 0 ? serveEntryLauncher({ command: argv[0], args: argv.slice(1) }) : null;
+ const s = serve && state(serve.launcher);
+ if (!s) continue;
+ out.push({ harness: 'opencode', lane: 'mcp', source: file, reason: s.reason, ...(bootstrapRerun('opencode') ?? { rerun: ['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--repair'], setupOwned: false, owner: 'none' }),
+ detail: `the 'gbrain' MCP server in ${file} ${s.why}` });
+ }
return out;
}
diff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.ts
index b71bacb8f3..c5f5c37a25 100644
--- a/src/core/setup/turn-hook-check.ts
+++ b/src/core/setup/turn-hook-check.ts
@@ -123,7 +123,7 @@ export function inspectTurnHook(harness: string, opts: { projectDir?: string } =
* gbrain did not write.
*/
export interface HookLauncherProblem {
- harness: 'claude-code' | 'codex';
+ harness: 'claude-code' | 'codex' | 'opencode';
/** setup and turn-rule: hooks; mcp, harness and bootstrap: the other lanes (launcher-lanes.ts), which carry their own rerun. */
lane: 'setup' | 'turn-rule' | LauncherLane;
/** The settings or hooks file holding the entry. */
@@ -137,6 +137,7 @@ export interface HookLauncherProblem {
rerun?: string[];
rerunFrom?: string;
setupOwned?: boolean;
+ owner?: 'setup' | 'bootstrap' | 'none';
}
/** The hook hashes a harness's setup receipts own and the ones they record as edited by the user: Claude Code can drop the `_gbrain` marker on a rewrite, and setup owns its entries by hash. */
diff --git a/test/bootstrap-opencode-door.serial.test.ts b/test/bootstrap-opencode-door.serial.test.ts
index 21cb961a97..5489988e31 100644
--- a/test/bootstrap-opencode-door.serial.test.ts
+++ b/test/bootstrap-opencode-door.serial.test.ts
@@ -21,6 +21,7 @@
*
* Serial: mutates GBRAIN_HOME and XDG_CONFIG_HOME.
*/
+import { hookLauncherPath } from '../src/core/setup/hook-launcher.ts';
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -187,8 +188,9 @@ describe('opencode workspace lane — default scope is USER-GLOBAL', () => {
type: string; command: string[]; environment: Record<string, string>; enabled: boolean;
};
expect(entry.type).toBe('local');
- expect(entry.command[0]).toBe(FAKE_BIN); // user scope: absolute path
- expect(entry.command.slice(1)).toEqual(['serve', '--surface', 'starter', '--advertise', 'verbs']);
+ // user scope: gbrain's launcher, then the absolute path (#8435: opencode starts it in the session's directory)
+ expect(entry.command.slice(0, 2)).toEqual([hookLauncherPath(), FAKE_BIN]);
+ expect(entry.command.slice(2)).toEqual(['serve', '--surface', 'starter', '--advertise', 'verbs']);
expect(entry.environment.GBRAIN_SOURCE).toBeDefined();
expect(entry.enabled).toBe(true);
@@ -384,11 +386,14 @@ describe('opencode never-narrow: a rewritten entry keeps its surface form', () =
}
test('a pinned --surface stays pinned, a bare serve stays bare, an explicit --surface wins', async () => {
- expect(await rerunWith([FAKE_BIN, 'serve', '--surface', 'full'])).toEqual([FAKE_BIN, 'serve', '--surface', 'full']);
+ // A rewrite also moves the entry onto gbrain's launcher (#8435).
+ const L = hookLauncherPath();
+ expect(await rerunWith([FAKE_BIN, 'serve', '--surface', 'full'])).toEqual([L, FAKE_BIN, 'serve', '--surface', 'full']);
// S0: starter differs from the registration default (full), so keeping it is observable.
- expect(await rerunWith([FAKE_BIN, 'serve', '--surface', 'starter'])).toEqual([FAKE_BIN, 'serve', '--surface', 'starter']);
- expect(await rerunWith([FAKE_BIN, 'serve'])).toEqual([FAKE_BIN, 'serve']);
- expect(await rerunWith([FAKE_BIN, 'serve', '--surface', 'full'], ['--surface', 'verbs'])).toEqual([FAKE_BIN, 'serve', '--surface', 'verbs']);
+ expect(await rerunWith([FAKE_BIN, 'serve', '--surface', 'starter'])).toEqual([L, FAKE_BIN, 'serve', '--surface', 'starter']);
+ expect(await rerunWith([FAKE_BIN, 'serve'])).toEqual([L, FAKE_BIN, 'serve']);
+ expect(await rerunWith([FAKE_BIN, 'serve', '--surface', 'full'], ['--surface', 'verbs'])).toEqual([L, FAKE_BIN, 'serve', '--surface', 'verbs']);
+ expect(await rerunWith([L, FAKE_BIN, 'serve', '--surface', 'full'])).toEqual([L, FAKE_BIN, 'serve', '--surface', 'full']);
}, 60_000);
});
diff --git a/test/hook-launcher-bunfig.test.ts b/test/hook-launcher-bunfig.test.ts
index e15709118d..1379e607cd 100644
--- a/test/hook-launcher-bunfig.test.ts
+++ b/test/hook-launcher-bunfig.test.ts
@@ -205,7 +205,7 @@ describe('hooks written before the launcher: doctor flags them, post-upgrade mov
expect(existsSync(b.marker)).toBe(false);
});
- test('codex: an old turn-rule group is flagged, then refreshed with a matching trust entry', async () => {
+ test('codex: an old turn-rule group Codex runs is flagged and named, and post-upgrade leaves hooks.json and its trust alone', async () => {
const b = box();
const hooks = join(b.home, '.codex', 'hooks.json');
const config = join(b.home, '.codex', 'config.toml');
@@ -216,13 +216,13 @@ describe('hooks written before the launcher: doctor flags them, post-upgrade mov
appendCodexTomlTable(config, ['hooks', 'state', `${hooks}:user_prompt_submit:0:0`], { trusted_hash: codexHookTrustHash('user_prompt_submit', old.hooks[0]!.command, old.hooks[0]!.timeout) }, 'test: Codex trusted the old hook');
expect(codexHookGroupRuns(hooks, config, { event: 'UserPromptSubmit', index: 0 })).toBe(true);
expect(hookLauncherProblem('codex')).toMatchObject({ lane: 'turn-rule', reason: 'session_cwd' });
- await refreshHookLaunchers(() => {});
- expect(hookLauncherProblem('codex')).toBeNull();
+ const before = { hooks: readFileSync(hooks, 'utf8'), config: readFileSync(config, 'utf8') };
+ const lines: string[] = [];
+ await refreshHookLaunchers((l) => lines.push(l));
+ expect(lines.join('\n')).toContain('run `gbrain setup codex --instructions-only` to rewrite it');
+ expect({ hooks: readFileSync(hooks, 'utf8'), config: readFileSync(config, 'utf8') }).toEqual(before);
+ expect(hookLauncherProblem('codex')).toMatchObject({ lane: 'turn-rule', reason: 'session_cwd' });
});
- 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('codex: a turn-rule group Codex never trusted is left as is, so post-upgrade grants no trust', async () => {
@@ -237,7 +237,7 @@ describe('hooks written before the launcher: doctor flags them, post-upgrade mov
await withEnv(env(b), async () => {
const lines: string[] = [];
await refreshHookLaunchers((l) => lines.push(l));
- expect(lines.join('\n')).toContain('Codex does not run the codex turn-rule hook');
+ expect(lines.join('\n')).toContain('the codex turn-rule hook starts gbrain in the session\'s directory, so it is left as is');
});
expect(readJson(hooks)).toEqual({ hooks: { UserPromptSubmit: [group] } });
expect(codexHookGroupRuns(hooks, config, { event: 'UserPromptSubmit', index: 0 })).toBe(false);
diff --git a/test/launcher-lanes-bunfig.serial.test.ts b/test/launcher-lanes-bunfig.serial.test.ts
index f322e1c06c..a7a10c5c8d 100644
--- a/test/launcher-lanes-bunfig.serial.test.ts
+++ b/test/launcher-lanes-bunfig.serial.test.ts
@@ -79,6 +79,21 @@ async function serveFromSession(command: string, args: string[], entryEnv: Recor
const parsed = JSON.parse(text) as { source_id?: string };
if (!parsed.source_id) throw new Error(`put_page answered without a source: ${text}\n${stderr}`);
return parsed.source_id;
+ } catch (e) {
+ throw new Error(`${(e as Error).message}\nserve stderr: ${stderr}`);
+ } finally {
+ await client.close().catch(() => {});
+ }
+}
+
+/** Call one tool on a stdio MCP entry started from the session directory. */
+async function callFromSession(command: string, args: string[], entryEnv: Record<string, string>, tool: string, toolArgs: Record<string, unknown>): Promise<{ isError: boolean; text: string }> {
+ const transport = new StdioClientTransport({ command, args, env: { ...env, ...entryEnv }, cwd: hostile, stderr: 'pipe' });
+ const client = new Client({ name: 'launcher-lanes', version: '1' }, { capabilities: {} });
+ try {
+ await client.connect(transport);
+ const r = await client.callTool({ name: tool, arguments: toolArgs });
+ return { isError: r.isError === true, text: (r.content as Array<{ text: string }>)[0]!.text };
} finally {
await client.close().catch(() => {});
}
@@ -149,6 +164,17 @@ async function quiet<T>(fn: () => Promise<T>): Promise<{ result: T; err: string
try { return { result: await fn(), err }; } finally { console.log = log; console.error = error; }
}
+describe('#8426: serve reads relative paths from the session directory', () => {
+ test('file_upload of a relative path finds the file in the session directory, not the launcher directory', async () => {
+ writeFileSync(join(hostile, 'report.pdf'), '%PDF-1.4 example\n');
+ const entry = desiredMcpEntry({ name: 'gbrain', scope: 'user', launcher: gbrain, brainHome: join(home, '.gbrain'), gbrainHomeEnv: home, sourceId: null, surface: 'full', advertise: null, events: [] }) as { command: string; args: string[]; env: Record<string, string> };
+ const r = await callFromSession(entry.command, entry.args, entry.env, 'file_upload', { path: 'report.pdf' });
+ // The keyless test brain has no storage backend, so the upload stops after the path checks, naming the session file.
+ expect(JSON.parse(r.text)).toMatchObject({ code: 'storage_error' });
+ expect(r.text).toContain(join(hostile, 'report.pdf'));
+ }, 90_000);
+});
+
describe('#8426, #8428: gbrain bootstrap hooks registers serve and writes its hooks through the launcher', () => {
test('claude-code: the user-scope claude mcp add argv and the workspace hooks', async () => {
const ws = bootstrapWorkspace();
@@ -205,6 +231,27 @@ describe('#8426, #8428: gbrain bootstrap hooks registers serve and writes its ho
}
await withEnv(procEnv, async () => { expect(launcherLaneFindings().filter((f) => f.lane !== 'harness')).toEqual([]); });
}, 120_000);
+
+ test('opencode (#8435): doctor names a user-global entry that starts serve in the session directory, and bootstrap rewrites it through the launcher', async () => {
+ const ws = bootstrapWorkspace();
+ const config = join(home, '.config', 'opencode', 'opencode.jsonc');
+ mkdirSync(join(home, '.config', 'opencode'), { recursive: true });
+ writeFileSync(config, JSON.stringify({ mcp: { gbrain: { type: 'local', command: [gbrain, 'serve'], environment: { GBRAIN_SOURCE: 'source-b' }, enabled: true } } }, null, 2));
+ await withEnv(procEnv, async () => {
+ expect(launcherLaneFindings().filter((f) => f.harness === 'opencode')).toMatchObject([{ lane: 'mcp', source: config, reason: 'session_cwd', setupOwned: false, rerun: ['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--repair'] }]);
+ expect((await quiet(() => runBootstrap(['render', '--workspace', ws]))).result).toBe(0);
+ const r = await quiet(() => runBootstrap(['hooks', '--workspace', ws, '--harness', 'opencode', '--gbrain-bin', gbrain]));
+ expect(r.result, r.err).toBe(0);
+ expect(launcherLaneFindings().filter((f) => f.harness === 'opencode')).toEqual([]);
+ });
+ const entry = readJson(config).mcp.gbrain as { command: string[]; environment: Record<string, string> };
+ expect(entry.command.slice(0, 3)).toEqual([launcher, gbrain, 'serve']);
+ clearMarker();
+ // The workspace's own source is not registered in this brain, so the probe pins one that is.
+ expect(await serveFromSession(entry.command[0]!, entry.command.slice(1), { ...entry.environment, GBRAIN_SOURCE: 'source-b' }, 'notes/bootstrap-opencode')).toBe('source-b');
+ expect(existsSync(marker)).toBe(false);
+ await waitForDetached();
+ }, 120_000);
});
describe('#8428: the harness and plugin hook lanes', () => {
@@ -226,6 +273,10 @@ describe('#8428: the harness and plugin hook lanes', () => {
mkdirSync(join(pluginRoot, '.agents'), { recursive: true });
copyFileSync(join(ROOT, 'plugin-variants', 'gbrain-coding', '.agents', 'gbrain-launcher'), join(pluginRoot, '.agents', 'gbrain-launcher'));
chmodSync(join(pluginRoot, '.agents', 'gbrain-launcher'), 0o755);
+ const recorder = join(root, 'recording-gbrain');
+ const seen = join(root, 'recorder-saw');
+ writeFileSync(recorder, `#!/bin/sh\nif [ "$1" = --version ]; then echo "gbrain 0.60.549.0"; exit 0; fi\nprintf '%s|%s|%s\\n' "$GBRAIN_HOOK_CWD" "$(pwd)" "$1" > '${seen}'\n`);
+ chmodSync(recorder, 0o755);
const manifests: Array<[string, string]> = [['.claude-plugin/plugin.json', '${CLAUDE_PLUGIN_ROOT}'], ['.codex-plugin/plugin.json', '${PLUGIN_ROOT}']];
for (const [file, token] of manifests) {
const m = readJson(join(ROOT, 'plugin-variants', 'gbrain-coding', file));
@@ -235,6 +286,10 @@ describe('#8428: the harness and plugin hook lanes', () => {
const r = runHook(command.replaceAll(token, pluginRoot), { GBRAIN_BIN: gbrain });
expect(r.exitCode, r.stderr).toBe(0);
expect(existsSync(marker)).toBe(false);
+ // A launcher that exits 0 without starting gbrain also leaves no marker: a recording binary shows it ran, from where, and with which session directory.
+ rmSync(seen, { force: true });
+ expect(runHook(command.replaceAll(token, pluginRoot), { GBRAIN_BIN: recorder }).exitCode).toBe(0);
+ expect(readFileSync(seen, 'utf8')).toBe(`${hostile}|${join(pluginRoot, '.agents')}|hook\n`);
}
}, 120_000);
});
diff --git a/test/mcp-registration.test.ts b/test/mcp-registration.test.ts
index 04899e724b..ba04c47d40 100644
--- a/test/mcp-registration.test.ts
+++ b/test/mcp-registration.test.ts
@@ -67,14 +67,14 @@ describe('REGISTRATION_SURFACE and stdioServeArgv', () => {
describe('every stdio registration path builds from REGISTRATION_SURFACE', () => {
test('readiness harness_wiring: Claude Code and Codex pin the surface; opencode runs bootstrap hooks', () => {
// #8426: Claude Code and Codex register through gbrain setup, which puts serve behind the hook launcher.
- expect(wiring('claude-code')?.argv).toEqual(['gbrain', 'setup', 'claude-code', '--no-hooks', '--no-instructions', '--gbrain-bin', BIN]);
- expect(wiring('codex')?.argv).toEqual(['gbrain', 'setup', 'codex', '--no-hooks', '--no-instructions', '--gbrain-bin', BIN]);
+ expect(wiring('claude-code')?.argv).toEqual(['gbrain', 'setup', 'claude-code', '--no-hooks', '--gbrain-bin', BIN]);
+ expect(wiring('codex')?.argv).toEqual(['gbrain', 'setup', 'codex', '--no-hooks', '--gbrain-bin', BIN]);
expect(wiring('opencode')?.argv).toEqual(['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks']);
expect(wiring('claude-code')?.why).toContain(`${hookLauncherPath()} ${stdioServeArgv(BIN, REGISTRATION_SURFACE, REGISTRATION_ADVERTISE).join(' ')}`);
});
test('init --surface reaches the readiness fix (the quickstart line and the first-run harness decision read it)', () => {
- expect(wiring('claude-code', 'starter')?.argv).toEqual(['gbrain', 'setup', 'claude-code', '--no-hooks', '--no-instructions', '--gbrain-bin', BIN, '--surface', 'starter']);
+ expect(wiring('claude-code', 'starter')?.argv).toEqual(['gbrain', 'setup', 'claude-code', '--no-hooks', '--gbrain-bin', BIN, '--surface', 'starter']);
expect(wiring('claude-code', 'starter')?.why).toContain(`${BIN} serve --surface starter`);
expect(wiring('opencode', 'verbs')?.argv).toEqual(['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks', '--surface', 'verbs']);
const missing = harnessWiringEntry({ transport: 'cli', harnesses: [], lockOwner: null, gbrainBin: BIN }).fix;
@@ -165,7 +165,19 @@ describe('S0: README, docs/mcp, INSTALL, BOOTSTRAP, push-context and the manifes
}
});
}
- expect(commands).toBeGreaterThan(10);
+ expect(commands).toBeGreaterThanOrEqual(10);
+ expect(offenders).toEqual([]);
+ });
+
+ test('#8436: no install doc teaches a Claude Code or Codex stdio mcp add of serve that skips gbrain\'s launcher', () => {
+ const offenders: string[] = [];
+ for (const file of DOCS) {
+ readFileSync(join(ROOT, file), 'utf8').split('\n').forEach((line, i) => {
+ for (const m of line.matchAll(/\b(?:claude|codex)\s+mcp add\b[^`\n|]*?\bserve\b/g)) {
+ if (!m[0].includes('hook-launcher/gbrain-hook')) offenders.push(`${file}:${i + 1}: ${line.trim()}`);
+ }
+ });
+ }
expect(offenders).toEqual([]);
});
diff --git a/test/persistence-local-client.test.ts b/test/persistence-local-client.test.ts
index 45b7f33bb1..94d0de2642 100644
--- a/test/persistence-local-client.test.ts
+++ b/test/persistence-local-client.test.ts
@@ -8,6 +8,7 @@ import { PersistenceIpcTransportError, persistenceSocketPathForConfig, startPers
import { resolveSourceId } from '../src/core/source-resolver.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { withEnv } from './helpers/with-env.ts';
+import { captureHookSessionCwd } from '../src/core/session-cwd.ts';
const BRAIN = '10000000-0000-4000-8000-000000000001';
const dirs: string[] = [];
@@ -36,6 +37,22 @@ describe('engine-free local persistence routing', () => {
});
});
+ test('#8426: a serve the hook launcher started binds the socket of the mount its session directory names', async () => {
+ const dir = temp(), project = join(dir, 'project'), mounts = join(dir, 'mounts.json');
+ mkdirSync(project);
+ writeFileSync(join(project, '.gbrain-mount'), 'example-brain\n'); chmodSync(join(project, '.gbrain-mount'), 0o644);
+ writeFileSync(mounts, JSON.stringify({ version: 1, mounts: [{ id: 'example-brain', engine: 'pglite', path: join(dir, 'clone'), database_path: '/mount/db' }] }), { mode: 0o600 });
+ const host = { engine: 'postgres' as const, database_url: 'postgresql://example.invalid/host' };
+ await withEnv({ GBRAIN_MOUNTS_PATH: mounts, GBRAIN_BRAIN_ID: undefined, GBRAIN_HOOK_CWD: project }, () => {
+ captureHookSessionCwd();
+ try {
+ expect(residentPersistenceConfig(host)).toEqual({ ...host, engine: 'pglite', database_path: '/mount/db', database_url: undefined });
+ } finally {
+ captureHookSessionCwd();
+ }
+ });
+ });
+
test('missing registration never allocates a replacement principal', async () => {
const dir = temp();
await withEnv({ GBRAIN_HOME: dir }, () => {
diff --git a/test/plugin-turn-hook.test.ts b/test/plugin-turn-hook.test.ts
index 5d3d51b12b..935950b68b 100644
--- a/test/plugin-turn-hook.test.ts
+++ b/test/plugin-turn-hook.test.ts
@@ -266,7 +266,7 @@ describe('the plugin launcher on the per-turn hook (#7963)', () => {
test('a CLI older than the plugin lane: the plugin hook exits 0 silently, probing once per binary', () => {
const b = box();
- const cli = fakeCli(b, '0.60.497.0');
+ const cli = fakeCli(b, '0.60.546.0');
const env = { HOME: b.home, GBRAIN_BIN: cli.bin, GBRAIN_HOOK_LANE: 'plugin' };
expect(launch(env, ['hook', 'user-prompt'])).toEqual({ code: 0, stdout: '', stderr: '' });
expect(cli.calls()).toEqual(['--version']);
@@ -278,7 +278,7 @@ describe('the plugin launcher on the per-turn hook (#7963)', () => {
// Upgrading the binary (newer mtime than the cached verdict) re-probes.
const cache = join(b.home, '.gbrain', 'cache', 'plugin-hook-cli');
utimesSync(cache, new Date(Date.now() - 120_000), new Date(Date.now() - 120_000));
- const upgraded = fakeCli(b, '0.60.498.0');
+ const upgraded = fakeCli(b, '0.60.547.0');
expect(launch(env, ['hook', 'user-prompt']).stdout).toBe('ran hook user-prompt\n');
expect(upgraded.calls()).toEqual(['--version', 'hook user-prompt']);
expect(launch(env, ['hook', 'user-prompt']).stdout).toBe('ran hook user-prompt\n');
@@ -291,6 +291,6 @@ describe('the plugin launcher on the per-turn hook (#7963)', () => {
const gHome = join(b.root, 'ghome');
expect(launch({ HOME: b.home, GBRAIN_HOME: gHome, GBRAIN_BIN: cli.bin, GBRAIN_HOOK_LANE: 'plugin' }, ['hook', 'user-prompt', '--harness', 'codex']))
.toEqual({ code: 0, stdout: 'ran hook user-prompt --harness codex\n', stderr: '' });
- expect(readFileSync(join(gHome, '.gbrain', 'cache', 'plugin-hook-cli'), 'utf8')).toBe(`${cli.bin}\n0.60.498.0\nok\n`);
+ expect(readFileSync(join(gHome, '.gbrain', 'cache', 'plugin-hook-cli'), 'utf8')).toBe(`${cli.bin}\n0.60.547.0\nok\n`);
});
});
diff --git a/test/readiness.test.ts b/test/readiness.test.ts
index c430022619..4873cb3b3e 100644
--- a/test/readiness.test.ts
+++ b/test/readiness.test.ts
@@ -170,12 +170,12 @@ describe('harness_wiring by state', () => {
test('one harness, no serve: gbrain setup registers the absolute binary behind the hook launcher, --surface starter and --advertise verbs', () => {
const claude = harnessWiringEntry({ transport: 'cli', harnesses: ['claude-code'], lockOwner: null, gbrainBin: BIN });
- expect(claude.fix?.argv).toEqual(['gbrain', 'setup', 'claude-code', '--no-hooks', '--no-instructions', '--gbrain-bin', BIN]);
+ expect(claude.fix?.argv).toEqual(['gbrain', 'setup', 'claude-code', '--no-hooks', '--gbrain-bin', BIN]);
expect(claude.fix?.why).toContain(`/hook-launcher/gbrain-hook ${BIN} serve --surface starter --advertise verbs`);
expect(claude.fix?.consent).toEqual(['persistent_install']);
expect(claude.fix?.why).toContain('~/.claude.json');
expect(harnessWiringEntry({ transport: 'cli', harnesses: ['codex'], lockOwner: null, gbrainBin: BIN }).fix?.argv)
- .toEqual(['gbrain', 'setup', 'codex', '--no-hooks', '--no-instructions', '--gbrain-bin', BIN]);
+ .toEqual(['gbrain', 'setup', 'codex', '--no-hooks', '--gbrain-bin', BIN]);
expect(harnessWiringEntry({ transport: 'cli', harnesses: ['opencode'], lockOwner: null, gbrainBin: BIN }).fix?.argv)
.toEqual(['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks']);
});
diff --git a/test/setup.test.ts b/test/setup.test.ts
index 2498cc1411..6f70c70a57 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -982,11 +982,27 @@ describe('hooks written before the hook launcher (#8424): the next setup and pos
const before = { settings: readFileSync(settings(b), 'utf8'), config: readFileSync(claudeJson(b), 'utf8') };
await withEnv(env(b), async () => {
const plan = { name: r.name, scope: r.scope, launcher: r.launcher, brainHome: r.gbrain_home, sourceId: r.source_id, surface: r.surface, advertise: r.advertise ?? null, events: Object.keys(r.hooks.owned) as any };
- await expect(applyClaudeSetup(plan, r.consent, { pluginOwner: null, brainCreated: false, mcpMustBeSetups: true })).rejects.toThrow('MCP entry changed');
+ await expect(applyClaudeSetup(plan, r.consent, { pluginOwner: null, brainCreated: false, refreshOf: r })).rejects.toThrow('MCP entry changed');
});
expect({ settings: readFileSync(settings(b), 'utf8'), config: readFileSync(claudeJson(b), 'utf8') }).toEqual(before);
});
+ test('claude-code: the hook rewrite refuses under the lock when another install replaced the receipt it planned from, and writes nothing', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);
+ downgradeClaude(b);
+ // post-upgrade read this receipt; before it took the lock, the name was removed and installed again, so the entry is the new install's and still setup's.
+ const planned = readSetupReceipt(receipt(b)).setup!;
+ const replaced = { ...planned, consent: { ...planned.consent, recorded_at: '2026-01-01T00:00:00.000Z' } };
+ writeFileSync(receipt(b), JSON.stringify(replaced, null, 2));
+ const before = { settings: readFileSync(settings(b), 'utf8'), config: readFileSync(claudeJson(b), 'utf8'), receipt: readFileSync(receipt(b), 'utf8') };
+ await withEnv(env(b), async () => {
+ const plan = { name: planned.name, scope: planned.scope, launcher: planned.launcher, brainHome: planned.gbrain_home, sourceId: planned.source_id, surface: planned.surface, advertise: planned.advertise ?? null, events: Object.keys(planned.hooks.owned) as any };
+ await expect(applyClaudeSetup(plan, planned.consent, { pluginOwner: null, brainCreated: false, refreshOf: planned })).rejects.toThrow('setup receipt changed');
+ });
+ expect({ settings: readFileSync(settings(b), 'utf8'), config: readFileSync(claudeJson(b), 'utf8'), receipt: readFileSync(receipt(b), 'utf8') }).toEqual(before);
+ });
+
test('claude-code: --instructions-only moves a pre-launcher turn-rule entry that sits beside setup hooks', async () => {
const b = box();
expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);
@@ -1079,6 +1095,21 @@ describe('hooks written before the hook launcher (#8424): the next setup and pos
expect((await setup(b, ['claude-code', '--json'])).doc.steps.map((s: any) => s.action)).toEqual(['keep', 'keep', 'keep']);
});
+ test('claude-code MCP (#8426): doctor\'s rerun keeps a recorded --no-hooks, so moving the entry turns no hooks on', async () => {
+ const b = box();
+ expect((await setup(b, ['claude-code', '--no-hooks', '--json'])).exitCode).toBe(0);
+ downgradeClaudeMcp(b);
+ let argv: string[] = [];
+ await withEnv(env(b), async () => {
+ argv = hookLauncherFix(hookLauncherProblems([])!).argv!;
+ expect(argv).toEqual(['gbrain', 'setup', 'claude-code', '--no-hooks']);
+ });
+ expect((await setup(b, [...argv.slice(2), '--json'])).exitCode).toBe(0);
+ expect(readSetupReceipt(receipt(b)).setup!.consent.wiring_scope.value.hooks).toBe('none');
+ const moved = readJson(claudeJson(b)).mcpServers.gbrain;
+ expect(moved.command).toBe(launcher(b));
+ });
+
test('claude-code MCP (#8426): a pre-launcher MCP entry the user edited is kept; post-upgrade and doctor hand it to the user', async () => {
const b = box();
expect((await setup(b, ['claude-code', '--json'])).exitCode).toBe(0);