Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
lane 1: plugin launcher, variants, codex trust, hermes lock, bootstrap help
garrytan5a46bf45429c
diff --git a/.agents/gbrain-launcher b/.agents/gbrain-launcherindex ecd8ba4abc..bc5b5a4772 100755--- a/.agents/gbrain-launcher+++ b/.agents/gbrain-launcher@@ -18,12 +18,27 @@# No auto-install by design: an MCP server start must never run a network# install. On a miss this exits 127 with the recovery path on stderr; the# bundled `setup` skill walks the install interactively.+#+# `hook …` (the plugin's per-turn hook) is the exception: 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+# <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+HOOK=0+[ "${1:-}" = "hook" ] && HOOK=1+resolve_bin() {if [ -n "${GBRAIN_BIN:-}" ]; thenif [ ! -x "$GBRAIN_BIN" ]; then+ [ "$HOOK" = 1 ] && exit 0echo "gbrain-launcher: GBRAIN_BIN='$GBRAIN_BIN' is not an executable file" >&2exit 127fi@@ -42,6 +57,7 @@ resolve_bin() {command -v gbrainreturnfi+ [ "$HOOK" = 1 ] && exit 0echo "gbrain-launcher: gbrain binary not found." >&2echo " install: bun install -g github:garrytan/gbrain#latest-stable" >&2echo " (the npm package named 'gbrain' is unrelated - do not npm install it)" >&2@@ -50,8 +66,49 @@ resolve_bin() {exit 127}+# 0 when dotted-numeric version $1 >= $2.+version_ge() {+ _a="$1"; _b="$2"+ while [ -n "$_a$_b" ]; do+ _x="${_a%%.*}"; _y="${_b%%.*}"+ case "$_a" in *.*) _a="${_a#*.}" ;; *) _a="" ;; esac+ case "$_b" in *.*) _b="${_b#*.}" ;; *) _b="" ;; esac+ if [ "${_x:-0}" -gt "${_y:-0}" ]; then return 0; fi+ if [ "${_x:-0}" -lt "${_y:-0}" ]; then return 1; fi+ done+ return 0+}++# 0 when $BIN understands GBRAIN_HOOK_LANE=plugin (see the header).+plugin_lane_ok() {+ _cache=""+ case "${GBRAIN_HOME:-${HOME:-}}" in /*) _cache="${GBRAIN_HOME:-$HOME}/.gbrain/cache/plugin-hook-cli" ;; esac+ if [ -n "$_cache" ] && [ "$_cache" -nt "$BIN" ]; then+ if { IFS= read -r _cbin && IFS= read -r _cmin && IFS= read -r _cok; } 2>/dev/null < "$_cache"; then+ if [ "$_cbin" = "$BIN" ] && [ "$_cmin" = "$PLUGIN_LANE_MIN" ]; then+ [ "$_cok" = ok ]+ return+ fi+ fi+ fi+ _v="$("$BIN" --version 2>/dev/null)" || return 1+ _v="${_v##* }"+ case "$_v" in ''|*[!0-9.]*|.*|*..*) return 1 ;; esac+ _ok=old+ if version_ge "$_v" "$PLUGIN_LANE_MIN"; then _ok=ok; fi+ if [ -n "$_cache" ]; then+ { (umask 077 && mkdir -p "${_cache%/*}") && printf '%s\n%s\n%s\n' "$BIN" "$PLUGIN_LANE_MIN" "$_ok" > "$_cache.$" && mv -f "$_cache.$" "$_cache"; } 2>/dev/null || rm -f "$_cache.$" 2>/dev/null || :+ fi+ [ "$_ok" = ok ]+}+BIN="$(resolve_bin)"-echo "gbrain-launcher: using $BIN" >&2+if [ "$HOOK" = 1 ]; then+ [ -n "$BIN" ] || exit 0+ if [ "${GBRAIN_HOOK_LANE:-}" = "plugin" ] && ! plugin_lane_ok; then exit 0; fi+else+ echo "gbrain-launcher: using $BIN" >&2+fi# Surface override — only for `serve` invocations. Rebuilds the positional# params in place (rotate-through-sentinel idiom; no eval, no word-splittingdiff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex 0c0dd7ada3..36b939ce31 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -21,7 +21,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/setup/capabilities.ts` + `src/core/setup/claude-code.ts` — `gbrain setup`'s data and Claude Code writer. `capabilities.ts` is the versioned harness × transport table (`SETUP_CAPABILITY_TABLE_VERSION`; per row `setup`, `pull`, `push`, `read_events`, `capture_events`, `docs`); push is `native-pending` or `unsupported` on every row until an observed injected event proves it. `claude-code.ts` owns entries by exact hash through the connection receipt `.gbrain-connection-claude-code-<name>[-project-<hash>].json` beside `~/.claude.json` (`connection: 'local-stdio'`, `entry_hash`/`pending_entry_hash`, `hooks.{owned,pending,edited}`, `consent`, `gbrain_home`; a receipt with `client_id` is a hosted one and is never adopted). The MCP entry (`{type:'stdio', command, args, env}`, user scope `mcpServers` or project scope `projects[<dir>].mcpServers`) is written directly; hooks go through `writeClaudeHooksAt`/`removeClaudeHooksAt` with marker `GBRAIN_SETUP_MARKER_VALUE` and `ownedEntryHashes`. `applyClaudeSetup` (under the config-dir bootstrap lock) writes the receipt `prepared` first, then the brain (`beforeMcp`), the MCP entry, the hooks and `installed`, each step recording its hash so a resume never duplicates; an unchanged install writes nothing. An owned event whose recorded hash vanished while a marked entry remains is `edited`: preserved, reported, and skipped by later runs. `removeClaudeSetup` deletes only hash-matched entries (adopted entries stay), keeps a `removed` receipt when an edited entry survives, and otherwise deletes the receipt. The codex row (table version 2) is `supported` with `push: 'native-verified'` and a `push_evidence` string (codex-cli 0.162.1, observed UserPromptSubmit injection into fresh native sessions, 3/3, with a `--no-hooks` control); `entryHash` is `ownedEntryFingerprint` from adopted-connections.ts.- `src/core/setup/codex.ts` — `gbrain setup codex`'s writer. Owns three kinds of entry, each by `ownedEntryFingerprint` (sha256 over canonical JSON of the exact parsed entry) recorded per entry in `$CODEX_HOME/.gbrain-connection-codex-<name>.json` (`setup_receipt_version: 2`: the claude-code receipt fields plus `hooks_path`, `gbrain_home_env` and `trust.{owned,pending,edited}` keyed by event as `{key, hash}`; a `client_id` receipt is hosted and never adopted): the stdio `[mcp_servers.<name>]` table (`command`, `args`, inline `env`), one hooks.json group per wanted event (`codexSetupHookGroup`), and one `[hooks.state."<hooks.json>:<event>:<index>:0"]` trust table per group. `applyCodexSetup` (under the CODEX_HOME bootstrap lock) writes in a crash-recoverable order: receipt `prepared` (the consent record and pending fingerprints) → brain (`beforeMcp`) → MCP table → hooks.json groups (inert until trusted) → stale owned trust tables removed, wanted ones appended (activation last) → `installed`; each step records its fingerprints so a resume never duplicates. Compare-and-swap everywhere: a group whose recorded hash vanished while a this-install setup-lane group remains is `edited` (preserved, reported, never trusted by setup); a trust table at setup's key with a different value is preserved (`conflict`/`edited`); an identical pre-existing MCP table is `mcp_adopted` and kept on removal. `removeCodexSetup` runs trust → hooks → MCP → receipt and keeps a `removed` receipt when an edited entry survives. `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks|trust` is the crash seam. Pinned by the codex blocks of `test/setup.test.ts`.- `src/core/setup/local-receipts.ts` — read-only view of this install's live local-stdio setup receipts (`.gbrain-connection-*.json` beside `~/.claude.json` and in `CODEX_HOME`; kept only when `connection: 'local-stdio'`, a numeric `setup_receipt_version`, `gbrain_home === configDir()` and status `prepared`/`installed`). Engine-free, imports no harness writer. `providerDeclineRecord()` (a recorded `providers: declined`, opt-outs win) gates OpenAI model discovery and doctor's provider probe; `claudeCodeSpawnsServe(cwd)` (an installed claude-code receipt, user scope or a project receipt for exactly `cwd`) tells the SessionStart hook that Claude Code is starting a stdio serve.-- `src/core/bootstrap/plugin-lanes.ts` — plugin-lane detection (`codexPluginProvidesName`, `claudePluginProvidesName`, `codexAnyRegistrationExists`, `claudeAnyRegistrationExists`; re-exported from harness.ts) plus `enabledPluginLanes(name)`, the one list `plugin_lane_collision` and `harness_wiring` both read. Config, not health: an enabled plugin counts even if its launcher fails.+- `src/core/bootstrap/plugin-lanes.ts` — plugin-lane detection (`*PluginProvidesName`, `*AnyRegistrationExists`, re-exported by harness.ts; variants count as `gbrain`) plus `enabledPluginLanes(name)`, read by `plugin_lane_collision`/`harness_wiring`. Config, not health. `pluginHookYields`: yield to no-hooks consent, another lane (Codex: trusted, enabled), a higher `GBRAIN_PLUGIN`.- `src/core/bootstrap/codex-hooks.ts` — the codex `hooks.json` writer (SessionEnd capture lane), built entirely on the dated `CODEX_HOOKS_SPEC_TARGET` (verified 2026-08-25 against pinned codex-cli 0.147.0, live + tag-source evidence; re-run the observation gate on codex version bumps). The three load-bearing facts: hooks.json is TOP-LEVEL deny-unknown-fields (ownership rides the legal `description` slot + a command-substring token, never a `_gbrain` key); user-layer hooks are TRUST-GATED and fail SILENTLY (the writer lands BOTH the hooks.json entry AND its `[hooks.state."<path>:session_end:<g>:<h>"].trusted_hash` config.toml entry — sha256 of the recursively-key-sorted compact canonical JSON of the normalized handler identity — inside a gbrain-managed marker block, backing config.toml up to `.hooks.bak` so it never clobbers the MCP writer's `.bak` rollback anchor); SessionEnd handlers are hard-killed at 3s (the command captures stdin to a mktemp file and detaches a nohup grandchild running the real `gbrain hook session-end --harness codex` — live-verified end-to-end). Deliberately NO `GBRAIN_SOURCE` in the command: hooks.json is user-global, so a baked source would stamp every codex session on the machine; session-end resolves everything from the payload. a fresh install APPENDS our group last while a re-run REPLACES it IN PLACE (a single well-formed install never shifts a foreign group's trust index; dropping DUPLICATE gbrain groups can shift foreign groups sitting after them — the writer prints a note naming the re-trust); the whole command is wrapped in a top-level `sh -c '…' <bin>` so a non-POSIX $SHELL (fish/csh) never parses the POSIX script; the foreign-trust-entry guard is a tolerant [hooks.state…] header match (not byte-exact); a golden known-answer hash vector pins the canonical recipe; removal also deletes the gbrain description when byte-identical to ours and NOTES the inherent index shift for foreign groups that sat after ours; unparseable hooks.json is never touched, on write or removal; the residual stale-trust-index case (user reorders their own groups) degrades to silent non-execution, which doctor's `codex_hooks_never_fired` rung names. Pinned by `test/codex-hooks-writer.test.ts`. `codexHookTrustHash(eventName, command, timeout)` is the generalized recipe (re-read against openai/codex rust-v0.162.1 `hook_hash` + `version_for_toml`; a known-answer vector from trust entries a live codex-cli 0.162.1 executed pins it in `test/setup.test.ts`). The setup lane (`CODEX_SETUP_EVENTS` SessionStart/UserPromptSubmit 15s, SessionEnd 3s) is hash-owned: `codexSetupHookGroup` renders `env GBRAIN_HOOK_LANE=setup [GBRAIN_HOME=…] [GBRAIN_SOURCE=…] <bin> hook <sub> --harness codex` (SessionEnd prefixes the detached capture command), `codexHookCensus` fingerprints every group and tags its lane, `writeCodexSetupHooks` replaces owned groups in place / appends / drops only owned groups (notes any index shift), and the token-owned bootstrap writer's `isOurGroup` skips groups carrying `GBRAIN_HOOK_LANE=setup`, so bootstrap never claims or strips setup's groups.`writeCommittedClaudeHooks` is the second, COMMITTED hook carrier: it writes marker-keyed entries into the workspace's checked-in `.claude/settings.json` using `buildPortableClaudeHookCommand` (PATH-resolved `gbrain`, fail-open when the binary is absent) so teammates cloning the repo inherit the hooks; `committedHookEvents(ws)` feeds the local writer's `carriedEvents` so the two carriers never double-wire an event, and `removeClaudeHooks` strips both.- `src/core/bootstrap/codex-toml.ts` — the ONE direct codex-config writer (`codex mcp add` cannot express an inline credential, and framework-spawned codex inherits no shell profile for the env-var lane). One `[mcp_servers.<name>]` table between full-line markers carrying `url` + `http_headers = { Authorization = "Bearer <token>" }` (NOT inline `bearer_token`, which codex-cli >=0.149 rejects at config load; `parseCodexBlockBearer` in harness.ts keeps a legacy `bearer_token` read fallback so existing tokens still recover); everything outside survives byte-for-byte. Foreign-server detection PARSES the config (Bun.TOML.parse, no dependency) with our block stripped — a header-only regex would false-negative inline-table/dotted/quoted spellings into a codex-bricking duplicate table; rewrites re-anchor at EOF; renders are parse-validated with an ours-keys-exactly assert before rename; damaged markers refuse; 0600 tmp/target/.bak (the .bak carries the previous token on re-runs); CRLF preserved, missing trailing newline repaired. Also exports `renderCodexHttpServerBlock({name, url, bearerToken})` — a MARKER-FREE, parse-validated `[mcp_servers.<name>]` TOML render for paste-into-config surfaces (`gbrain agent register`'s codex block); rendering only, never writes a file. Pinned by `test/codex-toml.test.ts`. Also the hash-owned single-table helpers for `gbrain setup codex`: `readCodexTomlTable`, `appendCodexTomlTable` (EOF append, refuses an existing table, parse-verifies the result is exactly the old document plus the table) and `removeCodexTomlTable` (header through the line before the next header, keeping trailing comments/blank lines and a preceding `# gbrain setup` comment; `unlocatable` when the edit would change anything but that table, e.g. a re-rendered subtable). No markers: codex may rewrite config.toml and drop comments.diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.mdindex 7f025c9690..31ccbb33d0 100644--- a/docs/architecture/key-files/entrypoints-and-docs.md+++ b/docs/architecture/key-files/entrypoints-and-docs.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `.agents/gbrain-launcher` — shared plugin MCP launcher (sh, Unix-only) for the Codex, Claude Code, and OpenClaw (`openclaw.plugin.json` `mcpServers.gbrain`) lanes: GBRAIN_BIN → ~/.bun/bin/gbrain → PATH resolution, one stderr resolution line, GBRAIN_SURFACE substitute-or-append override for `serve` argv, actionable exit-127 recovery copy, no auto-install by design. Behavioral branches all pinned in the manifest test.+- `.agents/gbrain-launcher` — shared plugin MCP launcher (sh, Unix-only) for the Codex, Claude Code, and OpenClaw (`openclaw.plugin.json` `mcpServers.gbrain`) lanes: GBRAIN_BIN → ~/.bun/bin/gbrain → PATH resolution, one stderr resolution line, GBRAIN_SURFACE substitute-or-append override for `serve` argv, actionable exit-127 recovery copy, no auto-install by design. `hook …` exits 0 silently on a miss (no per-turn error on plugin-first installs), and with GBRAIN_HOOK_LANE=plugin also when the CLI predates the plugin lane (`PLUGIN_LANE_MIN`; one `--version` probe per binary, verdict cached in `.gbrain/cache/plugin-hook-cli` while newer than the binary). Behavioral branches all pinned in the manifest test.- `.claude-plugin/plugin.json` + `.claude-plugin/marketplace.json` — the Claude Code plugin lane: inline MCP declaration (command/args/cwd via `${CLAUDE_PLUGIN_ROOT}`; no `env` block — Claude passes the parent env through); the Claude marketplace carries the full plugin PLUS the persona variant entries (`gbrain-coding`/`gbrain-daily` → `plugin-variants/`), while the codex marketplace intentionally stays single-entry until codex's multi-entry handling gets its observation run — variant names are pinned to `skills/plugin-lanes.json#personas` by `test/codex-plugin-manifest.test.ts`.diff --git a/plugin-variants/gbrain-coding/.agents/gbrain-launcher b/plugin-variants/gbrain-coding/.agents/gbrain-launcherindex ecd8ba4abc..bc5b5a4772 100755--- a/plugin-variants/gbrain-coding/.agents/gbrain-launcher+++ b/plugin-variants/gbrain-coding/.agents/gbrain-launcher@@ -18,12 +18,27 @@# No auto-install by design: an MCP server start must never run a network# install. On a miss this exits 127 with the recovery path on stderr; the# bundled `setup` skill walks the install interactively.+#+# `hook …` (the plugin's per-turn hook) is the exception: 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+# <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+HOOK=0+[ "${1:-}" = "hook" ] && HOOK=1+resolve_bin() {if [ -n "${GBRAIN_BIN:-}" ]; thenif [ ! -x "$GBRAIN_BIN" ]; then+ [ "$HOOK" = 1 ] && exit 0echo "gbrain-launcher: GBRAIN_BIN='$GBRAIN_BIN' is not an executable file" >&2exit 127fi@@ -42,6 +57,7 @@ resolve_bin() {command -v gbrainreturnfi+ [ "$HOOK" = 1 ] && exit 0echo "gbrain-launcher: gbrain binary not found." >&2echo " install: bun install -g github:garrytan/gbrain#latest-stable" >&2echo " (the npm package named 'gbrain' is unrelated - do not npm install it)" >&2@@ -50,8 +66,49 @@ resolve_bin() {exit 127}+# 0 when dotted-numeric version $1 >= $2.+version_ge() {+ _a="$1"; _b="$2"+ while [ -n "$_a$_b" ]; do+ _x="${_a%%.*}"; _y="${_b%%.*}"+ case "$_a" in *.*) _a="${_a#*.}" ;; *) _a="" ;; esac+ case "$_b" in *.*) _b="${_b#*.}" ;; *) _b="" ;; esac+ if [ "${_x:-0}" -gt "${_y:-0}" ]; then return 0; fi+ if [ "${_x:-0}" -lt "${_y:-0}" ]; then return 1; fi+ done+ return 0+}++# 0 when $BIN understands GBRAIN_HOOK_LANE=plugin (see the header).+plugin_lane_ok() {+ _cache=""+ case "${GBRAIN_HOME:-${HOME:-}}" in /*) _cache="${GBRAIN_HOME:-$HOME}/.gbrain/cache/plugin-hook-cli" ;; esac+ if [ -n "$_cache" ] && [ "$_cache" -nt "$BIN" ]; then+ if { IFS= read -r _cbin && IFS= read -r _cmin && IFS= read -r _cok; } 2>/dev/null < "$_cache"; then+ if [ "$_cbin" = "$BIN" ] && [ "$_cmin" = "$PLUGIN_LANE_MIN" ]; then+ [ "$_cok" = ok ]+ return+ fi+ fi+ fi+ _v="$("$BIN" --version 2>/dev/null)" || return 1+ _v="${_v##* }"+ case "$_v" in ''|*[!0-9.]*|.*|*..*) return 1 ;; esac+ _ok=old+ if version_ge "$_v" "$PLUGIN_LANE_MIN"; then _ok=ok; fi+ if [ -n "$_cache" ]; then+ { (umask 077 && mkdir -p "${_cache%/*}") && printf '%s\n%s\n%s\n' "$BIN" "$PLUGIN_LANE_MIN" "$_ok" > "$_cache.$" && mv -f "$_cache.$" "$_cache"; } 2>/dev/null || rm -f "$_cache.$" 2>/dev/null || :+ fi+ [ "$_ok" = ok ]+}+BIN="$(resolve_bin)"-echo "gbrain-launcher: using $BIN" >&2+if [ "$HOOK" = 1 ]; then+ [ -n "$BIN" ] || exit 0+ if [ "${GBRAIN_HOOK_LANE:-}" = "plugin" ] && ! plugin_lane_ok; then exit 0; fi+else+ echo "gbrain-launcher: using $BIN" >&2+fi# Surface override — only for `serve` invocations. Rebuilds the positional# params in place (rotate-through-sentinel idiom; no eval, no word-splittingdiff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex cd1c95e2b3..d6dcbfe00b 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -37,7 +37,7 @@"hooks": [{"type": "command",- "command": "env GBRAIN_HOOK_LANE=plugin \"${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt",+ "command": "env GBRAIN_HOOK_LANE=plugin GBRAIN_PLUGIN=gbrain-coding \"${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt","timeout": 3}]diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex efad8907a9..c9fa686d9d 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -27,7 +27,7 @@"hooks": [{"type": "command",- "command": "env GBRAIN_HOOK_LANE=plugin \"${PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt --harness codex",+ "command": "env GBRAIN_HOOK_LANE=plugin GBRAIN_PLUGIN=gbrain-coding \"${PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt --harness codex","timeout": 15}]diff --git a/plugin-variants/gbrain-daily/.agents/gbrain-launcher b/plugin-variants/gbrain-daily/.agents/gbrain-launcherindex ecd8ba4abc..bc5b5a4772 100755--- a/plugin-variants/gbrain-daily/.agents/gbrain-launcher+++ b/plugin-variants/gbrain-daily/.agents/gbrain-launcher@@ -18,12 +18,27 @@# No auto-install by design: an MCP server start must never run a network# install. On a miss this exits 127 with the recovery path on stderr; the# bundled `setup` skill walks the install interactively.+#+# `hook …` (the plugin's per-turn hook) is the exception: 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+# <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+HOOK=0+[ "${1:-}" = "hook" ] && HOOK=1+resolve_bin() {if [ -n "${GBRAIN_BIN:-}" ]; thenif [ ! -x "$GBRAIN_BIN" ]; then+ [ "$HOOK" = 1 ] && exit 0echo "gbrain-launcher: GBRAIN_BIN='$GBRAIN_BIN' is not an executable file" >&2exit 127fi@@ -42,6 +57,7 @@ resolve_bin() {command -v gbrainreturnfi+ [ "$HOOK" = 1 ] && exit 0echo "gbrain-launcher: gbrain binary not found." >&2echo " install: bun install -g github:garrytan/gbrain#latest-stable" >&2echo " (the npm package named 'gbrain' is unrelated - do not npm install it)" >&2@@ -50,8 +66,49 @@ resolve_bin() {exit 127}+# 0 when dotted-numeric version $1 >= $2.+version_ge() {+ _a="$1"; _b="$2"+ while [ -n "$_a$_b" ]; do+ _x="${_a%%.*}"; _y="${_b%%.*}"+ case "$_a" in *.*) _a="${_a#*.}" ;; *) _a="" ;; esac+ case "$_b" in *.*) _b="${_b#*.}" ;; *) _b="" ;; esac+ if [ "${_x:-0}" -gt "${_y:-0}" ]; then return 0; fi+ if [ "${_x:-0}" -lt "${_y:-0}" ]; then return 1; fi+ done+ return 0+}++# 0 when $BIN understands GBRAIN_HOOK_LANE=plugin (see the header).+plugin_lane_ok() {+ _cache=""+ case "${GBRAIN_HOME:-${HOME:-}}" in /*) _cache="${GBRAIN_HOME:-$HOME}/.gbrain/cache/plugin-hook-cli" ;; esac+ if [ -n "$_cache" ] && [ "$_cache" -nt "$BIN" ]; then+ if { IFS= read -r _cbin && IFS= read -r _cmin && IFS= read -r _cok; } 2>/dev/null < "$_cache"; then+ if [ "$_cbin" = "$BIN" ] && [ "$_cmin" = "$PLUGIN_LANE_MIN" ]; then+ [ "$_cok" = ok ]+ return+ fi+ fi+ fi+ _v="$("$BIN" --version 2>/dev/null)" || return 1+ _v="${_v##* }"+ case "$_v" in ''|*[!0-9.]*|.*|*..*) return 1 ;; esac+ _ok=old+ if version_ge "$_v" "$PLUGIN_LANE_MIN"; then _ok=ok; fi+ if [ -n "$_cache" ]; then+ { (umask 077 && mkdir -p "${_cache%/*}") && printf '%s\n%s\n%s\n' "$BIN" "$PLUGIN_LANE_MIN" "$_ok" > "$_cache.$" && mv -f "$_cache.$" "$_cache"; } 2>/dev/null || rm -f "$_cache.$" 2>/dev/null || :+ fi+ [ "$_ok" = ok ]+}+BIN="$(resolve_bin)"-echo "gbrain-launcher: using $BIN" >&2+if [ "$HOOK" = 1 ]; then+ [ -n "$BIN" ] || exit 0+ if [ "${GBRAIN_HOOK_LANE:-}" = "plugin" ] && ! plugin_lane_ok; then exit 0; fi+else+ echo "gbrain-launcher: using $BIN" >&2+fi# Surface override — only for `serve` invocations. Rebuilds the positional# params in place (rotate-through-sentinel idiom; no eval, no word-splittingdiff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex bce931342b..7398eb36b8 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -37,7 +37,7 @@"hooks": [{"type": "command",- "command": "env GBRAIN_HOOK_LANE=plugin \"${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt",+ "command": "env GBRAIN_HOOK_LANE=plugin GBRAIN_PLUGIN=gbrain-daily \"${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt","timeout": 3}]diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 7346d4c729..776086d6b8 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -27,7 +27,7 @@"hooks": [{"type": "command",- "command": "env GBRAIN_HOOK_LANE=plugin \"${PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt --harness codex",+ "command": "env GBRAIN_HOOK_LANE=plugin GBRAIN_PLUGIN=gbrain-daily \"${PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt --harness codex","timeout": 15}]diff --git a/scripts/generate-plugin-tree.ts b/scripts/generate-plugin-tree.tsindex 963a71dc6b..44c2f19545 100644--- a/scripts/generate-plugin-tree.ts+++ b/scripts/generate-plugin-tree.ts@@ -343,6 +343,19 @@ function emitVariant(variantsDir: string, personaName: string, def: PersonaDef,// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversalcpSync(join(ROOT, '.agents', 'gbrain-launcher'), join(root, '.agents', 'gbrain-launcher'));+ // The per-turn hook names its plugin (GBRAIN_PLUGIN) so that, with several+ // gbrain plugins enabled, the CLI runs only the highest-precedence one's+ // (pluginHookYields, src/core/bootstrap/plugin-lanes.ts).+ const LANE = 'env GBRAIN_HOOK_LANE=plugin ';+ const withIdentity = (hooks: unknown): unknown => {+ const text = JSON.stringify(hooks);+ if (!/^[a-z0-9-]+$/.test(def.plugin_name) || !text?.includes(LANE)) {+ console.error(`generate-plugin-tree: cannot name ${def.plugin_name} in the root manifests' hook commands (expected "${LANE}…")`);+ process.exit(1);+ }+ return JSON.parse(text.replaceAll(LANE, `${LANE}GBRAIN_PLUGIN=${def.plugin_name} `));+ };+// Claude plugin manifest: model on the root manifest, retargeted at the// variant root (skills live at ./skills/ here, not ./plugin/skills/).const claudeBase = JSON.parse(readFileSync(join(ROOT, '.claude-plugin', 'plugin.json'), 'utf8')) as Record<@@ -355,6 +368,7 @@ function emitVariant(variantsDir: string, personaName: string, def: PersonaDef,version,description: `${def.description} (persona variant of the gbrain plugin — ${slugs.length} skills)`,skills: './skills/',+ hooks: withIdentity(claudeBase.hooks),};// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversalmkdirSync(join(root, '.claude-plugin'), { recursive: true });@@ -374,6 +388,7 @@ function emitVariant(variantsDir: string, personaName: string, def: PersonaDef,description: `${def.description} (persona variant of the gbrain plugin — ${slugs.length} skills)`,skills: './skills/',mcpServers: './.codex-plugin/mcp.json',+ hooks: withIdentity(codexBase.hooks),};// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversalmkdirSync(join(root, '.codex-plugin'), { recursive: true });diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.tsindex 71b9ae4d94..03227713b5 100644--- a/src/commands/bootstrap.ts+++ b/src/commands/bootstrap.ts@@ -64,7 +64,7 @@ import {removeClaudeHooks,} from '../core/bootstrap/hooks.ts';import { removeCodexHooks, writeCodexHooks } from '../core/bootstrap/codex-hooks.ts';-import { isRegistrationSurface, registeredSurface, stdioServeArgv } from '../core/mcp-registration.ts';+import { isRegistrationSurface, registeredSurface, REGISTRATION_SURFACE, stdioServeArgv } from '../core/mcp-registration.ts';import type { McpSurface } from '../mcp/surface.ts';import {guardReceiptOverwrite,@@ -204,7 +204,7 @@ const SUBCOMMAND_HELP: Record<string, string> = {hooks:'gbrain bootstrap hooks [--harness claude-code|codex|opencode] [--repair] [--no-hooks] [--gbrain-bin <path>]\n' +' [--seat <label> | --no-seat] [--surface verbs|starter|full] [--adopt [--name <server>]]\n' +- ' Register MCP (--surface full unless given; a replaced entry keeps its surface) (+ per-turn hooks on Claude Code, ON by default; --no-hooks opts out).\n' ++ ` Register MCP (--surface ${REGISTRATION_SURFACE} unless given; a replaced entry keeps its surface, full when unreadable) (+ per-turn hooks on Claude Code, ON by default; --no-hooks opts out).\n` +' --seat credits captured sessions to this agent seat (kept on re-install; --no-seat clears it; --seat off records none).\n' +' --adopt (Codex): record the project .codex/config.toml server you manage yourself as the wire evidence after a passing verify; writes no config.',verify:@@ -1487,7 +1487,7 @@ async function runHooks();return 1;}- const re = await runner(surfaceFlag || priorSurface === undefined ? argv : buildArgvs(priorSurface)[0]);+ const re = await runner(surfaceFlag ? argv : buildArgvs(priorSurface === undefined ? 'full' : priorSurface)[0]);if (re.code !== 0 && !/already exists|already registered/i.test(re.stderr + re.stdout)) {console.error(`MCP re-registration failed (${argv.join(' ')}): ${re.stderr.trim() || `exit ${re.code}`}`);return 1;diff --git a/src/core/bootstrap/codex-hooks.ts b/src/core/bootstrap/codex-hooks.tsindex 70a3504447..81b0ad7a98 100644--- a/src/core/bootstrap/codex-hooks.ts+++ b/src/core/bootstrap/codex-hooks.ts@@ -49,6 +49,7 @@ import { createHash } from 'node:crypto';import { chmodSync, copyFileSync, existsSync, readFileSync, statSync } from 'node:fs';import { atomicWriteTextFile } from './atomic-write.ts';import { ownedEntryFingerprint } from './adopted-connections.ts';+import { readCodexTomlTable } from './codex-toml.ts';import type { HostSpecTarget } from './host-specs.ts';import { CODEX_HOOK_EVENTS, codexConfigPath, codexHooksPath } from './host-specs.ts';@@ -427,6 +428,29 @@ export function codexHookCensus(hooksPath: string): CodexHookCensusGroup[] {return out;}+/**+ * Whether Codex runs gbrain's handler in group `index` of a context event+ * (SessionStart, UserPromptSubmit): its `[hooks.state."<hooksPath>:<state>:+ * <index>:<handler>"]` entry in `configPath` is not `enabled = false` and its+ * `trusted_hash` equals the hash of the handler as written (gbrain's shape: no+ * matcher, not async, an unset timeout normalized to 600). Codex never runs an+ * untrusted or disabled user-layer hook. Throws on an unparseable file.+ */+export function codexHookGroupRuns(hooksPath: string, configPath: string, group: { event: string; index: number }): boolean {+ if (group.event !== 'SessionStart' && group.event !== 'UserPromptSubmit') return false;+ const { stateName } = SETUP_EVENT_SPECS[group.event];+ const handlers = loadHooksJson(hooksPath).hooks[group.event]?.[group.index]?.hooks;+ if (!Array.isArray(handlers)) return false;+ const states = readCodexTomlTable(configPath, ['hooks', 'state']) as Record<string, { enabled?: unknown; trusted_hash?: unknown } | undefined> | undefined;+ return handlers.some((h, i) => {+ const command = h?.command;+ if (typeof command !== 'string' || !(command.includes(CODEX_SETUP_LANE_TOKEN) || CONTEXT_LANE_TOKENS.some((t) => command.includes(t)))) return false;+ const state = states?.[`${hooksPath}:${stateName}:${group.index}:${i}`];+ if (!state || state.enabled === false) return false;+ return state.trusted_hash === codexHookTrustHash(stateName, command, typeof h.timeout === 'number' ? Math.max(1, h.timeout) : 600);+ });+}+/*** Converge setup's groups in hooks.json: for each event, a group whose* fingerprint is in `owned` (or equals the wanted one) is replaced IN PLACE bydiff --git a/src/core/bootstrap/plugin-lanes.ts b/src/core/bootstrap/plugin-lanes.tsindex 43aa6a53f5..4d2b77d3e4 100644--- a/src/core/bootstrap/plugin-lanes.ts+++ b/src/core/bootstrap/plugin-lanes.ts@@ -7,7 +7,7 @@*/import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';-import { codexHookCensus } from './codex-hooks.ts';+import { codexHookCensus, codexHookGroupRuns } from './codex-hooks.ts';import { classifyHarnessHook } from './hooks.ts';import { claudeSetupPaths } from '../setup/claude-code.ts';import { codexSetupPaths } from '../setup/codex.ts';@@ -25,12 +25,30 @@ import { CLAUDE_HOOK_SUBCOMMAND, claudeUserSettingsPath, codexConfigPath, codexH// codexBlockOwnsName: fail-open (null/false) on any read or parse error./**- * Marketplace-qualified id (`<name>@<marketplace>`) when an ENABLED codex- * plugin named `name` exists in the codex config, else null. Line-anchored+ * The gbrain plugin and its persona variants (plugin-variants/), which all+ * serve the `gbrain` MCP server, in fixed per-turn hook precedence: when+ * several are enabled, only the first one's hook runs (pluginHookYields).+ */+export const GBRAIN_PLUGIN_NAMES = ['gbrain', 'gbrain-coding', 'gbrain-daily'] as const;++const pluginNamesFor = (name: string): readonly string[] => (name === 'gbrain' ? GBRAIN_PLUGIN_NAMES : [name]);++/**+ * Marketplace-qualified id (`<plugin>@<marketplace>`) when an ENABLED codex+ * plugin providing server `name` exists in the codex config, else null (for+ * `gbrain`, the first enabled of GBRAIN_PLUGIN_NAMES). Line-anchored* table-header scan — a commented-out lookalike or an inline mention never* matches — followed by `enabled = true` before the next table header.*/export function codexPluginProvidesName(configPath: string, name: string): string | null {+ for (const plugin of pluginNamesFor(name)) {+ const id = codexPluginEnabled(configPath, plugin);+ if (id) return id;+ }+ return null;+}++function codexPluginEnabled(configPath: string, name: string): string | null {if (!existsSync(configPath)) return null;try {const lines = readFileSync(configPath, 'utf8').replace(/\r\n/g, '\n').split('\n');@@ -53,12 +71,21 @@ export function codexPluginProvidesName(configPath: string, name: string): strin}/**- * Marketplace-qualified id when an ENABLED Claude Code plugin named `name`- * exists in `~/.claude/settings.json` (`enabledPlugins`: `"<name>@<mkt>":- * true` — the shape verified on a live install), else null. User-level file- * only; project-scope enablement is out of best-effort scope.+ * Marketplace-qualified id when an ENABLED Claude Code plugin providing+ * server `name` exists in `~/.claude/settings.json` (`enabledPlugins`:+ * `"<plugin>@<mkt>": true` — the shape verified on a live install), else+ * null (for `gbrain`, the first enabled of GBRAIN_PLUGIN_NAMES). User-level+ * file only; project-scope enablement is out of best-effort scope.*/export function claudePluginProvidesName(settingsPath: string, name: string): string | null {+ for (const plugin of pluginNamesFor(name)) {+ const id = claudePluginEnabled(settingsPath, plugin);+ if (id) return id;+ }+ return null;+}++function claudePluginEnabled(settingsPath: string, name: string): string | null {if (!existsSync(settingsPath)) return null;try {const parsed = JSON.parse(readFileSync(settingsPath, 'utf8')) as {@@ -163,10 +190,17 @@ export function claudeAnyRegistrationExists(* (`gbrain setup`, `gbrain bootstrap harness`, a workspace bootstrap) already* wires this hook subcommand for the harness, so the event fires once. Claude Code: any gbrain-marked or* harness-lane entry in the user settings or the cwd's .claude settings;- * Codex: a setup or bootstrap group in CODEX_HOME/hooks.json. Fail-open: an- * unreadable file counts as not wired.+ * Codex: a setup or bootstrap group in CODEX_HOME/hooks.json that Codex runs+ * (trusted in config.toml and not disabled). A persona variant+ * (GBRAIN_PLUGIN, set by its manifest) also yields to an enabled plugin+ * earlier in GBRAIN_PLUGIN_NAMES. Fail-open: an unreadable file counts as+ * not wired.*/export function pluginHookYields(harness: string, subcommand: string, cwd: string): boolean {+ const rank = (GBRAIN_PLUGIN_NAMES as readonly string[]).indexOf(process.env.GBRAIN_PLUGIN ?? '');+ for (const plugin of GBRAIN_PLUGIN_NAMES.slice(0, Math.max(rank, 0))) {+ if (harness === 'codex' ? codexPluginEnabled(codexConfigPath(), plugin) : claudePluginEnabled(claudeUserSettingsPath(), plugin)) return true;+ }const receipt = harness === 'codex' ? codexSetupPaths('gbrain').receiptPath : claudeSetupPaths({ name: 'gbrain', scope: 'user' }).receiptPath;try {if ((JSON.parse(readFileSync(receipt, 'utf8')) as { consent?: { wiring_scope?: { value?: { hooks?: string } } } }).consent?.wiring_scope?.value?.hooks === 'none') return true;@@ -174,7 +208,10 @@ export function pluginHookYields(harness: string, subcommand: string, cwd: strinconst event = Object.entries(CLAUDE_HOOK_SUBCOMMAND).find(([, s]) => s === subcommand)?.[0];if (!event) return false;if (harness === 'codex') {- try { return codexHookCensus(codexHooksPath()).some((g) => g.event === event && g.lane !== 'other'); } catch { return false; }+ try {+ const hooksPath = codexHooksPath();+ return codexHookCensus(hooksPath).some((g) => g.event === event && g.lane !== 'other' && codexHookGroupRuns(hooksPath, codexConfigPath(), g));+ } catch { return false; }}for (const path of [claudeUserSettingsPath(), join(cwd, '.claude', 'settings.json'), join(cwd, '.claude', 'settings.local.json')]) {try {diff --git a/src/core/setup/hermes-turn-hook.ts b/src/core/setup/hermes-turn-hook.tsindex b28a364ee8..ff7f929607 100644--- a/src/core/setup/hermes-turn-hook.ts+++ b/src/core/setup/hermes-turn-hook.ts@@ -18,6 +18,7 @@import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';+import { acquireNativeLockSync } from '../persistence/native-lock.ts';import { loadBoundedYaml } from '../data-frontmatter.ts';import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';import { renderBrainFirstTurnRule, writeUnlessChanged, type BrainFirstAccess } from './brain-first.ts';@@ -54,20 +55,40 @@ function readAllowlist(path: string): Allowlist {const approves = (e: Record<string, unknown>, command: string) => e.event === EVENT && e.command === command;+/**+ * Read-modify-write the allowlist under Hermes's own lock: an exclusive+ * flock(2) on the sibling `shell-hooks-allowlist.json.lock` (Hermes's+ * agent/shell_hooks.py `_locked_update_approvals`), so an approval Hermes+ * records at the same moment is never lost. Fails closed: a lock held past+ * the wait, or no lock primitive on this host, throws and writes nothing.+ */+function withAllowlistLock(path: string, update: (list: Allowlist) => Allowlist | null): void {+ const lockPath = `${path}.lock`;+ const lock = acquireNativeLockSync(lockPath, { timeoutMs: 3000 });+ if (!lock) throw new Error(`Hermes holds ${lockPath}; ${ALLOWLIST} was not changed. Run setup again once Hermes is idle`);+ try {+ const next = update(readAllowlist(path));+ if (next) atomicWriteTextFile(path, `${JSON.stringify(next, null, 2)}\n`, { freshMode: 0o600 });+ } finally {+ lock.release();+ }+}+function approve(hermesHome: string, command: string): void {- const path = join(hermesHome, ALLOWLIST);- const list = readAllowlist(path);- if (list.approvals.some((e) => approves(e, command))) return;- list.approvals.push({ event: EVENT, command, approved_at: new Date().toISOString(), script_mtime_at_approval: null });- atomicWriteTextFile(path, `${JSON.stringify(list, null, 2)}\n`, { freshMode: 0o600 });+ withAllowlistLock(join(hermesHome, ALLOWLIST), (list) => {+ if (list.approvals.some((e) => approves(e, command))) return null;+ list.approvals.push({ event: EVENT, command, approved_at: new Date().toISOString(), script_mtime_at_approval: null });+ return list;+ });}function revoke(hermesHome: string, command: string): void {const path = join(hermesHome, ALLOWLIST);if (!existsSync(path)) return;- const list = readAllowlist(path);- const kept = list.approvals.filter((e) => !approves(e, command));- if (kept.length !== list.approvals.length) atomicWriteTextFile(path, `${JSON.stringify({ ...list, approvals: kept }, null, 2)}\n`, { freshMode: 0o600 });+ withAllowlistLock(path, (list) => {+ const kept = list.approvals.filter((e) => !approves(e, command));+ return kept.length === list.approvals.length ? null : { ...list, approvals: kept };+ });}/** Write or update the hook (accepted decision). Never throws: anything gbrain cannot edit safely is printed to add by hand. */diff --git a/test/bootstrap-plugin-lane.serial.test.ts b/test/bootstrap-plugin-lane.serial.test.tsindex 9e06330b54..751961e423 100644--- a/test/bootstrap-plugin-lane.serial.test.ts+++ b/test/bootstrap-plugin-lane.serial.test.ts@@ -34,6 +34,7 @@ import {} from '../src/core/bootstrap/harness.ts';import { initState, setAnswer, readBackHash, confirm } from '../src/core/bootstrap/interview.ts';import { readReceipt } from '../src/core/bootstrap/format.ts';+import { REGISTRATION_SURFACE } from '../src/core/mcp-registration.ts';const REQUIRED_ANSWERS: Record<string, string> = {AGENT_NAME: 'Lanekeeper',@@ -245,6 +246,47 @@ describe('runHooks plugin-lane skip (serial: env fixtures)', () => {expect(add!.join(' ')).toContain('serve --surface starter');}, 30_000);+ test('codex + an enabled persona variant (gbrain-coding) → the MCP substep skips too (#7963)', async () => {+ writeFileSync(join(codexHome, 'config.toml'), '[plugins."gbrain-coding@gbrain"]\nenabled = true\n');+ const { runner, calls } = makeRunner();+ const r = await capture(() =>+ runBootstrap(['hooks', '--workspace', ws, '--harness', 'codex', '--gbrain-bin', process.execPath], { runner }),+ );+ expect(r.result).toBe(0);+ expect(r.out).toContain("the 'gbrain-coding@gbrain' plugin already provides the gbrain MCP server");+ expect(calls.some((c) => c[0] === 'codex')).toBe(false);+ }, 30_000);++ test('replacing a registration whose surface cannot be read re-adds it at full, not the default (#7962)', async () => {+ writeFileSync(join(codexHome, 'config.toml'), '[projects."/tmp/x"]\ntrust_level = "trusted"\n');+ const calls: string[][] = [];+ let lastAdd: string[] | null = null;+ const runner = async (argv: string[]) => {+ calls.push(argv);+ if (argv[0] !== 'codex') return { code: 0, stdout: '', stderr: '' };+ if (argv[2] === 'add') {+ if (!lastAdd) { lastAdd = argv; return { code: 1, stdout: '', stderr: 'Error: server gbrain already exists' }; }+ lastAdd = argv;+ return { code: 0, stdout: '', stderr: '' };+ }+ if (argv[2] === 'get') return { code: 0, stdout: calls.some((c) => c[2] === 'remove') ? lastAdd!.join(' ') : 'gbrain\n transport: stdio\n command: /opt/elsewhere/gbrain-wrapper\n', stderr: '' };+ return { code: 0, stdout: '', stderr: '' };+ };+ const r = await capture(() =>+ runBootstrap(['hooks', '--workspace', ws, '--harness', 'codex', '--gbrain-bin', process.execPath], { runner }),+ );+ expect(r.result).toBe(0);+ const adds = calls.filter((c) => c[0] === 'codex' && c[2] === 'add');+ expect(adds).toHaveLength(2);+ expect(adds[0]!.join(' ')).toContain('serve --surface starter');+ expect(adds[1]!.join(' ')).toContain('serve --surface full');+ }, 30_000);++ test('hooks --help names the real default surface (#7962)', async () => {+ const r = await capture(() => runBootstrap(['hooks', '--help']));+ expect(r.out + r.err).toContain(`--surface ${REGISTRATION_SURFACE} unless given`);+ });+test('codex + plugin + --mcp-even-if-plugin → registration forced through', async () => {writeFileSync(join(codexHome, 'config.toml'), ENABLED_PLUGIN_TOML);const { runner, calls } = makeRunner();diff --git a/test/brain-first-turn-rule.test.ts b/test/brain-first-turn-rule.test.tsindex 8bf4ed6dc3..7a15b7189d 100644--- a/test/brain-first-turn-rule.test.ts+++ b/test/brain-first-turn-rule.test.ts@@ -154,6 +154,54 @@ describe('per-turn rule: Hermes pre_llm_call hook in config.yaml', () => {expect(approvals(d)).toEqual([other]);});+ // Hermes's own writer (agent/shell_hooks.py _locked_update_approvals): an+ // exclusive fcntl.flock on the sibling .lock around read-modify-write.+ const HERMES_WRITER = [+ 'import fcntl, json, os, sys, time',+ 'home, hold = sys.argv[1], float(sys.argv[2])',+ 'path = os.path.join(home, "shell-hooks-allowlist.json")',+ 'with open(path + ".lock", "a+") as lock:',+ ' fcntl.flock(lock.fileno(), fcntl.LOCK_EX)',+ ' print("locked", flush=True)',+ ' data = json.load(open(path, encoding="utf-8-sig")) if os.path.exists(path) else {"approvals": []}',+ ' time.sleep(hold)',+ ' data["approvals"].append({"event": "post_tool_call", "command": "/opt/hermes-side", "approved_at": "x", "script_mtime_at_approval": None})',+ ' open(path + ".tmp", "w").write(json.dumps(data))',+ ' os.replace(path + ".tmp", path)',+ ' fcntl.flock(lock.fileno(), fcntl.LOCK_UN)',+ ].join('\n');+ async function hermesHoldsLock(d: string, holdSecs: number) {+ const proc = Bun.spawn(['python3', '-c', HERMES_WRITER, d, String(holdSecs)], { stdout: 'pipe', stderr: 'inherit' });+ const reader = proc.stdout.getReader();+ const first = await reader.read();+ expect(new TextDecoder().decode(first.value)).toContain('locked');+ reader.releaseLock();+ return proc;+ }++ test.skipIf(!Bun.which('python3'))('the approval waits for Hermes\'s allowlist flock, so an approval Hermes records at the same moment survives', async () => {+ const d = hermes('model: x\n');+ const proc = await hermesHoldsLock(d, 0.8);+ expect(syncHermesTurnHook({ hermesHome: d, access, dryRun: false }).action).toBe('write');+ expect(await proc.exited).toBe(0);+ expect(approvals(d).map((a) => a.command)).toEqual(['/opt/hermes-side', cmd]);+ });++ test.skipIf(!Bun.which('python3'))('a flock Hermes holds past the wait refuses loudly and leaves the allowlist untouched', async () => {+ const d = hermes('model: x\n', [{ event: 'pre_tool_call', command: '/usr/bin/true' }]);+ const before = readFileSync(join(d, 'shell-hooks-allowlist.json'), 'utf8');+ const proc = await hermesHoldsLock(d, 8);+ try {+ const o = syncHermesTurnHook({ hermesHome: d, access, dryRun: false });+ expect(o.action).toBe('print');+ expect(o.detail).toContain('shell-hooks-allowlist.json.lock');+ expect(readFileSync(join(d, 'shell-hooks-allowlist.json'), 'utf8')).toBe(before);+ } finally {+ proc.kill();+ await proc.exited;+ }+ });+test('new rule text rewrites the block in place and moves the approval to the new command', () => {const d = hermes('');syncHermesTurnHook({ hermesHome: d, access, dryRun: false });diff --git a/test/plugin-turn-hook.test.ts b/test/plugin-turn-hook.test.tsindex ed03e811ae..5d3d51b12b 100644--- a/test/plugin-turn-hook.test.ts+++ b/test/plugin-turn-hook.test.ts@@ -9,13 +9,13 @@* CLAUDE_CONFIG_DIR and GBRAIN_HOME.*/import { afterAll, describe, expect, test } from 'bun:test';-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { buildClaudeHookCommand } from '../src/core/bootstrap/hooks.ts';-import { codexSetupHookGroup } from '../src/core/bootstrap/codex-hooks.ts';+import { codexSetupHookGroup, codexSetupTrustEntry } from '../src/core/bootstrap/codex-hooks.ts';import { CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS } from '../src/core/bootstrap/host-specs.ts';-import { pluginHookYields } from '../src/core/bootstrap/plugin-lanes.ts';+import { claudePluginProvidesName, codexPluginProvidesName, enabledPluginLanes, pluginHookYields } from '../src/core/bootstrap/plugin-lanes.ts';import { runHook } from '../src/commands/hook.ts';import { harnessWiringCheck, instructionBlockUpgradeHints } from '../src/commands/doctor/checks/harness-wiring.ts';import { renderBrainFirstTurnRule } from '../src/core/setup/brain-first.ts';@@ -34,15 +34,15 @@ const tail = (command: string, bin: string) => command.slice(command.indexOf(bindescribe('plugin manifests declare the hook setup installs', () => {const claudeSetup = buildClaudeHookCommand('/x/gbrain', 'UserPromptSubmit', {});const codexSetup = codexSetupHookGroup('/x/gbrain', 'UserPromptSubmit', {}).hooks[0]!;- for (const dir of ['.', 'plugin-variants/gbrain-coding', 'plugin-variants/gbrain-daily']) {- test(`${dir}: Claude Code and Codex UserPromptSubmit, setup's subcommand and timeout, through the launcher`, () => {+ for (const [dir, identity] of [['.', ''], ['plugin-variants/gbrain-coding', 'GBRAIN_PLUGIN=gbrain-coding '], ['plugin-variants/gbrain-daily', 'GBRAIN_PLUGIN=gbrain-daily ']]) {+ test(`${dir}: Claude Code and Codex UserPromptSubmit, setup's subcommand and timeout, through the launcher, naming its variant`, () => {expect(existsSync(join(ROOT, dir, '.agents', 'gbrain-launcher'))).toBe(true);expect(json(join(dir, '.claude-plugin', 'plugin.json')).hooks).toEqual({ UserPromptSubmit: [{ hooks: [{ type: 'command',- command: `env GBRAIN_HOOK_LANE=plugin "\${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher" ${tail(claudeSetup, '/x/gbrain')}`,+ command: `env GBRAIN_HOOK_LANE=plugin ${identity}"\${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher" ${tail(claudeSetup, '/x/gbrain')}`,timeout: CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS.UserPromptSubmit }] }] });// Codex's inline form is a whole hooks.json document (the `hooks` wrapper); Claude Code's is the bare event map.expect(json(join(dir, '.codex-plugin', 'plugin.json')).hooks).toEqual({ hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command',- command: `env GBRAIN_HOOK_LANE=plugin "\${PLUGIN_ROOT}/.agents/gbrain-launcher" ${tail(codexSetup.command, '/x/gbrain')}`,+ command: `env GBRAIN_HOOK_LANE=plugin ${identity}"\${PLUGIN_ROOT}/.agents/gbrain-launcher" ${tail(codexSetup.command, '/x/gbrain')}`,timeout: codexSetup.timeout }] }] } });});}@@ -57,7 +57,7 @@ function box(): Box {mkdirSync(home, { recursive: true });return { root, home, env: {HOME: home, GBRAIN_HOME: home, CODEX_HOME: join(root, 'codex'), CLAUDE_CONFIG_DIR: join(root, 'claude'), XDG_CONFIG_HOME: join(root, 'xdg'),- GBRAIN_HOOK_LANE: 'plugin', GBRAIN_AGENT_INSTRUCTIONS: undefined, GBRAIN_HOOKS: undefined, GBRAIN_SURFACE: undefined, GBRAIN_SOURCE: undefined,+ GBRAIN_HOOK_LANE: 'plugin', GBRAIN_PLUGIN: undefined, GBRAIN_AGENT_INSTRUCTIONS: undefined, GBRAIN_HOOKS: undefined, GBRAIN_SURFACE: undefined, GBRAIN_SOURCE: undefined,CLAUDECODE: undefined, CLAUDE_CODE_ENTRYPOINT: undefined, CODEX_SANDBOX: undefined, CODEX_CI: undefined, OPENCODE: undefined, OPENCODE_PID: undefined,} };}@@ -152,9 +152,145 @@ describe('plugin lane: one hook per event, rule only with a block', () => {writeFileSync(join(b.home, '.gbrain', 'agent-instructions.json'), JSON.stringify({ version: 1, entries: [{ harness: 'codex', status: 'installed',path: join(b.home, 'AGENTS.md'), block_version: 2, access: { kind: 'mcp', server: 'gbrain' }, writer: 'test', created_file: false, updated_at: '2026-10-28T00:00:00.000Z' }] }));expect(JSON.parse((await userPrompt(b, 'codex')).trim()).hookSpecificOutput.additionalContext).toBe(RULE);- writeFileSync(join(b.env.CODEX_HOME!, 'hooks.json'), JSON.stringify({ hooks: { UserPromptSubmit: [codexSetupHookGroup('/opt/g', 'UserPromptSubmit', {})] } }));+ const group = codexSetupHookGroup('/opt/g', 'UserPromptSubmit', {});+ const hooksPath = join(b.env.CODEX_HOME!, 'hooks.json');+ writeFileSync(hooksPath, JSON.stringify({ hooks: { UserPromptSubmit: [group] } }));+ const trust = codexSetupTrustEntry(hooksPath, 'UserPromptSubmit', 0, group);+ writeFileSync(join(b.env.CODEX_HOME!, 'config.toml'), `[hooks.state."${trust.key}"]\ntrusted_hash = "${trust.trusted_hash}"\n`);expect(await userPrompt(b, 'codex')).toBe('');writeFileSync(join(b.env.CODEX_HOME!, 'hooks.json'), '{ not json');await withEnv(b.env, async () => { expect(pluginHookYields('codex', 'user-prompt', b.root)).toBe(false); });});});++describe('Codex: yield only to a setup group Codex runs (#7963)', () => {+ test('an untrusted, stale-hash or disabled setup group leaves the plugin hook running; a trusted one wins', async () => {+ const b = box();+ mkdirSync(b.env.CODEX_HOME!, { recursive: true });+ mkdirSync(join(b.home, '.gbrain'), { recursive: true });+ writeFileSync(join(b.home, '.gbrain', 'agent-instructions.json'), JSON.stringify({ version: 1, entries: [{ harness: 'codex', status: 'installed',+ path: join(b.home, 'AGENTS.md'), block_version: 2, access: { kind: 'mcp', server: 'gbrain' }, writer: 'test', created_file: false, updated_at: '2026-10-28T00:00:00.000Z' }] }));+ const hooksPath = join(b.env.CODEX_HOME!, 'hooks.json');+ const configPath = join(b.env.CODEX_HOME!, 'config.toml');+ const other = { hooks: [{ type: 'command', command: 'echo unrelated', timeout: 5 }] };+ const group = codexSetupHookGroup('/opt/g', 'UserPromptSubmit', {});+ writeFileSync(hooksPath, JSON.stringify({ hooks: { UserPromptSubmit: [other, group] } }));+ const trust = codexSetupTrustEntry(hooksPath, 'UserPromptSubmit', 1, group);+ const rule = async () => JSON.parse((await userPrompt(b, 'codex')).trim()).hookSpecificOutput.additionalContext;++ expect(await rule()).toBe(RULE);+ writeFileSync(configPath, `[hooks.state."${trust.key}"]\ntrusted_hash = "sha256:${'0'.repeat(64)}"\n`);+ expect(await rule()).toBe(RULE);+ writeFileSync(configPath, `[hooks.state."${trust.key}"]\nenabled = false\ntrusted_hash = "${trust.trusted_hash}"\n`);+ expect(await rule()).toBe(RULE);+ writeFileSync(configPath, `[hooks.state."${trust.key.replace(':1:0', ':0:0')}"]\ntrusted_hash = "${trust.trusted_hash}"\n`);+ expect(await rule()).toBe(RULE);+ writeFileSync(configPath, `[hooks.state."${trust.key}"]\ntrusted_hash = "${trust.trusted_hash}"\n`);+ expect(await userPrompt(b, 'codex')).toBe('');+ writeFileSync(configPath, '[hooks.state\nnot toml');+ await withEnv(b.env, async () => { expect(pluginHookYields('codex', 'user-prompt', b.root)).toBe(false); });+ });+});++describe('persona variants count as the gbrain plugin, and only one plugin hook fires (#7963)', () => {+ test('Claude Code: a variant alone is a plugin lane; the variants yield to an enabled higher-precedence plugin', async () => {+ const b = box();+ claudeSettings(b, { enabledPlugins: { 'gbrain-daily@gbrain': true } });+ const settings = join(b.env.CLAUDE_CONFIG_DIR!, 'settings.json');+ expect(claudePluginProvidesName(settings, 'gbrain')).toBe('gbrain-daily@gbrain');+ expect(claudePluginProvidesName(settings, 'other-server')).toBeNull();+ await withEnv(b.env, async () => {+ expect(enabledPluginLanes('gbrain')).toEqual([{ harness: 'claude-code', plugin: 'gbrain-daily@gbrain' }]);+ for (const plugin of [undefined, 'gbrain-coding', 'gbrain-daily']) {+ await withEnv({ GBRAIN_PLUGIN: plugin }, async () => { expect(pluginHookYields('claude-code', 'user-prompt', b.root)).toBe(false); });+ }+ });+ claudeSettings(b, { enabledPlugins: { 'gbrain-daily@gbrain': true, 'gbrain-coding@gbrain': true, 'gbrain@gbrain': false } });+ expect(claudePluginProvidesName(settings, 'gbrain')).toBe('gbrain-coding@gbrain');+ await withEnv(b.env, async () => {+ await withEnv({ GBRAIN_PLUGIN: 'gbrain-daily' }, async () => { expect(pluginHookYields('claude-code', 'user-prompt', b.root)).toBe(true); });+ await withEnv({ GBRAIN_PLUGIN: 'gbrain-coding' }, async () => { expect(pluginHookYields('claude-code', 'user-prompt', b.root)).toBe(false); });+ });+ claudeSettings(b, { enabledPlugins: { 'gbrain-coding@gbrain': true, 'gbrain@gbrain': true } });+ await withEnv(b.env, async () => {+ await withEnv({ GBRAIN_PLUGIN: 'gbrain-coding' }, async () => { expect(pluginHookYields('claude-code', 'user-prompt', b.root)).toBe(true); });+ await withEnv({ GBRAIN_PLUGIN: undefined }, async () => { expect(pluginHookYields('claude-code', 'user-prompt', b.root)).toBe(false); });+ });+ });++ test('Codex: [plugins."<variant>@<mkt>"] counts, and the lower variant yields', async () => {+ const b = box();+ mkdirSync(b.env.CODEX_HOME!, { recursive: true });+ const config = join(b.env.CODEX_HOME!, 'config.toml');+ writeFileSync(config, '[plugins."gbrain-daily@gbrain"]\nenabled = true\n');+ expect(codexPluginProvidesName(config, 'gbrain')).toBe('gbrain-daily@gbrain');+ await withEnv(b.env, async () => {+ expect(enabledPluginLanes('gbrain')).toEqual([{ harness: 'codex', plugin: 'gbrain-daily@gbrain' }]);+ await withEnv({ GBRAIN_PLUGIN: 'gbrain-daily' }, async () => { expect(pluginHookYields('codex', 'user-prompt', b.root)).toBe(false); });+ });+ writeFileSync(config, '[plugins."gbrain-daily@gbrain"]\nenabled = true\n\n[plugins."gbrain-coding@gbrain"]\nenabled = true\n');+ expect(codexPluginProvidesName(config, 'gbrain')).toBe('gbrain-coding@gbrain');+ await withEnv(b.env, async () => {+ await withEnv({ GBRAIN_PLUGIN: 'gbrain-daily' }, async () => { expect(pluginHookYields('codex', 'user-prompt', b.root)).toBe(true); });+ await withEnv({ GBRAIN_PLUGIN: 'gbrain-coding' }, async () => { expect(pluginHookYields('codex', 'user-prompt', b.root)).toBe(false); });+ });+ });+});++describe('the plugin launcher on the per-turn hook (#7963)', () => {+ const LAUNCHER = join(ROOT, '.agents', 'gbrain-launcher');+ const launch = (env: Record<string, string>, args: string[]) => {+ const r = Bun.spawnSync(['/bin/sh', LAUNCHER, ...args], { env: { PATH: '/usr/bin:/bin', ...env }, stdout: 'pipe', stderr: 'pipe' });+ return { code: r.exitCode, stdout: r.stdout.toString(), stderr: r.stderr.toString() };+ };+ function fakeCli(b: Box, version: string): { bin: string; calls: () => string[] } {+ const bin = join(b.root, 'fake-gbrain');+ const log = join(b.root, 'calls.log');+ writeFileSync(bin, `#!/bin/sh\necho "$*" >> '${log}'\nif [ "$1" = --version ]; then echo "gbrain ${version}"; exit 0; fi\necho "ran $*"\n`);+ chmodSync(bin, 0o755);+ const mtime = new Date(Date.now() - 60_000);+ utimesSync(bin, mtime, mtime);+ writeFileSync(log, '');+ return { bin, calls: () => readFileSync(log, 'utf8').split('\n').filter(Boolean) };+ }++ test('no gbrain binary: hook exits 0 with no output; serve keeps exit 127 and the recovery text', () => {+ const b = box();+ expect(launch({ HOME: b.home }, ['hook', 'user-prompt'])).toEqual({ code: 0, stdout: '', stderr: '' });+ expect(launch({ HOME: b.home, GBRAIN_BIN: join(b.root, 'missing') }, ['hook', 'user-prompt'])).toEqual({ code: 0, stdout: '', stderr: '' });+ const serve = launch({ HOME: b.home }, ['serve', '--surface', 'full']);+ expect(serve.code).toBe(127);+ expect(serve.stderr).toContain('gbrain binary not found');+ expect(launch({ HOME: b.home, GBRAIN_BIN: join(b.root, 'missing') }, ['serve']).code).toBe(127);+ });++ 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 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']);+ expect(launch(env, ['hook', 'user-prompt'])).toEqual({ code: 0, stdout: '', stderr: '' });+ expect(cli.calls()).toEqual(['--version']);+ expect(existsSync(join(b.home, '.gbrain', 'cache', 'plugin-hook-cli'))).toBe(true);+ // Setup's own hook (no plugin lane) still runs on the old CLI.+ expect(launch({ HOME: b.home, GBRAIN_BIN: cli.bin }, ['hook', 'user-prompt']).stdout).toBe('ran hook user-prompt\n');+ // 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');+ 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');+ expect(upgraded.calls()).toEqual(['--version', 'hook user-prompt', 'hook user-prompt']);+ });++ test('GBRAIN_HOME places the probe cache; a lane-aware CLI runs the hook', () => {+ const b = box();+ const cli = fakeCli(b, '0.61.0.0');+ 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`);+ });+});