Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(setup): gbrain setup codex with hash-owned MCP, hooks and trust entries

garrytana478967a244b
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 43a2bd1d11..1483163c60 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -107,7 +107,8 @@ comes from agent-authored `## Facts` fences and the `remember` verb.
## Step 3: Create the Brain
-**If you are Claude Code**, one command does Step 3 and the MCP registration:
+**If you are Claude Code or Codex**, one command does Step 3 and the MCP registration
+(use `codex` in place of `claude-code` on Codex):
```bash
gbrain setup claude-code --dry-run --json # the resolved target; writes nothing
diff --git a/README.md b/README.md
index bf91113d60..cdd555f054 100644
--- a/README.md
+++ b/README.md
@@ -100,14 +100,14 @@ before restarting services with this version.
> Run `gbrain apply-migrations --yes --no-autopilot-install`; exit 1 means it's still
> behind: run `gbrain doctor --json`, not `--yes` again.
-**Claude Code, fastest path:**
+**Claude Code or Codex, fastest path:**
```bash
bun install -g github:garrytan/gbrain
-gbrain setup claude-code # --dry-run previews, --remove undoes
+gbrain setup claude-code # or codex; --dry-run previews, --remove undoes
```
-`setup` shows the brain, source, launcher and owner it resolved before writing, runs `gbrain init --pglite --no-embedding` only when no brain exists, writes the stdio MCP entry and read-context hooks (owned by hash) and smoke-tests them. Capture and providers stay off unless accepted; a hosted brain keeps `gbrain connect --install`. [Setup guide](docs/guides/setup.md).
+`setup` shows the brain, source, launcher and owner it resolved before writing, runs `gbrain init --pglite --no-embedding` only when no brain exists, writes the stdio MCP entry and read-context hooks (owned by hash, plus Codex hook trust) and smoke-tests them. Capture and providers stay off unless accepted; a hosted brain keeps `gbrain connect --install`. [Setup guide](docs/guides/setup.md).
Start with the agent you already use. For Grok Bot and Muse, the dedicated guides above install an isolated launcher, repairable runtime, and memory in a verified persistent directory. For a coding agent, paste:
@@ -182,7 +182,7 @@ The agent starts with keyless memory and verifies it. API keys, automatic captur
### Lighter ways in
-**Just want a memory for your coding agent — no identity, no repo.** On Claude Code run `gbrain setup claude-code` (above). By hand: `gbrain init --pglite --no-embedding`, then `codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full` (`claude mcp add` takes the same argv; `--surface verbs` or `starter` for a harness that caps its tool count). Saved memories are brain-wide by default; pass `visibility: "private"` for local-only facts.
+**Just want a memory for your coding agent — no identity, no repo.** On Claude Code or Codex use `gbrain setup` (above). By hand: `gbrain init --pglite --no-embedding`, then `codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full` (`claude mcp add` takes the same argv; `--surface verbs` or `starter` for a harness that caps its tool count). Saved memories are brain-wide by default; pass `visibility: "private"` for local-only facts.
**Already have a brain on a remote host** (OpenClaw, Hermes, or any `gbrain serve --http`)? Point your laptop agents at it with one command each — `--install` wires it up and smoke-tests the token before handoff:
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.md
index 6fc57404ff..3c9bbaad10 100644
--- a/docs/architecture/key-files/agent-bootstrap.md
+++ b/docs/architecture/key-files/agent-bootstrap.md
@@ -18,18 +18,19 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/bootstrap/repo.ts` / `attach.ts` / `uninstall.ts` — private-repo lifecycle. `createPrivateRepo`: gh gates, slugified name probe, `gh repo create --private --source --push`, privacy verified via `gh api .private` (rate-limit/5xx is VERIFY_UNAVAILABLE, distinct from not-private) before any push, idempotency keyed off the remote URL. A pre-existing origin is adopted (disposition 'adopted') when the authed gh user owns it, there's no recorded `repo_url`, and it is SAFE — empty or already carrying our history (`assertAdoptableOrigin`; a foreign-content repo is refused `ORIGIN_NOT_EMPTY`, never a silent no-op); this is the create-repo-first path. Org-owned origins and anything else are refused and pointed at attach. Repo-local git identity is set in both create and adopt paths before commit; `repo_url` is recorded only after a successful push. `attachWorkspace` (machine two): requires an `initialized` manifest, writes this machine's receipt, returns structured wiring steps. `uninstallWorkspace`: receipt-keyed, refuses under a live serve (read-only lock probe — never opens the engine), removes exactly receipt-recorded paths + marker-keyed host entries, keeps the brain unless `--delete-brain` AND bootstrap created it; never wholesale-deletes the gbrain home. All gh/git through an injectable ExecRunner seam.
- `src/core/bootstrap/hooks.ts` + `host-specs.ts` — host wiring. `host-specs.ts` is the ONE module owning host-format assumptions (dated spec targets with verifiedAt + doc references: claude-code hooks/settings shapes incl. the 10,000-char hook-output cap and the five hook events; codex mcp-add argv, the streamable-HTTP `url` + `http_headers = { Authorization = "Bearer <t>" }` config shape (loads on codex-cli 0.147.x and 0.149.x; inline `bearer_token` is rejected at config load by >=0.149), `codexConfigPath()` honoring CODEX_HOME, `claudeUserSettingsPath()` honoring CLAUDE_CONFIG_DIR/$HOME explicitly — Bun's homedir() ignores a remapped HOME, which would point sandboxed writers at the operator's real settings; the shared resolution lives in the private `claudeConfigBase()` (CLAUDE_CONFIG_DIR-else-$HOME-else-homedir(), the directory playing the role of `~/.claude` — NOT for `claudeUserMcpConfigPath`, whose default lives at the HOME level as `~/.claude.json`), which also feeds `claudeUserSkillsDir()`/`claudeProjectSkillsDir()` (native SKILL.md discovery, the harness-bridge install targets; user scope attested, project scope provisional-from-docs) — and the opencode shapes: `opencodeConfigDir`/`opencodeGlobalConfigPath` (XDG-only resolution; the `.jsonc` name preferred for parity with `opencode mcp add`; OPENCODE_CONFIG/_CONFIG_DIR/_CONFIG_CONTENT deliberately NOT honored — observed INERT in opencode 1.18.18, honoring them would write registrations into a file opencode never reads), `opencodeProjectConfigPath`, `opencodeGlobalSiblingPath` (the OTHER member of the global filename pair — writers reconcile `mcp.<name>` across it because opencode merges both), and `OPENCODE_HAS_HOOKS=false` — 'gbrain does not wire opencode's plugin/event system yet', not 'opencode has no hooks'). The settings writers are path+marker parameterized: `writeClaudeHooksAt`/`removeClaudeHooksAt` take an explicit settings file and a marker VALUE (workspace installs stamp `bootstrap-v1` in `.claude/settings.local.json`; harness installs stamp `bootstrap-harness-v1` in user-scope settings or a --project dir — the two coexist and each removal strips only its own; `refuseOnForeignGbrainMarker` blocks same-file double-wiring), fail-closed on broken JSON (a settings file that doesn't parse THROWS with the path — a writer must never relocate or overwrite a config it can't read), mode-preserving realpath-resolved atomic writes (dotfile symlinks survive), and fixed-or-timestamped backups. `addPermissionsAllowEntry`/`removePermissionsAllowEntry` manage the harness lane's `mcp__<name>` headless pre-approval with set semantics and NO marker (ownership rides the harness receipt; foreign entries always survive); the add path fails CLOSED when an existing `permissions` key or `permissions.allow` carries a shape it doesn't understand (host security policy is never rewritten on a guess), while removal leaves shapes it can't read untouched and reports nothing-to-remove. `registerClaudeMcp`/`registerCodexMcp` build argv only (Claude Code takes `--scope`, project default; Codex has no scope flag — `codex mcp add` is always user-global; `-e`/`--env GBRAIN_SOURCE` so MCP writes land in the workspace source, and the serve argv from `stdioServeArgv` in `src/core/mcp-registration.ts`: `--surface starter` by default so a pre-existing `mcp_surface: verbs` config row can't narrow the registration, or the `surface` the caller passes — `bootstrap hooks --surface`, or an existing entry's form carried over on replacement, `null` meaning a bare `serve`). `bootstrap hooks` never narrows: a matching registration is kept, `verifyMcpTargetsWorkspace` returns the existing entry's surface (`registeredSurface`) and the mismatch re-add keeps it, and the opencode writer keeps the existing command's form unless `--surface` is given. The opencode workspace lane execs NOTHING — registration is the direct `opencode-json.ts` write with an INVERTED scope default (user-global; opencode spawns project-config servers with no trust prompt, so `MCP_SCOPE=project` is an explicit opt-in that writes the committed-candidate `opencode.json` with a PATH-resolved command and prints the sharing warning), verification is config parse-back + a best-effort `opencode mcp list --pure` probe — the probe spawns via a held Bun.spawn handle from a fresh EMPTY temp-dir cwd (never the invoking cwd: opencode merges a project opencode.json from cwd and spawns its servers with no trust prompt), is SKIPPED entirely for project scope (printed note; parse-back is authoritative) and on plugin-bearing configs (`mcp list` is a code-execution surface), and on timeout actually kills the child (SIGTERM → SIGKILL, bounded pipe drain, code 124 into the could-not-confirm branch; `probeSpawn` is the injectable seam). User-scope writes also reconcile the SIBLING global filename first (ours → removed with a note; foreign → refuse naming both files) so a merge-shadow registration can never survive. `detectHarness` probes `OPENCODE`/`OPENCODE_PID` (set in opencode's bash-tool children, observed 1.18.18). `ClaudeHookEnv.GBRAIN_SEAT` (#4618) renders `GBRAIN_SEAT=<label>` into local-carrier hook commands (never the committed carrier); `writeClaudeHooksAt` keeps the seat a prior install of the same marker rendered when the caller passes none, and `''` clears it. `parseSeatFlags` validates `--seat <label>` / `--no-seat` for `bootstrap hooks` and `bootstrap harness` and returns a `note` where a seat cannot be rendered (codex, opencode, the cloud committed carrier). Pinned by `test/bootstrap-seat.serial.test.ts`. Harness-lane hook ownership does not rest on the marker alone: Claude Code can drop unknown keys when it rewrites settings.json, so `parseClaudeHookCommand` (the inverse of `buildClaudeHookCommand`: shellQuote-aware word split, env keys limited to the four the builder writes, each at most once, an absolute launcher, nothing after `hook <sub>`, and a re-render that must equal the input) feeds `classifyHarnessHook(entry, event, identity)` → `marked` / `command` (unmarked, exactly the harness hook for THAT event, launcher/source/seat inside a `HarnessHookIdentity`, no GBRAIN_HOME) / `unowned` (harness-looking under a wired event but edited or another install's; never deleted) / null. `harnessHookIdentity(receipt, target, current)` merges the running install with the receipt's recorded `launcher`/`seat` and source binding (seats constrain only when recorded). `writeClaudeHooksAt({identity})` replaces owned unmarked entries like marked ones (one entry per event on re-run, seat carried from marked then owned entries) and notes `harness_hook_unowned` lookalikes; `removeClaudeHooksAt(path, marker, {identity, dryRun})` returns `unmarked` (event + why, never command text) and `unowned` events; `scanHarnessHookCarrier` is the read-only per-event census (doctor, `--status`, the cross-HOME guard with identity `'any'`); `groupsCarryGbrainHook` feeds `hook_carrier_overlap`. The workspace lane (bootstrap-v1) keys on the marker alone. Pinned by `test/bootstrap-harness-hook-ownership.test.ts`. `hookEntryHash` (sha256 over `type`, `command`, `timeout`; the marker excluded, so a dropped marker keeps the hash) backs the opt-in `ownedEntryHashes` option on both writers: with it a marker match alone never replaces or removes an entry, edited marked entries come back in `preserved`, and unmarked entries with an owned hash are still ours (`gbrain setup`); without it every existing caller keeps marker-keyed ownership.
- `src/core/bootstrap/harness-hooks.ts` — the receipt-aware glue for harness hook entries without their marker: `removeHarnessHooksTarget` (one hooks target: owned marked + unmarked entries removed and listed by event; a surviving lookalike prints the `harness_hook_unowned` notice block with `next: tell_user_to_run` and throws so the target stays failed and `--remove` exits 1), `previewHarnessRemoval` (`--remove --dry-run`: every target's would-be action, nothing written, receipt untouched), `harnessHooksPresent` (the cross-HOME `--project` guard: marked, unmarked or edited-by-shape `unowned` entries, any install; W4.8) and `harnessHookCarrierStatus` (`--status` text line + `hook_carriers` JSON).
-- `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.
+- `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/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/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`.
+- `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`.
-- `src/core/bootstrap/adopted-connections.ts` + `adopt-connection.ts` — an operator-managed Codex PROJECT connection (`<workspace>/.codex/config.toml` `[mcp_servers.<name>]`, streamable HTTP logged in with `codex mcp login`, or stdio) is not a bootstrap-owned registration, so the `wire` phase in `status.ts` reads it through `adoptedConnectionState`: `detected` (the table exists, nothing proves it works) is `partial` with the adopt hint, `adopted` is `done`, `drifted` (fingerprint changed, table gone, file unparsable) is `partial` with a re-adopt hint, `none` leaves the receipt/hook detectors' verdict (#4082). Evidence lives in the versioned, offline-readable sidecar `<gbrain-home>/bootstrap/adopted-connections.json` (`version: 1`, one row per workspace + harness + name; `recordAdoptedConnection` replaces, never appends twins), never in the install receipt, so uninstall does not tear down config bootstrap did not write. The fingerprint is sha256 over canonical JSON of transport, target (URL or command) and header NAMES; header values and tokens are never stored or printed, so a token rotation is not drift. `adoptConnection` backs `gbrain bootstrap hooks --adopt --harness codex [--name <server>]` (dispatch in `src/commands/bootstrap.ts` `runHooks`, before the harness writers): Codex only, refuses without a passing `bootstrap verify` run newer than the config file's mtime, writes nothing to the Codex config and fabricates no receipt registration. Pinned by `test/bootstrap-adopted-connection.serial.test.ts`.
+- `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.
+- `src/core/bootstrap/adopted-connections.ts` + `adopt-connection.ts` — an operator-managed Codex PROJECT connection (`<workspace>/.codex/config.toml` `[mcp_servers.<name>]`, streamable HTTP logged in with `codex mcp login`, or stdio) is not a bootstrap-owned registration, so the `wire` phase in `status.ts` reads it through `adoptedConnectionState`: `detected` (the table exists, nothing proves it works) is `partial` with the adopt hint, `adopted` is `done`, `drifted` (fingerprint changed, table gone, file unparsable) is `partial` with a re-adopt hint, `none` leaves the receipt/hook detectors' verdict (#4082). Evidence lives in the versioned, offline-readable sidecar `<gbrain-home>/bootstrap/adopted-connections.json` (`version: 1`, one row per workspace + harness + name; `recordAdoptedConnection` replaces, never appends twins), never in the install receipt, so uninstall does not tear down config bootstrap did not write. The fingerprint is sha256 over canonical JSON of transport, target (URL or command) and header NAMES; header values and tokens are never stored or printed, so a token rotation is not drift. `adoptConnection` backs `gbrain bootstrap hooks --adopt --harness codex [--name <server>]` (dispatch in `src/commands/bootstrap.ts` `runHooks`, before the harness writers): Codex only, refuses without a passing `bootstrap verify` run newer than the config file's mtime, writes nothing to the Codex config and fabricates no receipt registration. Pinned by `test/bootstrap-adopted-connection.serial.test.ts`. `ownedEntryFingerprint(value)` is the shared fingerprint (`connectionFingerprint` and `gbrain setup`'s per-entry hashes both go through it).
- `src/core/bootstrap/serve-health.ts` — serve `/health` probe + scopes version-skew floor, re-exported by `harness.ts`. `probeServeHealth(mcpUrl, fetchFn, timeoutMs=3000)` GETs `<base>/health` and returns `{ok, version?, engine?, detail?}`, never throws; `fetchFn` is an explicit argument (no ambient fetch, no engine, no config). `isServeOlderThanScopes(v)` compares against the PINNED `SCOPES_MIN_SERVE_VERSION` constant — a comparison against the moving CLI VERSION would false-flag every scope-aware serve on the next release. An older serve verifies scoped tokens as FULL ACCESS, so callers print the floor line unconditionally.
- `src/core/bootstrap/opencode-json.ts` — the ONE direct opencode-config writer (workspace stdio lane, harness remote lane, connect `--install`). ALL edits ride jsonc-parser `modify`/`applyEdits` (comments/formatting/EOLs survive byte-for-byte outside the edited range — opencode's own `mcp add` preserves comments, and JSONC is its effective grammar for BOTH `.json` and `.jsonc` filenames, which MERGE when both exist). Ownership is a 4-state STRUCTURAL FINGERPRINT (`opencodeEntryKind` → ours-same-source | ours-other-source | foreign | absent; GBRAIN_SOURCE EQUALITY for local entries, receipt-url match or the `{env:GBRAIN_REMOTE_TOKEN}` interpolation for remote), never a marker key (a future strict-schema flip must not brick the host). Distinct read-failure classes (ENOENT create / empty-as-{} / unreadable refuse); foreign refusal on write AND remove; post-render validation (our entry round-trips + every other key survives) keeps the original on failure; 0600 for inline-bearer targets; backups are UNIQUE per operation (`<config>.bak-<hex>`, returned in the result with `writtenText`, the exact rendered bytes) so overlapping runs can never clobber each other's snapshot, and a backup is chmod'd 0600 whenever the COPIED content carries an inline bearer (write AND remove paths); the ours-other-source refusal is caller-appropriate (url + `--force` wording on the remote/expect-url path, GBRAIN_SOURCE wording on the local path); `removeOpencodeMcpEntry` takes a caller expectation + optional `skipOtherSource` — the uninstall lane passes THIS workspace's source id so an ours-other-source match becomes a calm skip-with-note (another workspace's registration is never deleted; foreign still refuses); `reconcileOpencodeSiblingGlobal` clears a same-name gbrain entry from the OTHER global filename before a global write (foreign → refuse naming both files) — opencode merges both, so a leftover sibling entry is a shadow registration; the bun-run ownership lane is ANCHORED (an exact `gbrain`/`gbrain-*` path segment in some arg — a gbrainy-fork cli path is NOT ours, fail-closed); `parseOpencodeEntryBearer` recovers the harness `--status` token url-matched only; `opencodeRemoteEntryExists` is the stdio-lane ownership arbiter (codexBlockOwnsName analog). Callers hold `acquireBootstrapLock` (config-dir → opencode-dir ordering). Pinned by `test/opencode-json.test.ts` (incl. the fingerprint truth-table suite).
- `src/core/bootstrap/atomic-write.ts` — the ONE atomic config-file writer for bootstrap host surfaces: symlink-target-resolving, mode-inheriting (`freshMode` for new files, `forceMode` for secret-bearing targets), random-suffix tmp + rename, tmp unlinked best-effort when write/chmod/rename throws (ENOSPC/EACCES never strand `.tmp-` litter), and the existsSync→realpathSync race falls back to fresh-path resolution instead of throwing raw ENOENT. hooks.ts (JSON), codex-toml.ts (TOML+EOL), and opencode-json.ts (JSONC) all swap through it; serialization and EOL policy stay caller-side.
-- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). An explicit private posture (file-plane `memory.visibility_posture`) prints a pre-consent WARNING outside registrar mode: the wired HTTP sessions read world facts only, so they cannot read back what they save as private. Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath), then `requireConsent` via `consentGate` (effects `persistent_install`, plus `credentials` when it mints the token; `--yes` approves; the TTY prompt runs only when `isInteractive()`, and EOF/decline or no human at the terminal writes nothing and exits 3 with the consent payload, whose argv never repeats `--token`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve; it removes hook entries that lost their marker when their command is this install's (`harness-hooks.ts`), keeps the hooks target failed on an unowned lookalike, and `--remove --dry-run` previews without a lock or any write. Hooks targets record `launcher` and `seat` on the receipt (the ownership identity for later runs); the permission target carries `mechanism: 'added'` forward from a prior confirmed receipt target so a re-run never relabels its own `mcp__<name>` as pre-existing, and the failed-smoke rollback removes only an entry added this run. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`. The production mint (`mintHarnessToken`, exported) rotates each host's token from the token it replaces via `carryLegacyGrant`. `--refresh-skills` (`src/core/bootstrap/harness-skills.ts`, `refreshHarnessSkills`) re-joins each live shared-skills entry under its recorded credential so the receipt and native router adopt the server's current enrollment epoch, with no token rotation; `localEnrollment` reads the adapter receipt epoch for `--status`, and `supersededEnrollments` is doctor's read-only comparison against `shared_skill_members` (`bootstrap_harness_health` warn, code `shared_skills_epoch_superseded`). Pinned by `test/harness-skills-epoch.test.ts`.
+- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). An explicit private posture (file-plane `memory.visibility_posture`) prints a pre-consent WARNING outside registrar mode: the wired HTTP sessions read world facts only, so they cannot read back what they save as private. Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath), then `requireConsent` via `consentGate` (effects `persistent_install`, plus `credentials` when it mints the token; `--yes` approves; the TTY prompt runs only when `isInteractive()`, and EOF/decline or no human at the terminal writes nothing and exits 3 with the consent payload, whose argv never repeats `--token`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve; it removes hook entries that lost their marker when their command is this install's (`harness-hooks.ts`), keeps the hooks target failed on an unowned lookalike, and `--remove --dry-run` previews without a lock or any write. Hooks targets record `launcher` and `seat` on the receipt (the ownership identity for later runs); the permission target carries `mechanism: 'added'` forward from a prior confirmed receipt target so a re-run never relabels its own `mcp__<name>` as pre-existing, and the failed-smoke rollback removes only an entry added this run. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`. The production mint (`mintHarnessToken`, exported) rotates each host's token from the token it replaces via `carryLegacyGrant`. `--refresh-skills` (`src/core/bootstrap/harness-skills.ts`, `refreshHarnessSkills`) re-joins each live shared-skills entry under its recorded credential so the receipt and native router adopt the server's current enrollment epoch, with no token rotation; `localEnrollment` reads the adapter receipt epoch for `--status`, and `supersededEnrollments` is doctor's read-only comparison against `shared_skill_members` (`bootstrap_harness_health` warn, code `shared_skills_epoch_superseded`). Pinned by `test/harness-skills-epoch.test.ts`. The Codex SessionEnd capture hook obeys the same recorded consent as the Claude lane (`wireCodexCapture`: hooks on, capture accepted, never registrar mode) and is a numbered consent item when wired.
- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor, `[]` stored as the explicit no-source grant; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). `carryLegacyGrant` + `readActiveTokenPermissions` are the harness rotation carry-over: takes holders and the source grant carry as stored (explicit empty lists included; an explicit `--source` wins), a stored operation snapshot narrows to the run's snapshot plus only skills-policy-added operations, and newer operations are reported as withheld (pinned by `test/harness-rotation-grants.test.ts`). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`. `insertUnifiedToken` (shared with `auth create`) births every token on the unified grant columns at revision 1 plus the `permissions` mirror; a brain whose schema predates the columns refuses with `migrations_pending` (fix: `gbrain apply-migrations --yes`) and nothing is written; `carryLegacyGrant` parses the prior grant from its JSONB through `tokenGrantFromPermissions`, so a drifted prior carries its JSON edit (the `--adopt-permissions` resolution).
-- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune via `gcCorpusTurnFiles`: an extracted `.txt` goes at `corpus_retention_days`, one with no `.ingested` sidecar only at `CORPUS_UNINGESTED_RETENTION_FACTOR` (3) times that, E-N1, pinned by `test/corpus-retention-uningested.serial.test.ts`; an assistant-only whole-file parse heartbeats `degraded`/`no_user_turns`, E-N4; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`. Seat identity (#4618): session-end (before any corpus write of the session), compact (before `bankCompactSegment`) and the stop hook's writeback bank (before `bankWritebackTurn`) record `<sessionId>.seat.json` through `context/seat.ts` — `GBRAIN_SEAT` when valid, else the hashed harness-home seat; `seat_label_invalid`, `seat_conflict` (first seat kept) and `seat_write_failed` are heartbeat reasons with a fixed `hint` (session-end applies them last, like the deferred reasons). `gcCorpusArtifacts` reaps a seat sidecar once no `.txt` of its session remains, after a 10-minute grace. Pinned by `test/session-seat-capture.serial.test.ts`. `HOOK_EVENTS` is the router inventory from `src/cli/subcommands.ts`; `hook <event> --help` prints usage and never runs the event.
+- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune via `gcCorpusTurnFiles`: an extracted `.txt` goes at `corpus_retention_days`, one with no `.ingested` sidecar only at `CORPUS_UNINGESTED_RETENTION_FACTOR` (3) times that, E-N1, pinned by `test/corpus-retention-uningested.serial.test.ts`; an assistant-only whole-file parse heartbeats `degraded`/`no_user_turns`, E-N4; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`. Seat identity (#4618): session-end (before any corpus write of the session), compact (before `bankCompactSegment`) and the stop hook's writeback bank (before `bankWritebackTurn`) record `<sessionId>.seat.json` through `context/seat.ts` — `GBRAIN_SEAT` when valid, else the hashed harness-home seat; `seat_label_invalid`, `seat_conflict` (first seat kept) and `seat_write_failed` are heartbeat reasons with a fixed `hint` (session-end applies them last, like the deferred reasons). `gcCorpusArtifacts` reaps a seat sidecar once no `.txt` of its session remains, after a 10-minute grace. Pinned by `test/session-seat-capture.serial.test.ts`. `HOOK_EVENTS` is the router inventory from `src/cli/subcommands.ts`; `hook <event> --help` prints usage and never runs the event. `user-prompt` confines and parses `transcript_path` through `captureSpecFor(io.harness)`, so `--harness codex` reads the rollout under `CODEX_HOME/sessions` (the Claude projects root otherwise), and skips the Claude-only pressure notice for codex.
- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). Both the hook-tail and full-session parsers skip root `isSidechain`, `isMeta`, or `isCompactSummary` exactly `true`; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string root `origin.kind` other than `'human'` is excluded; missing, empty, or unstructured origins stay compatible, without guessing from message text. Assistant text and non-text placeholders remain eligible, while skipped metadata entries also contribute no collected tool calls. `test/claude-code-jsonl-origin.test.ts` uses synthetic fixtures, not new live-harness validation. `genuineUserTurnIndexes` separately records accepted user-role turns containing real text blocks (harness tags and paste blocks removed first), because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.
- `src/core/transcripts/pasted-content.ts` — #5812, the ONE Claude Code paste detector (`<pasted_content id="…">…</pasted_content id="…">`, tag shape from a real 2.1.287 transcript; depends on that harness format). `stripPastedContent` removes closed blocks and an unclosed tail only when the opening tag has the exact harness shape, scanning with `indexOf` (no lazy regex); `stripPastedContentFromCorpus` strips inside each `[user]` block of the `toCorpusText` rendering, never across the flattened corpus, so an unclosed paste ends with its turn. Consumers: the writeback gate (banked text), `isGenuineUserText` in the parser (classification only; turn, corpus, segment and ingest text keep the paste), and `corpusTextForExtraction` (`corpus-segments.ts`: a `.wb-` file is one turn, other corpus files per block) used by the sweep, the checkpoint harvest and dream `extract_atoms`. `synthesize` keeps pastes. Tests: `test/transcripts-pasted-content.test.ts`, `test/facts/writeback-gate.test.ts`, `test/extract-atoms-pasted-content.test.ts`.
- `src/core/transcripts/grok.ts` — the Grok Build (grok CLI) transcript adapter: one session directory (`~/.grok/sessions/<url-encoded-cwd>/<uuid>/chat_history.jsonl`) = one session; `GROK_HOME` relocates the root. Turn selection is STRUCTURAL (`mapGrokLine`, exported so the dated `SPEC_TARGET` mapping is pinned): user turns are `type:'user'` text blocks WITHOUT `synthetic_reason` (injected system_reminder/task_completed rows are `typed`, i.e. intentionally text-free, as are tool_result-only user arrays); assistant turns need non-empty string `content` (tool-only rows — `content` ''/null WITH `tool_calls` — are `typed`); system/reasoning/tool_result/backend_tool_call rows are `typed`; unknown row types `skip`. A recognised HUMAN-turn row whose content this parser cannot decode (user `content` missing / non-string / non-array / an array holding non-block entries; assistant non-string `content` with no `tool_calls`) is `malformed` and counted as SKIPPED, never typed, so a file made only of such rows is never `expectedEmpty` — the ingest drift signal fires (`bytesRead > 0`, sessions 0, `cleanScan=false`, watermark frozen) and `zeroSessionsReason` names the malformed row count, instead of an upstream schema change silently advancing the watermark past whole conversations. `chat_history.jsonl` carries NO per-message timestamps: session times come from the sibling `summary.json` (`created_at`/`last_active_at`; a malformed summary is ignored, an unparseable date is never fabricated) and, because grok writes `summary.json` at session END, an in-progress session or partial rsync falls back to the log file's own mtime — a real filesystem time — with `raw.timestamp_source` stamped `'summary.json'` vs `'file_mtime'` so consumers can tell them apart (without the fallback the render refusal would freeze the `--since-last` watermark for the whole grok root). Every message carries the session bounds (last message = `last_active_at`, the rest = start). Session id: summary → UUID dir name → `stableIdFromPath` (a sha256 prefix of the log path, never the bare `chat_history` basename, which would collapse every such session onto one page). Sidecars (updates.jsonl, events.jsonl, rewind_points.jsonl, summary.json, prompt_history.jsonl) are not sessions — discover.ts's grok-sidecar filter is scoped to PROVEN grok trees and the head sniff rejects claude-family keys (grok detection runs after claude-code; an oversized system head still detects through the truncated-line sniff); a percent-encoded cwd segment that fails to decode yields `cwd` undefined with the session id intact.
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index c3285aa038..273402ada3 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -28,7 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/skillify-check.ts` — `gbrain skillpack-check` agent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wraps `check-resolvable --json`, `doctor --json`, and migration ledger into one payload. Required item 12 (`brain_first_compliance`) calls `analyzeSkillBrainFirst()` on the candidate SKILL.md; exits 1 when the verdict is `missing_brain_first` (external-lookup pattern present, no callout, no `brain_first: exempt`). The scaffold path in `src/core/skillify/templates.ts` pre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.
-- `src/commands/setup.ts` + `src/cli/commands/setup.ts` — `gbrain setup <harness>` (D8), pre-connect and engine-free (`thinClient: 'none'`, `json: 'document'`): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (`loadConfig`; none → a `gbrain init --pglite --no-embedding` child, `--providers` drops `--no-embedding`), the source (`--source` > `GBRAIN_SOURCE` > unpinned), the launcher (`--gbrain-bin` > `resolveGbrainBin`), the surface (`--surface` > `GBRAIN_SURFACE` > the receipt's > `REGISTRATION_SURFACE`) and the registration owner, prints them, then refuses before any write with `setup_hosted_connection` (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or `setup_owner_conflict` (`live_serve` from `peekLock` unless the live stdio serve is this registration's own, `unowned_entry`, `other_install` by receipt `gbrain_home`, `harness_lane` for a bootstrap harness receipt or another gbrain marker on a wanted event). Consent is three recorded decisions (`resolveConsent`): wiring scope (`--scope`, `--no-hooks`, `GBRAIN_HOOKS=0`), capture (`--capture`/`--no-capture`; a file-config `memory.auto_writeback: off` wins) and providers; read-context events come from the capability row, capture events only when accepted. Verify reuses `smokeStdioRegistration` from `doctor/checks/harness-wiring.ts`; states are `configured` → `connection-verified` → `native-pending` (`native-verified` is never claimed). Unsupported harness ids (`codex`, `openclaw`, `hermes`, unknown) refuse with `setup_harness_unsupported` naming the row's guide (exit 2). `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks` is the crash-injection seam. Pinned by `test/setup.test.ts`.
+- `src/commands/setup.ts` + `src/cli/commands/setup.ts` — `gbrain setup <harness>` (D8), pre-connect and engine-free (`thinClient: 'none'`, `json: 'document'`): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (`loadConfig`; none → a `gbrain init --pglite --no-embedding` child, `--providers` drops `--no-embedding`), the source (`--source` > `GBRAIN_SOURCE` > unpinned), the launcher (`--gbrain-bin` > `resolveGbrainBin`), the surface (`--surface` > `GBRAIN_SURFACE` > the receipt's > `REGISTRATION_SURFACE`) and the registration owner, prints them, then refuses before any write with `setup_hosted_connection` (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or `setup_owner_conflict` (`live_serve` from `peekLock` unless the live stdio serve is this registration's own, `unowned_entry`, `other_install` by receipt `gbrain_home`, `harness_lane` for a bootstrap harness receipt or another gbrain marker on a wanted event). Consent is three recorded decisions (`resolveConsent`): wiring scope (`--scope`, `--no-hooks`, `GBRAIN_HOOKS=0`), capture (`--capture`/`--no-capture`; a file-config `memory.auto_writeback: off` wins) and providers; read-context events come from the capability row, capture events only when accepted. Verify reuses `smokeStdioRegistration` from `doctor/checks/harness-wiring.ts`; states are `configured` → `connection-verified` → `native-pending` (`native-verified` is never claimed). `gbrain setup codex` (`runCodexSetup`/`runCodexRemove`, writer in `src/core/setup/codex.ts`) shares the target, consent, refusal and verify steps: user scope only (`--scope project` exits 2), the codex plugin (`codexPluginProvidesName`) skips the MCP table, `harness_lane` also covers a bootstrap harness receipt targeting codex or a bootstrap-lane group on a wanted event, the dry run adds a `trust` step, and the final state is `native-verified` when the codex row's push is verified and the receipt owns the trusted UserPromptSubmit hook. Unsupported harness ids (`openclaw`, `hermes`, unknown) refuse with `setup_harness_unsupported` naming the row's guide (exit 2). `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks` is the crash-injection seam. Pinned by `test/setup.test.ts`.
- `src/commands/skillify.ts` + `src/core/skillify/{generator,templates}.ts` — `gbrain skillify scaffold <name>` creates all stubs for a new skill: SKILL.md, script, tests, routing-eval.jsonl, resolver entry, filing-rules pointer. `gbrain skillify check <script>` runs the 10-step checklist (LLM evals, routing evals, check-resolvable gate, filing audit) against a candidate skill before it lands.
- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — `install`/`uninstall` are not supported (they exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`; strict arguments through the `skillpack reference` row of `src/cli/strict-args.ts` (#5491): `--dry-run=true`, a typo or an unknown flag exits 2 before any write, the per-skill and `--all` grammars print separately, and `--all --apply-clean-hunks` refuses with the three-command update path; pinned by `test/skillpack-reference-strict-args.test.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` remain because `gbrain skillpack diff` uses `diffSkill` from there.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 0d60532d80..ba5044aaae 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -1981,9 +1981,8 @@ codes when that target is not safe to wire. A refusal writes nothing. Guide:
### Setup harness unsupported
-`setup_harness_unsupported`: setup wires Claude Code only in this release. The
-message names the guide for the harness you asked for (Codex:
-[docs/mcp/CODEX.md](../mcp/CODEX.md), OpenClaw:
+`setup_harness_unsupported`: setup wires Claude Code and Codex in this release.
+The message names the guide for the harness you asked for (OpenClaw:
[docs/mcp/OPENCLAW.md](../mcp/OPENCLAW.md), Hermes:
[docs/mcp/HERMES.md](../mcp/HERMES.md)); follow its manual steps.
`gbrain setup --help` lists the supported harnesses.
@@ -1998,7 +1997,7 @@ message names the guide for the harness you asked for (Codex:
registration would start a second server that fails on the lock. Stop that
server (quit the agent session that started it), or keep it and connect
through it: a shared `gbrain serve --http` is wired with
- `gbrain bootstrap harness --harness claude-code`.
+ `gbrain bootstrap harness --harness <claude-code|codex>`.
- `unowned_entry`: the harness configuration already has an entry under the
same MCP server name, and its hash is not one this setup recorded (you or
another tool wrote it, or you edited it). Setup never overwrites it. Pick
@@ -2009,7 +2008,10 @@ message names the guide for the harness you asked for (Codex:
each install owns its own entries.
- `harness_lane`: `gbrain bootstrap harness` (or a workspace bootstrap
install) already wires gbrain hooks or MCP in this configuration. Keep that
- wiring, or remove it with `gbrain bootstrap harness --remove` first.
+ wiring, or remove it with `gbrain bootstrap harness --remove` first. On
+ Codex this also fires when the bootstrap Codex lane's `SessionEnd` hook is in
+ `hooks.json` and you passed `--capture`: keep that lane and run setup without
+ `--capture`.
`gbrain setup claude-code --dry-run --json` shows the resolved target and the
blocking owner without writing anything.
@@ -2022,7 +2024,7 @@ the harness configuration, or a `gbrain connect --install` receipt), and no
`gbrain setup` receipt owns it. Setup never falls back to a new local brain,
because sessions would then read an empty brain while useful memory stays on
the hosted one. Manage that connection with `gbrain connect <mcp-url>
---harness claude-code --install`; `gbrain doctor --only harness_wiring` shows
+--harness <claude-code|codex> --install`; `gbrain doctor --only harness_wiring` shows
which brain the registration reaches.
## Related
diff --git a/docs/guides/setup.md b/docs/guides/setup.md
index 6b2bb4b8b6..831c055456 100644
--- a/docs/guides/setup.md
+++ b/docs/guides/setup.md
@@ -1,18 +1,18 @@
# Connect an agent with `gbrain setup`
-`gbrain setup claude-code` gives Claude Code memory in one command: a brain
-(the existing one, or a new keyless local brain), a stdio MCP entry, and the
-read-context hooks, verified with the same smoke test `gbrain doctor --only
-harness_wiring` runs. It changes only what it records, and `--remove` undoes
-exactly that.
+`gbrain setup claude-code` and `gbrain setup codex` give Claude Code or Codex
+memory in one command: a brain (the existing one, or a new keyless local
+brain), a stdio MCP entry, and the read-context hooks, verified with the same
+smoke test `gbrain doctor --only harness_wiring` runs. Setup changes only what
+it records, and `--remove` undoes exactly that.
-**Say to your agent:** *"set up gbrain memory for Claude Code"* — *"preview what gbrain setup would change"* — *"remove the gbrain setup from Claude Code"*. The agent runs `gbrain setup claude-code` (with `--dry-run` or `--remove`).
+**Say to your agent:** *"set up gbrain memory for Claude Code"* (or *"for Codex"*) — *"preview what gbrain setup would change"* — *"remove the gbrain setup from Codex"*. The agent runs `gbrain setup claude-code` or `gbrain setup codex` (with `--dry-run` or `--remove`).
```bash
bun install -g github:garrytan/gbrain
-gbrain setup claude-code --dry-run # the resolved target and every step; writes nothing
-gbrain setup claude-code # wire and verify
-gbrain setup claude-code --remove # remove only what setup wrote
+gbrain setup codex --dry-run # the resolved target and every step; writes nothing
+gbrain setup codex # wire and verify (or: gbrain setup claude-code)
+gbrain setup codex --remove # remove only what setup wrote
```
## Target first
@@ -23,16 +23,17 @@ Before it writes anything, setup resolves and prints:
|---|---|
| Brain | This install's config (`GBRAIN_HOME`). With none, a new keyless PGLite brain from `gbrain init --pglite --no-embedding`. |
| Source | `--source`, else `GBRAIN_SOURCE`, else unpinned (the server uses the brain's default source). |
-| Transport | Local stdio: Claude Code starts `<launcher> serve --surface <surface>`. |
+| Transport | Local stdio: the harness starts `<launcher> serve --surface <surface>`. |
| Launcher | `--gbrain-bin`, else the absolute `gbrain` on `PATH` (GUI-launched hosts inherit no `PATH`, so a bare name is never written). |
| Surface | `--surface`, else `GBRAIN_SURFACE`, else the surface already registered, else `full`. |
-| Owner | Who owns the MCP name now: nobody, this setup (its receipt), or the gbrain Claude Code plugin (setup then adds hooks only). |
+| Owner | Who owns the MCP name now: nobody, this setup (its receipt), or the gbrain Claude Code or Codex plugin (setup then adds hooks only). |
It refuses with a coded error, before any write, when the target is not safe:
a hosted brain is already connected (`setup_hosted_connection`: setup never
creates a second, local brain), or another owner holds the target
(`setup_owner_conflict`: a live PGLite server it did not register, an entry it
-did not write, another install's receipt, or the `bootstrap harness` lane).
+did not write, another install's receipt, or the `bootstrap harness` lane;
+for Codex also the bootstrap Codex hook lane on an event setup would wire).
Each code's fix is in [setup refusals](repair.md#setup-refusals).
## Three decisions
@@ -42,8 +43,8 @@ the recorded answers; a flag changes one.
| Decision | Default | Change it |
|---|---|---|
-| Wiring scope | User scope (every Claude Code session), read-context hooks `SessionStart` and `UserPromptSubmit` | `--scope project` (only sessions in this directory), `--no-hooks` (MCP only; `GBRAIN_HOOKS=0` counts as the same opt-out) |
-| Automatic capture | Declined: no `Stop` or `SessionEnd` hook, so no transcript capture | `--capture`. An existing `memory.auto_writeback: off` wins over `--capture`. |
+| Wiring scope | User scope (every session), read-context hooks `SessionStart` and `UserPromptSubmit` | `--scope project` (Claude Code only: sessions in this directory), `--no-hooks` (MCP only; `GBRAIN_HOOKS=0` counts as the same opt-out) |
+| Automatic capture | Declined: no capture hook (Claude Code `Stop` and `SessionEnd`, Codex `SessionEnd`), so no transcript capture | `--capture`. An existing `memory.auto_writeback: off` wins over `--capture`. |
| Provider use | Declined: a new brain is keyless, and setup configures no paid provider | `--providers` (a new brain is then created with embeddings) |
Provider keys in the environment do not change these defaults.
@@ -57,10 +58,12 @@ Setup reports how far the wiring is proven:
tools/list and a `recall` (the `harness_wiring` smoke), or the live stdio
server this registration started holds the brain.
3. `native-pending`: no observed event has shown gbrain context reaching a
- fresh Claude Code session yet. Open a new session (Claude Code reads its
- config at session start) and check that `/mcp` lists gbrain.
-4. `native-verified`: reserved for an observed injected event; this release
- never claims it.
+ fresh session of this harness yet. Open a new session (the harness reads
+ its config at session start) and check that `/mcp` lists gbrain.
+4. `native-verified`: the capability table records an observed push for the
+ harness, and setup wired and trusted that event. Codex reaches it when
+ setup owns the trusted `UserPromptSubmit` hook (observed on codex-cli
+ 0.162.1, see the table below); Claude Code stays `native-pending`.
## Ownership and removal
@@ -71,6 +74,40 @@ receipt (decisions and pending hashes), brain, MCP entry, hooks, receipt
`installed`; a run interrupted at any step resumes from the receipt without
duplicating an entry. A second run on an unchanged install writes nothing.
+### Codex
+
+Codex keeps its MCP table and the hook trust entries in
+`$CODEX_HOME/config.toml` and the hooks in `$CODEX_HOME/hooks.json`; a user hook
+runs only when config.toml carries a `[hooks.state."<hooks.json>:<event>:<index>:0"]`
+table with its `trusted_hash`, otherwise Codex lists it and silently skips it.
+`gbrain setup codex` writes:
+
+- `[mcp_servers.<name>]` with `command`, `args` and `env` (`GBRAIN_HOME`,
+ `GBRAIN_SOURCE` when set);
+- one hooks.json group per event, running
+ `env GBRAIN_HOOK_LANE=setup … <launcher> hook session-start|user-prompt --harness codex`
+ (15 s), plus the detached `hook session-end --harness codex` capture command
+ (3 s) only after `--capture`;
+- one trust table per group.
+
+Each of these entries is owned by its sha256 fingerprint (canonical JSON of the
+exact parsed entry), stored per entry in
+`$CODEX_HOME/.gbrain-connection-codex-<name>.json` (`setup_receipt_version: 2`:
+the version 1 fields plus `hooks_path` and the per-event `trust` map). The write
+order is: receipt `prepared` (the three decisions and pending fingerprints,
+before anything else), brain, MCP table, hooks.json groups (inert until
+trusted), trust tables (activation, last), receipt `installed`. `--remove` runs
+it backwards: trust, hooks, MCP table, receipt. A crash at any point resumes
+from the receipt without a duplicate, and a hook that is not yet trusted never
+runs.
+
+The trust key carries the group's index. When a group is inserted before
+setup's (or setup's group moves), the next run removes setup's stale trust table
+and trusts the group at its new index; trust entries setup did not write are
+never touched. Removing setup's groups shifts groups that sat after them, so
+Codex treats their trust entries as stale; setup prints a note, and running
+setup again for another install re-trusts its own groups.
+
`--remove` deletes only entries whose hash it recorded. An entry you edited
after setup wrote it stays where it is and is reported, and a later setup
leaves it alone. The brain, its notes, unrelated MCP servers and hooks stay.
@@ -79,13 +116,13 @@ Two installs on one machine (different `GBRAIN_HOME`) each use their own
## Harness capability table
-The table is data (`src/core/setup/capabilities.ts`, version 1). Push is never
+The table is data (`src/core/setup/capabilities.ts`, version 2). Push is never
claimed from documentation alone.
| Harness | Transport | Setup | Push |
|---|---|---|---|
| claude-code | local stdio | supported | native-pending |
-| codex | local stdio | refusal with [its guide](../mcp/CODEX.md) | native-pending |
+| codex | local stdio | supported | native-verified: on codex-cli 0.162.1, after a fresh `gbrain setup codex`, the `UserPromptSubmit` hook put a randomized brain item into a fresh native `codex exec` session, which answered it with no tool call (3 of 3 installs); a `--no-hooks` control answered NONE |
| openclaw | local context engine | refusal with [its guide](../mcp/OPENCLAW.md) | native-pending |
| openclaw | thin client | refusal with [its guide](../mcp/OPENCLAW.md) | unsupported |
| hermes | local stdio | refusal with [its guide](../mcp/HERMES.md) | unsupported |
@@ -94,9 +131,9 @@ claimed from documentation alone.
- `gbrain init`: setup runs `gbrain init --pglite --no-embedding` when no brain
exists, and nothing when one does.
-- `claude mcp add` and `gbrain bootstrap hooks`: setup writes the same stdio
- entry and the same `gbrain hook` commands, without the personal-agent
- workspace, and owns them by hash instead of a marker.
+- `claude mcp add`, `codex mcp add` and `gbrain bootstrap hooks`: setup writes
+ the same stdio entry and the same `gbrain hook` commands, without the
+ personal-agent workspace, and owns them by hash instead of a marker.
- `gbrain connect <url> --install`: the path for a hosted brain; setup refuses
rather than replace it.
- `gbrain bootstrap harness`: the path for a shared `gbrain serve --http`; setup
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index ec46b44435..788d3474b3 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -11,6 +11,29 @@ Adding memory to an existing Codex agent preserves its identity and needs no pri
> durable body — not just a connection? That's `gbrain bootstrap`: see the paste
> block in the README and [docs/guides/bootstrap.md](../guides/bootstrap.md).
+## Fastest local path: `gbrain setup codex`
+
+For a brain on this machine, one command creates a keyless brain when there is
+none, registers the stdio MCP server, wires the read-context hooks with their
+trust entries and smoke-tests the registration:
+
+```bash
+bun install -g github:garrytan/gbrain
+gbrain setup codex --dry-run # the resolved target and every step; writes nothing
+gbrain setup codex # wire and verify
+gbrain setup codex --remove # remove only what setup wrote
+```
+
+It writes `[mcp_servers.gbrain]` and one `[hooks.state."…"]` trust table per
+hook into `$CODEX_HOME/config.toml`, and the `SessionStart` and
+`UserPromptSubmit` hooks into `$CODEX_HOME/hooks.json`. Codex runs a user hook
+only when config.toml trusts its exact command, so setup writes both and owns
+each entry by its sha256 fingerprint. Transcript capture (`SessionEnd`, with
+`--capture`) and provider use (`--providers`) stay off unless you accept them;
+`--no-hooks` registers MCP only. Per-turn push is observed on codex-cli 0.162.1:
+setup reports `native-verified` when it owns the trusted `UserPromptSubmit`
+hook. Details: [setup guide](../guides/setup.md#codex).
+
## Install as a Codex plugin (recommended)
gbrain ships as a native Codex plugin — MCP server + a curated brain-first
@@ -220,8 +243,12 @@ codex mcp remove gbrain
paths above), or migrate to the Postgres/Supabase engine, which tolerates
concurrent connections. Details:
[serve ↔ sync concurrency](../architecture/serve-sync-concurrency.md).
-- **Ambient recall (Codex has no lifecycle hooks — use the pull path).** At the
- start of a topical thread and after a compaction, call
+- **Ambient recall.** Codex has lifecycle hooks (`SessionStart`,
+ `UserPromptSubmit`, `SessionEnd` in `$CODEX_HOME/hooks.json`, each trusted by
+ a `[hooks.state]` entry in config.toml); `gbrain setup codex` wires the two
+ read-context hooks so brain pages named in a prompt arrive as context without
+ a tool call. Without those hooks (the plugin, `connect` or `--no-hooks`), use
+ the pull path: at the start of a topical thread and after a compaction, call
`context_pack(entities, budget_tokens)` to warm the standing entities; on a
periodic wake call `delta(session_id, budget_tokens)` for "what changed since
my last wake" (deduped per session). Both are zero-LLM, sub-second, world-only
diff --git a/llms-full.txt b/llms-full.txt
index 4ae3aad621..d5d05d7b19 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -2609,7 +2609,8 @@ comes from agent-authored `## Facts` fences and the `remember` verb.
## Step 3: Create the Brain
-**If you are Claude Code**, one command does Step 3 and the MCP registration:
+**If you are Claude Code or Codex**, one command does Step 3 and the MCP registration
+(use `codex` in place of `claude-code` on Codex):
```bash
gbrain setup claude-code --dry-run --json # the resolved target; writes nothing
@@ -4741,14 +4742,14 @@ before restarting services with this version.
> Run `gbrain apply-migrations --yes --no-autopilot-install`; exit 1 means it's still
> behind: run `gbrain doctor --json`, not `--yes` again.
-**Claude Code, fastest path:**
+**Claude Code or Codex, fastest path:**
```bash
bun install -g github:garrytan/gbrain
-gbrain setup claude-code # --dry-run previews, --remove undoes
+gbrain setup claude-code # or codex; --dry-run previews, --remove undoes
```
-`setup` shows the brain, source, launcher and owner it resolved before writing, runs `gbrain init --pglite --no-embedding` only when no brain exists, writes the stdio MCP entry and read-context hooks (owned by hash) and smoke-tests them. Capture and providers stay off unless accepted; a hosted brain keeps `gbrain connect --install`. [Setup guide](docs/guides/setup.md).
+`setup` shows the brain, source, launcher and owner it resolved before writing, runs `gbrain init --pglite --no-embedding` only when no brain exists, writes the stdio MCP entry and read-context hooks (owned by hash, plus Codex hook trust) and smoke-tests them. Capture and providers stay off unless accepted; a hosted brain keeps `gbrain connect --install`. [Setup guide](docs/guides/setup.md).
Start with the agent you already use. For Grok Bot and Muse, the dedicated guides above install an isolated launcher, repairable runtime, and memory in a verified persistent directory. For a coding agent, paste:
@@ -4823,7 +4824,7 @@ The agent starts with keyless memory and verifies it. API keys, automatic captur
### Lighter ways in
-**Just want a memory for your coding agent — no identity, no repo.** On Claude Code run `gbrain setup claude-code` (above). By hand: `gbrain init --pglite --no-embedding`, then `codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full` (`claude mcp add` takes the same argv; `--surface verbs` or `starter` for a harness that caps its tool count). Saved memories are brain-wide by default; pass `visibility: "private"` for local-only facts.
+**Just want a memory for your coding agent — no identity, no repo.** On Claude Code or Codex use `gbrain setup` (above). By hand: `gbrain init --pglite --no-embedding`, then `codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full` (`claude mcp add` takes the same argv; `--surface verbs` or `starter` for a harness that caps its tool count). Saved memories are brain-wide by default; pass `visibility: "private"` for local-only facts.
**Already have a brain on a remote host** (OpenClaw, Hermes, or any `gbrain serve --http`)? Point your laptop agents at it with one command each — `--install` wires it up and smoke-tests the token before handoff:
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 2e6873a30a..81ab96166b 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
src/core/config.ts 1955 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts)
-src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)
+src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)
src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part)
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 5e7683d733..077d5808f0 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -194,7 +194,7 @@ test/gbrain-owned-page-types.test.ts #5881 gbrain-owned page types are declared
test/get-page-federated-scope.test.ts #2555 get_chunks federated scope 5 source-surface-helper
test/get-page-federated-scope.test.ts #4275 alias hop scope: archived sources, include_deleted, fuzzy precedence, grant precedence 5 source-surface-helper
test/harness-onboarding.test.ts harness identity and private handoff 6 readFileSync
-test/hook-command.serial.test.ts user-prompt 16 source-surface-helper
+test/hook-command.serial.test.ts user-prompt 17 source-surface-helper
test/hook-push-spawn-env.test.ts spawnDetachedPush env handoff 2 readFileSync
test/hook-push-spawn-env.test.ts tryExecAsync env handoff 1 readFileSync
test/integrations-install.test.ts installRecipeIntoHostRepo — happy path 6 readFileSync
diff --git a/src/cli/top-help.ts b/src/cli/top-help.ts
index d842103396..07480d8902 100644
--- a/src/cli/top-help.ts
+++ b/src/cli/top-help.ts
@@ -14,7 +14,8 @@ USAGE
SETUP
mcp grant <name> --help Grant hosted access; private credential handoff
mcp verify --help Verify connection, permissions, and memory
- setup claude-code [--dry-run] Give an agent memory: brain + MCP + hooks, verified (--remove undoes)
+ setup claude-code|codex [--dry-run]
+ Give an agent memory: brain + MCP + hooks, verified (--remove undoes)
init [--pglite|--supabase|--url] Create brain (PGLite default, no server)
init --prefer-postgres [--allow-docker]
Postgres-first install ladder (env URL >
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 943d69c2fc..6cae21480a 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -1131,7 +1131,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
let priorContextText: string | undefined;
let transcriptPath: string | undefined;
if (j.transcript_path !== undefined && j.transcript_path !== null) {
- const conf = confineTranscriptPath(j.transcript_path, {
+ const conf = captureSpecFor(io.harness).confine(j.transcript_path, { // #5941: codex rollouts live under CODEX_HOME/sessions
...(io.transcriptRoot ? { root: io.transcriptRoot } : {}),
// #5701: bounded tail read below — the 50MiB whole-file gate must not
// reject a long session before it runs (full rationale in
@@ -1141,7 +1141,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
if (!conf.ok) return { outcome: 'degraded', reason: `transcript_${conf.reason}` };
transcriptPath = conf.path;
try {
- const parsed = parseTranscript(conf.path, { maxBytes: USER_PROMPT_TRANSCRIPT_MAX_BYTES });
+ const parsed = captureSpecFor(io.harness).parse(conf.path, { maxBytes: USER_PROMPT_TRANSCRIPT_MAX_BYTES });
turns = parsed.turns.slice(-USER_PROMPT_WINDOW_TURNS);
// Cross-turn dedupe: feed the blocks WE previously injected this
// session back as priorContextText (slug-only suppression + volunteer
@@ -1217,7 +1217,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
return { outcome: 'degraded', reason: reasonCode(resp.error ?? 'server_error'), turns: turns.length };
}
// Context-pressure notice (pressure.ts) leads the block so the cap loop never trims it.
- const pressure = transcriptPath ? claudeCodePressure(resp.block?.pressure, transcriptPath, sessionId) : null;
+ const pressure = transcriptPath && io.harness !== 'codex' ? claudeCodePressure(resp.block?.pressure, transcriptPath, sessionId) : null;
const text = [pressure?.notice, resp.block?.text].filter(Boolean).join('\n\n');
if (!text) return { outcome: 'ok', reason: 'empty_block', turns: turns.length };
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 7c87b6cee5..7d646a69c4 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -31,7 +31,7 @@ import { resolveGbrainBin } from '../core/gbrain-bin.ts';
import { isRegistrationSurface, isValidName, REGISTRATION_SURFACE } from '../core/mcp-registration.ts';
import { isValidSourceId } from '../core/source-id.ts';
import { peekLock } from '../core/pglite-lock.ts';
-import { claudePluginProvidesName } from '../core/bootstrap/plugin-lanes.ts';
+import { claudePluginProvidesName, codexPluginProvidesName } from '../core/bootstrap/plugin-lanes.ts';
import { claudeUserSettingsPath, type ClaudeHookEvent } from '../core/bootstrap/host-specs.ts';
import { readHarnessReceiptState } from '../core/bootstrap/format.ts';
import { smokeStdioRegistration } from './doctor/checks/harness-wiring.ts';
@@ -57,16 +57,30 @@ import {
type SetupStep,
type WiringScope,
} from '../core/setup/claude-code.ts';
+import {
+ applyCodexSetup,
+ codexSetupPaths,
+ desiredCodexMcpEntry,
+ inspectCodexSetup,
+ readCodexSetupReceipt,
+ removeCodexSetup,
+ type CodexSetupPlan,
+ type CodexSetupReceipt,
+ type CodexSetupStep,
+} from '../core/setup/codex.ts';
+import type { CodexSetupEvent } from '../core/bootstrap/codex-hooks.ts';
export const SETUP_HELP = `gbrain setup <harness> — give an agent harness memory in one command
Usage: gbrain setup claude-code [flags]
+ gbrain setup codex [flags]
Resolves the brain, source, transport, launcher and registration owner first and
prints them; refuses before writing anything when another owner holds the target.
With no brain configured it creates a keyless local one (gbrain init --pglite
---no-embedding). It then writes the MCP entry and hooks into Claude Code's own
-config and verifies them with the harness_wiring smoke.
+--no-embedding). It then writes the MCP entry and hooks into the harness's own
+config and verifies them with the harness_wiring smoke. Codex: [mcp_servers.<name>]
+and the hook trust entries in $CODEX_HOME/config.toml, the hooks in hooks.json.
Flags:
--dry-run Print the target and every step; write nothing.
@@ -75,9 +89,10 @@ Flags:
then the surface already registered, then full).
--scope user|project Wiring scope: every Claude Code session (user, default) or only
sessions in this directory (project: ~/.claude.json projects
- entry + .claude/settings.local.json).
+ entry + .claude/settings.local.json). Codex: user only.
--no-hooks Register MCP only; install no hooks (GBRAIN_HOOKS=0 does the same).
- --capture Accept automatic capture: also install Stop and SessionEnd hooks.
+ --capture Accept automatic capture: also install the capture hooks
+ (Claude Code: Stop and SessionEnd; Codex: SessionEnd).
--no-capture Decline automatic capture (the default).
--providers Accept provider use: a new brain is created with embeddings.
--no-providers Decline provider use (the default: keyless, no paid calls).
@@ -88,17 +103,22 @@ Flags:
brain and your notes stay. Combine with --dry-run to preview.
States: configured (entries written), connection-verified (the smoke answered),
-native-pending (no observed push into a native session yet), native-verified.
+native-pending (no observed push into a native session yet), native-verified (an
+observed push is on record for this harness and setup wired and trusted that event;
+Codex: UserPromptSubmit, codex-cli 0.162.1).
Refusals: setup never starts a second owner or a second brain. A hosted brain is
-wired with gbrain connect <url> --harness claude-code --install; a running
-serve --http owner with gbrain bootstrap harness --harness claude-code --yes.
+wired with gbrain connect <url> --harness <harness> --install; a running
+serve --http owner with gbrain bootstrap harness --harness <harness> --yes.
-Supported harnesses: claude-code. codex, openclaw and hermes print their guide.
+Supported harnesses: claude-code, codex. openclaw and hermes print their guide.
setup and onboard differ: setup wires a harness to a brain; onboard (post-connect)
improves an existing brain's content.
`;
+type SetupHarnessId = 'claude-code' | 'codex';
+const HARNESS_LABEL: Record<SetupHarnessId, string> = { 'claude-code': 'Claude Code', codex: 'Codex' };
+
interface SetupFlags {
harness?: string;
dryRun: boolean;
@@ -182,11 +202,12 @@ interface Target {
scope: WiringScope;
name: string;
config_path: string;
- settings_path: string;
+ settings_path?: string;
+ hooks_path?: string;
receipt_path: string;
}
-function resolveConsent(flags: SetupFlags, prior: ClaudeSetupReceipt | null, cfg: GBrainConfig | null, scope: WiringScope, notes: string[]): SetupConsent {
+function resolveConsent(flags: SetupFlags, prior: { consent: SetupConsent } | null, cfg: GBrainConfig | null, scope: WiringScope, notes: string[]): SetupConsent {
const hooksOff = flags.noHooks || process.env.GBRAIN_HOOKS === '0';
if (!flags.noHooks && process.env.GBRAIN_HOOKS === '0') notes.push('GBRAIN_HOOKS=0 is set: treated as an opt-out, so no hooks are installed.');
const wiring: SetupConsent['wiring_scope'] = {
@@ -210,29 +231,30 @@ function resolveConsent(flags: SetupFlags, prior: ClaudeSetupReceipt | null, cfg
return { wiring_scope: wiring, capture, providers };
}
-function hookEvents(consent: SetupConsent): ClaudeHookEvent[] {
+function hookEvents<E extends string>(consent: SetupConsent, harness: SetupHarnessId): E[] {
if (consent.wiring_scope.value.hooks === 'none') return [];
- const row = capabilityRows('claude-code')[0]!;
- return [...row.read_events, ...(consent.capture.value === 'accepted' ? row.capture_events : [])] as ClaudeHookEvent[];
+ const row = capabilityRows(harness)[0]!;
+ return [...row.read_events, ...(consent.capture.value === 'accepted' ? row.capture_events : [])] as E[];
}
-function describeTarget(t: Target, out: Out): void {
+function describeTarget(t: Target, out: Out, harness: SetupHarnessId = 'claude-code'): void {
const brain = t.brain.kind === 'new-local-pglite' ? `new keyless PGLite brain at ${t.brain.path} (gbrain init --pglite --no-embedding)`
: t.brain.kind === 'local-pglite' ? `existing PGLite brain at ${t.brain.path}` : 'existing Postgres brain (from this install\'s config)';
- say(out, `Target (Claude Code, ${t.scope} scope):`);
+ say(out, `Target (${HARNESS_LABEL[harness]}, ${t.scope} scope):`);
say(out, ` brain ${brain}`);
say(out, ` source ${t.source.id ? `'${t.source.id}' (pinned, from ${t.source.from === 'flag' ? '--source' : 'GBRAIN_SOURCE'})` : 'the brain\'s default source (unpinned)'}`);
say(out, ` transport stdio MCP: ${t.launcher} serve --surface ${t.surface}`);
- say(out, ` owner ${t.registration_owner === 'setup' ? `this setup (${t.receipt_path})` : t.registration_owner === 'plugin' ? 'the gbrain Claude Code plugin (MCP); setup adds hooks only' : `none yet; setup will own '${t.name}'`}`);
+ say(out, ` owner ${t.registration_owner === 'setup' ? `this setup (${t.receipt_path})` : t.registration_owner === 'plugin' ? `the gbrain ${HARNESS_LABEL[harness]} plugin (MCP); setup adds hooks only` : `none yet; setup will own '${t.name}'`}`);
if (t.live_owner) say(out, ` live gbrain ${t.live_owner.transport === 'http' ? 'serve --http' : 'stdio serve'} PID ${t.live_owner.pid}${t.live_owner.ours ? ' (started by this registration)' : ''}`);
- say(out, ` files ${t.config_path} (MCP), ${t.settings_path} (hooks)`);
+ say(out, ` files ${t.config_path} (MCP${t.hooks_path ? ' + hook trust' : ''}), ${t.hooks_path ?? t.settings_path} (hooks)`);
}
-function describeConsent(c: SetupConsent, events: ClaudeHookEvent[], out: Out): void {
+function describeConsent(c: SetupConsent, events: string[], out: Out, harness: SetupHarnessId = 'claude-code'): void {
const src = (s: string) => `[${s}]`;
+ const captureEvents = capabilityRows(harness)[0]!.capture_events;
say(out, 'Decisions:');
say(out, ` wiring ${c.wiring_scope.value.scope} scope; ${events.length ? `hooks ${events.join(', ')}` : 'no hooks'} ${src(c.wiring_scope.source)}`);
- say(out, ` capture ${c.capture.value}${c.capture.value === 'declined' ? ' (no Stop/SessionEnd hooks, no transcript capture; accept with --capture)' : ' (Stop and SessionEnd hooks)'} ${src(c.capture.source)}`);
+ say(out, ` capture ${c.capture.value}${c.capture.value === 'declined' ? ` (no ${captureEvents.join('/')} hooks, no transcript capture; accept with --capture)` : ` (${captureEvents.join(' and ')} hook${captureEvents.length > 1 ? 's' : ''})`} ${src(c.capture.source)}`);
say(out, ` providers ${c.providers.value}${c.providers.value === 'declined' ? ' (keyless: setup configures no paid provider; accept with --providers)' : ''} ${src(c.providers.source)}`);
}
@@ -254,10 +276,10 @@ export async function runSetup(args: string[]): Promise<number> {
const named = flags.harness ? `'${flags.harness}'` : 'no harness';
return refuse(opError('setup_harness_unsupported',
`gbrain setup does not wire ${named} yet. ${guide ? `Follow ${guide} to connect it by hand.` : `Supported: ${SETUP_CAPABILITIES.filter((r) => r.setup === 'supported').map((r) => r.harness).join(', ')}; known: ${SETUP_HARNESSES.join(', ')}.`}`,
- guide ? `Follow ${guide}.` : 'Run `gbrain setup claude-code`.',
+ guide ? `Follow ${guide}.` : 'Run `gbrain setup claude-code` or `gbrain setup codex`.',
{ reason: guide ? 'harness_not_wired' : 'unknown_harness', docs: 'docs/guides/repair.md#setup-harness-unsupported',
fix: { consent: [], actor: 'user', requires_exclusive: false, why: guide ? `The manual steps for this harness are in ${guide}.` : 'Setup wires the harnesses in its capability table.',
- user_message: guide ? `gbrain setup can't wire ${flags.harness} yet; the steps are in ${guide}.` : 'Pick a supported harness: gbrain setup claude-code.',
+ user_message: guide ? `gbrain setup can't wire ${flags.harness} yet; the steps are in ${guide}.` : 'Pick a supported harness: gbrain setup claude-code or gbrain setup codex.',
...(guide ? { docs: guide } : {}) } }), out);
}
@@ -273,6 +295,13 @@ export async function runSetup(args: string[]): Promise<number> {
return 1;
}
const brainHome = configDir();
+ if (flags.harness === 'codex') {
+ if (flags.scope === 'project') {
+ process.stderr.write('gbrain setup: codex is wired at user scope only (its hooks.json and config.toml live in CODEX_HOME); drop --scope project.\n');
+ return 2;
+ }
+ return runCodexSetup(flags, launcher, cfg, brainHome, out);
+ }
const scope: WiringScope = flags.scope ?? 'user';
const projectDir = scope === 'project' ? realpathSync(process.cwd()) : undefined;
const paths = claudeSetupPaths({ name: flags.name, scope, projectDir });
@@ -299,17 +328,13 @@ export async function runSetup(args: string[]): Promise<number> {
const plan: ClaudeSetupPlan = {
name: flags.name, scope, ...(projectDir ? { projectDir } : {}), launcher, brainHome,
...(process.env.GBRAIN_HOME?.trim() ? { gbrainHomeEnv: process.env.GBRAIN_HOME.trim() } : {}),
- sourceId, surface, events: hookEvents(consent),
+ sourceId, surface, events: hookEvents<ClaudeHookEvent>(consent, 'claude-code'),
};
const found = inspectClaudeSetup(plan);
if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags.name), out);
const pluginOwner = flags.name === 'gbrain' ? claudePluginProvidesName(claudeUserSettingsPath(), 'gbrain') : null;
- const dataDir = cfg && cfg.engine === 'pglite' && !cfg.database_url ? cfg.database_path ?? gbrainPath('brain.pglite') : undefined;
- const lock = dataDir ? peekLock(dataDir) : null;
- const ours = prior?.status === 'installed' && found.mcp.state === 'current';
- const liveOwner = lock?.held && lock.isServe && lock.pid !== undefined
- ? { pid: lock.pid, transport: lock.http ? 'http' as const : 'stdio' as const, ours: ours && !lock.http } : null;
+ const { dataDir, liveOwner } = liveOwnerOf(cfg, prior?.status === 'installed' && found.mcp.state === 'current');
const target: Target = {
brain: !cfg ? { kind: 'new-local-pglite', path: gbrainPath('brain.pglite'), config_dir: brainHome }
: cfg.engine === 'pglite' ? { kind: 'local-pglite', path: dataDir, config_dir: brainHome } : { kind: 'local-postgres', config_dir: brainHome },
@@ -323,18 +348,7 @@ export async function runSetup(args: string[]): Promise<number> {
describeConsent(consent, plan.events, out);
for (const n of notes) say(out, `note: ${n}`);
- if (liveOwner && !liveOwner.ours) {
- const http = liveOwner.transport === 'http';
- return refuse(ownerConflict('live_serve',
- `A live gbrain ${http ? 'serve --http' : 'stdio serve'} (PID ${liveOwner.pid}) holds this PGLite brain's single-writer lock; a stdio registration would start a second server that fails on the lock.`,
- http
- ? { actor: 'agent', argv: ['gbrain', 'bootstrap', 'harness', '--harness', 'claude-code', '--yes'], consent: ['persistent_install', 'credentials'],
- why: 'Connect Claude Code to the running shared server instead of starting a second owner.', verify: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'] } }
- : { actor: 'user', argv: ['kill', String(liveOwner.pid)],
- why: 'Stop the server that holds the brain (quit the agent session that started it), then run setup again.',
- user_message: `gbrain's database is in use by another server (PID ${liveOwner.pid}). Please quit the agent session that started it, then I'll run setup again.`,
- verify: verifyDryRun('claude-code', flags.name) }), out);
- }
+ if (liveOwner && !liveOwner.ours) return refuse(liveServeConflict(liveOwner, 'claude-code', flags.name), out);
if (found.mcp.state === 'unowned' && !pluginOwner) {
return refuse(ownerConflict('unowned_entry', `${found.configPath} already has an MCP server named '${flags.name}' that gbrain setup did not write (or it was edited since); setup never overwrites it.`, {
actor: 'agent', argv: ['gbrain', 'setup', 'claude-code', '--name', `${flags.name}-local`, '--dry-run', '--json'],
@@ -365,17 +379,7 @@ export async function runSetup(args: string[]): Promise<number> {
let notices: unknown[] = [];
const result = await applyClaudeSetup(plan, consent, {
pluginOwner, brainCreated: brainCreate, abortAfter: process.env.GBRAIN_SETUP_ABORT_AFTER,
- beforeMcp: brainCreate ? async () => {
- say(out, `Creating the brain: ${initArgv.join(' ')}`);
- const child = Bun.spawnSync(initArgv, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: process.env });
- const initOut = child.stdout?.toString() ?? '';
- process.stderr.write(child.stderr?.toString() ?? '');
- if (!out.json) process.stdout.write(initOut);
- if (child.exitCode !== 0) throw new Error(`\`${initArgv.join(' ')}\` exited ${child.exitCode}; nothing else was written. Fix the init error above, then run setup again.`);
- if (out.json) {
- try { notices = (JSON.parse(initOut) as { notices?: unknown[] }).notices ?? []; } catch { process.stderr.write(initOut); }
- }
- } : undefined,
+ beforeMcp: brainCreate ? async () => { notices = runBrainInit(initArgv, out); } : undefined,
});
for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);
if (!result.changed) say(out, 'Nothing changed: this install is already wired.');
@@ -399,15 +403,167 @@ export async function runSetup(args: string[]): Promise<number> {
}
}
-function hostedConnection(url: string, wired: boolean, name: string): OperationError {
+function liveOwnerOf(cfg: GBrainConfig | null, ours: boolean): { dataDir?: string; liveOwner: Target['live_owner'] } {
+ const dataDir = cfg && cfg.engine === 'pglite' && !cfg.database_url ? cfg.database_path ?? gbrainPath('brain.pglite') : undefined;
+ const lock = dataDir ? peekLock(dataDir) : null;
+ return { dataDir, liveOwner: lock?.held && lock.isServe && lock.pid !== undefined
+ ? { pid: lock.pid, transport: lock.http ? 'http' : 'stdio', ours: ours && !lock.http } : null };
+}
+
+function liveServeConflict(live: NonNullable<Target['live_owner']>, harness: SetupHarnessId, name: string): OperationError {
+ const http = live.transport === 'http';
+ return ownerConflict('live_serve',
+ `A live gbrain ${http ? 'serve --http' : 'stdio serve'} (PID ${live.pid}) holds this PGLite brain's single-writer lock; a stdio registration would start a second server that fails on the lock.`,
+ http
+ ? { actor: 'agent', argv: ['gbrain', 'bootstrap', 'harness', '--harness', harness, '--yes'], consent: ['persistent_install', 'credentials'],
+ why: `Connect ${HARNESS_LABEL[harness]} to the running shared server instead of starting a second owner.`, verify: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'] } }
+ : { actor: 'user', argv: ['kill', String(live.pid)],
+ why: 'Stop the server that holds the brain (quit the agent session that started it), then run setup again.',
+ user_message: `gbrain's database is in use by another server (PID ${live.pid}). Please quit the agent session that started it, then I'll run setup again.`,
+ verify: verifyDryRun(harness, name) });
+}
+
+/** Run the `gbrain init` child that creates a new keyless brain; returns its JSON notices. */
+function runBrainInit(initArgv: string[], out: Out): unknown[] {
+ say(out, `Creating the brain: ${initArgv.join(' ')}`);
+ const child = Bun.spawnSync(initArgv, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: process.env });
+ const initOut = child.stdout?.toString() ?? '';
+ process.stderr.write(child.stderr?.toString() ?? '');
+ if (!out.json) process.stdout.write(initOut);
+ if (child.exitCode !== 0) throw new Error(`\`${initArgv.join(' ')}\` exited ${child.exitCode}; nothing else was written. Fix the init error above, then run setup again.`);
+ if (!out.json) return [];
+ try { return (JSON.parse(initOut) as { notices?: unknown[] }).notices ?? []; } catch { process.stderr.write(initOut); return []; }
+}
+
+async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConfig | null, brainHome: string, out: Out): Promise<number> {
+ const paths = codexSetupPaths(flags.name);
+ try {
+ const receiptRead = readCodexSetupReceipt(paths.receiptPath);
+ if (flags.remove) return await runCodexRemove(flags, receiptRead.setup, paths.receiptPath, brainHome, out);
+
+ const hostedUrl = cfg?.remote_mcp?.mcp_url ?? receiptRead.hosted?.mcp_url ?? (receiptRead.hosted ? 'a hosted brain' : undefined);
+ if (hostedUrl) return refuse(hostedConnection(hostedUrl, receiptRead.hosted !== null, flags.name, 'codex'), out);
+ const prior = receiptRead.setup;
+ if (prior && prior.gbrain_home !== brainHome) {
+ return refuse(ownerConflict('other_install', `The '${flags.name}' connection belongs to the gbrain install at ${prior.gbrain_home}, not ${brainHome}.`, {
+ actor: 'agent', argv: ['gbrain', 'setup', 'codex', '--name', `${flags.name}-2`, '--dry-run', '--json'],
+ why: 'Each install owns its own MCP name and hooks; preview this install under another name.', verify: verifyDryRun('codex', flags.name) }), out);
+ }
+
+ const notes: string[] = [];
+ const consent = resolveConsent(flags, prior, cfg, 'user', notes);
+ const envSurface = process.env.GBRAIN_SURFACE;
+ if (envSurface && !isRegistrationSurface(envSurface)) notes.push(`GBRAIN_SURFACE='${envSurface}' is not verbs, starter or full; ignored.`);
+ const surface: McpSurface = flags.surface ?? (isRegistrationSurface(envSurface) ? envSurface : undefined) ?? prior?.surface ?? REGISTRATION_SURFACE;
+ const sourceId = flags.source ?? (process.env.GBRAIN_SOURCE && isValidSourceId(process.env.GBRAIN_SOURCE) ? process.env.GBRAIN_SOURCE : null);
+ const plan: CodexSetupPlan = {
+ name: flags.name, launcher, brainHome,
+ ...(process.env.GBRAIN_HOME?.trim() ? { gbrainHomeEnv: process.env.GBRAIN_HOME.trim() } : {}),
+ sourceId, surface, events: hookEvents<CodexSetupEvent>(consent, 'codex'),
+ };
+ const found = inspectCodexSetup(plan);
+ if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags.name, 'codex'), out);
+
+ const pluginOwner = codexPluginProvidesName(paths.configPath, flags.name);
+ const { dataDir, liveOwner } = liveOwnerOf(cfg, prior?.status === 'installed' && found.mcp.state === 'current');
+ const target: Target = {
+ brain: !cfg ? { kind: 'new-local-pglite', path: gbrainPath('brain.pglite'), config_dir: brainHome }
+ : cfg.engine === 'pglite' ? { kind: 'local-pglite', path: dataDir, config_dir: brainHome } : { kind: 'local-postgres', config_dir: brainHome },
+ source: { id: sourceId, pinned: sourceId !== null, from: flags.source ? 'flag' : sourceId ? 'env' : 'brain-default' },
+ transport: 'local-stdio', launcher, surface,
+ registration_owner: pluginOwner ? 'plugin' : prior ? 'setup' : 'none',
+ live_owner: liveOwner, scope: 'user', name: flags.name,
+ config_path: found.configPath, hooks_path: found.hooksPath, receipt_path: found.receiptPath,
+ };
+ describeTarget(target, out, 'codex');
+ describeConsent(consent, plan.events, out, 'codex');
+ for (const n of notes) say(out, `note: ${n}`);
+
+ if (liveOwner && !liveOwner.ours) return refuse(liveServeConflict(liveOwner, 'codex', flags.name), out);
+ if (found.mcp.state === 'unowned' && !pluginOwner) {
+ return refuse(ownerConflict('unowned_entry', `${found.configPath} already has [mcp_servers.${flags.name}] that gbrain setup did not write (or it was edited since); setup never overwrites it.`, {
+ actor: 'agent', argv: ['gbrain', 'setup', 'codex', '--name', `${flags.name}-local`, '--dry-run', '--json'],
+ why: 'Preview a setup under another name, or remove that table yourself and run setup again.', verify: verifyDryRun('codex', flags.name) }), out);
+ }
+ const harnessReceipt = readHarnessReceiptState(brainHome);
+ const harnessLane = harnessReceipt.state === 'ok' && harnessReceipt.receipt.targets.some((t) => t.host === 'codex');
+ const laneEvents = found.otherLaneEvents.filter((e) => (plan.events as string[]).includes(e));
+ if (harnessLane || laneEvents.length > 0) {
+ return refuse(ownerConflict('harness_lane', `${harnessLane ? '`gbrain bootstrap harness` already wires Codex for this install' : `${found.hooksPath} already wires ${laneEvents.join(', ')} through gbrain's bootstrap Codex lane`}; two lanes would fire every hook twice.`, {
+ actor: 'agent', argv: harnessLane ? ['gbrain', 'bootstrap', 'harness', '--remove', '--dry-run'] : ['gbrain', 'setup', 'codex', laneEvents.every((e) => e === 'SessionEnd') ? '--no-capture' : '--no-hooks', '--dry-run', '--json'],
+ why: harnessLane ? 'Preview removing the bootstrap harness wiring first, or keep it and skip setup.' : 'Keep the bootstrap lane for those events and preview setup without them.', verify: verifyDryRun('codex', flags.name) }), out);
+ }
+
+ const brainCreate = !cfg;
+ const initArgv = [launcher, 'init', '--pglite', ...(consent.providers.value === 'accepted' ? [] : ['--no-embedding']), ...(out.json ? ['--json'] : [])];
+ if (flags.dryRun) {
+ const unchanged = found.prior?.status === 'installed' && found.hooksCurrent && found.trustCurrent && (found.mcp.state === 'current' || !!pluginOwner) && !brainCreate;
+ const steps: CodexSetupStep[] = [
+ { step: 'receipt', action: unchanged ? 'keep' : 'write', detail: found.receiptPath },
+ ...(brainCreate ? [{ step: 'brain' as const, action: 'write' as const, detail: `would run: ${initArgv.join(' ')}` }] : []),
+ { step: 'mcp', action: pluginOwner ? 'skip' : found.mcp.state === 'current' ? 'keep' : 'write', detail: `[mcp_servers.${flags.name}] in ${found.configPath}` },
+ { step: 'hooks', action: found.hooksCurrent ? 'keep' : 'write', detail: plan.events.length ? `${plan.events.join(', ')} in ${found.hooksPath}` : `no hooks (${found.hooksPath})` },
+ { step: 'trust', action: found.trustCurrent ? 'keep' : 'write', detail: `trust entries for setup's groups in ${found.configPath}` },
+ ...Object.keys(found.edited).map((event) => ({ step: 'hooks' as const, action: 'preserve' as const, detail: `${event} was edited after setup wrote it; kept` })),
+ ];
+ return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes });
+ }
+
+ let notices: unknown[] = [];
+ const result = await applyCodexSetup(plan, consent, {
+ pluginOwner, brainCreated: brainCreate, abortAfter: process.env.GBRAIN_SETUP_ABORT_AFTER,
+ beforeMcp: brainCreate ? async () => { notices = runBrainInit(initArgv, out); } : undefined,
+ });
+ for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);
+ for (const n of result.notes) say(out, `note: ${n}`);
+ if (!result.changed) say(out, 'Nothing changed: this install is already wired.');
+
+ let verify: { ok: boolean; reason: string; message: string };
+ if (pluginOwner) verify = { ok: false, reason: 'plugin_lane', message: `The '${pluginOwner}' plugin serves MCP; start a new Codex session and check /mcp lists gbrain.` };
+ else if (liveOwner?.ours) verify = { ok: true, reason: 'wired_running', message: `A live stdio serve (PID ${liveOwner.pid}) started by this registration holds the brain.` };
+ else {
+ const entry = desiredCodexMcpEntry(plan) as { command: string; args: string[]; env?: Record<string, string> };
+ verify = await smokeStdioRegistration({ harness: 'codex', source: found.configPath, kind: 'stdio', command: entry.command, args: entry.args, env: entry.env });
+ }
+ const push = capabilityRows('codex')[0]!.push;
+ const states = ['configured', ...(verify.ok ? ['connection-verified', push === 'native-verified' && result.receipt.trust.owned.UserPromptSubmit ? 'native-verified' : 'native-pending'] : [])];
+ const code = await finish(out, { harness: 'codex', dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent,
+ steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved });
+ return verify.ok || pluginOwner ? code : 1;
+ } catch (e) {
+ if (e instanceof OperationError) return refuse(e, out);
+ if (e instanceof SetupAbortInjected) { process.stderr.write(`${e.message}\n`); return 1; }
+ process.stderr.write(`gbrain setup: ${(e as Error).message}\n`);
+ return 1;
+ }
+}
+
+async function runCodexRemove(flags: SetupFlags, receipt: CodexSetupReceipt | null, receiptPath: string, brainHome: string, out: Out): Promise<number> {
+ if (!receipt) {
+ say(out, `No gbrain setup receipt at ${receiptPath}; setup owns nothing here, so nothing was removed.`);
+ return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: [], states: [], verify: null, notices: [], notes: [] });
+ }
+ if (receipt.gbrain_home !== brainHome) {
+ return refuse(ownerConflict('other_install', `The '${receipt.name}' connection belongs to the gbrain install at ${receipt.gbrain_home}, not ${brainHome}; --remove leaves it alone.`, {
+ actor: 'user', why: `Run --remove with GBRAIN_HOME set to the install that owns it (${receipt.gbrain_home}).`, user_message: 'This setup belongs to another gbrain install; remove it from that install.' }), out);
+ }
+ const r = await removeCodexSetup(receipt, receiptPath, { dryRun: flags.dryRun });
+ for (const s of r.steps) say(out, ` ${(flags.dryRun ? `would ${s.action}` : s.action).padEnd(14)} ${s.step.padEnd(7)} ${s.detail}`);
+ for (const n of r.notes) say(out, `note: ${n}`);
+ say(out, 'The brain, its notes and unrelated Codex settings were left as they were.');
+ return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: r.notes, preserved: r.preserved });
+}
+
+function hostedConnection(url: string, wired: boolean, name: string, harness: SetupHarnessId = 'claude-code'): OperationError {
+ const label = HARNESS_LABEL[harness];
return opError('setup_hosted_connection',
- `This machine already reaches a hosted brain (${url})${wired ? ` and Claude Code's '${name}' entry points at it` : ''}; gbrain setup will not create a second, local brain.`,
- wired ? 'Nothing to do: the hosted connection is wired. `gbrain doctor --only harness_wiring` verifies it.' : `Connect Claude Code to it with \`gbrain connect ${url} --harness claude-code --install\`.`,
+ `This machine already reaches a hosted brain (${url})${wired ? ` and ${label}'s '${name}' entry points at it` : ''}; gbrain setup will not create a second, local brain.`,
+ wired ? 'Nothing to do: the hosted connection is wired. `gbrain doctor --only harness_wiring` verifies it.' : `Connect ${label} to it with \`gbrain connect ${url} --harness ${harness} --install\`.`,
{ docs: 'docs/guides/repair.md#setup-hosted-connection',
fix: wired
? { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the registration reaches and smoke-tests it.' }
- : { argv: ['gbrain', 'connect', url, '--harness', 'claude-code', '--install'], consent: ['persistent_install', 'credentials'], actor: 'user', requires_exclusive: false,
- why: 'The hosted connection installer writes the Claude Code entry with the hosted credential.', user_message: `Your brain is hosted at ${url}. Run gbrain connect for it (it needs your private handoff); setup will not create a local brain.`,
+ : { argv: ['gbrain', 'connect', url, '--harness', harness, '--install'], consent: ['persistent_install', 'credentials'], actor: 'user', requires_exclusive: false,
+ why: `The hosted connection installer writes the ${label} entry with the hosted credential.`, user_message: `Your brain is hosted at ${url}. Run gbrain connect for it (it needs your private handoff); setup will not create a local brain.`,
verify: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'] } } });
}
@@ -427,22 +583,25 @@ async function runRemove(flags: SetupFlags, receipt: ClaudeSetupReceipt | null,
}
async function finish(out: Out, doc: {
- dryRun: boolean; remove?: boolean; target?: Target; consent?: SetupConsent; steps: SetupStep[]; states: string[];
+ harness?: SetupHarnessId; dryRun: boolean; remove?: boolean; target?: Target; consent?: SetupConsent; steps: Array<{ step: string; action: string; detail: string }>; states: string[];
verify: { ok: boolean; reason: string; message: string } | null; notices: unknown[]; notes: string[]; preserved?: unknown[];
}): Promise<number> {
+ const harness = doc.harness ?? 'claude-code';
const state = doc.states.at(-1) ?? null;
if (out.json) {
await writeJsonDocument(`${JSON.stringify({
- harness: 'claude-code', dry_run: doc.dryRun, remove: doc.remove ?? false,
+ harness, dry_run: doc.dryRun, remove: doc.remove ?? false,
...(doc.target ? { target: doc.target } : {}), ...(doc.consent ? { consent: doc.consent } : {}),
steps: doc.steps, preserved: doc.preserved ?? [], states: doc.states, state, verify: doc.verify,
- capability: capabilityRows('claude-code')[0], capability_table_version: SETUP_CAPABILITY_TABLE_VERSION,
+ capability: capabilityRows(harness)[0], capability_table_version: SETUP_CAPABILITY_TABLE_VERSION,
notes: doc.notes, notices: doc.notices,
}, null, 2)}\n`, (t) => process.stdout.write(t));
return 0;
}
if (doc.verify) say(out, `Verify: ${doc.verify.ok ? 'ok' : 'not verified'} (${doc.verify.reason}): ${doc.verify.message}`);
- if (state) say(out, `State: ${state} (${doc.states.join(' -> ')}). Native push is not claimed until an observed event reaches a fresh session.`);
- if (state && !doc.remove) say(out, 'Next: open a new Claude Code session (config is read at session start) and check that /mcp lists gbrain.');
+ if (state) say(out, `State: ${state} (${doc.states.join(' -> ')}).${state === 'native-verified' ? '' : ' Native push is not claimed until an observed event reaches a fresh session.'}`);
+ if (state && !doc.remove) say(out, harness === 'codex'
+ ? 'Next: start a new Codex session (config and hooks are read at session start) and check that /mcp lists gbrain.'
+ : 'Next: open a new Claude Code session (config is read at session start) and check that /mcp lists gbrain.');
return 0;
}
diff --git a/src/core/bootstrap/adopted-connections.ts b/src/core/bootstrap/adopted-connections.ts
index ce790eb055..f5dc6a96e4 100644
--- a/src/core/bootstrap/adopted-connections.ts
+++ b/src/core/bootstrap/adopted-connections.ts
@@ -63,9 +63,16 @@ export type AdoptedConnectionState =
const canonical = (v: unknown): unknown => Array.isArray(v) ? v.map(canonical)
: v && typeof v === 'object' ? Object.fromEntries(Object.keys(v as object).sort().map(k => [k, canonical((v as Record<string, unknown>)[k])])) : v;
+/**
+ * THE harness-entry fingerprint: sha256 hex over the canonical JSON (keys
+ * sorted recursively) of exactly the value given. `gbrain setup` stores one
+ * per owned entry (an MCP table or JSON entry, a hook entry or group, a Codex
+ * trust table) in its connection receipt and compare-and-swaps on it; this
+ * sidecar hashes a redacted projection of an adopted server through it.
+ */
+export const ownedEntryFingerprint = (value: unknown): string => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
/** sha256 over canonical JSON of what identifies the connection; header values are excluded by construction. */
-export const connectionFingerprint = (parts: { type: string; target: string; header_names: string[] }): string =>
- createHash('sha256').update(JSON.stringify(canonical(parts))).digest('hex');
+export const connectionFingerprint = (parts: { type: string; target: string; header_names: string[] }): string => ownedEntryFingerprint(parts);
export function adoptedConnectionsPath(gbrainHomeDir: string): string {
return join(gbrainHomeDir, 'bootstrap', 'adopted-connections.json');
diff --git a/src/core/bootstrap/codex-hooks.ts b/src/core/bootstrap/codex-hooks.ts
index f848f7d79e..188c7447a4 100644
--- a/src/core/bootstrap/codex-hooks.ts
+++ b/src/core/bootstrap/codex-hooks.ts
@@ -48,6 +48,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 type { HostSpecTarget } from './host-specs.ts';
import { CODEX_HOOK_EVENTS, codexConfigPath, codexHooksPath } from './host-specs.ts';
@@ -134,13 +135,21 @@ function canonicalJson(v: unknown): string {
return JSON.stringify(v);
}
+/**
+ * Codex's trust hash for one matcher-less command handler: `event_name` is the
+ * snake_case state label (`session_end`, `session_start`, `user_prompt_submit`),
+ * the timeout is the normalized one (re-checked against openai/codex
+ * rust-v0.162.1 `hooks/src/engine/discovery.rs` `hook_hash` +
+ * `config/src/fingerprint.rs` `version_for_toml`).
+ */
+export function codexHookTrustHash(eventName: string, command: string, timeout: number): string {
+ const identity = { event_name: eventName, hooks: [{ type: 'command', command, timeout, async: false }] };
+ return 'sha256:' + createHash('sha256').update(canonicalJson(identity), 'utf8').digest('hex');
+}
+
/** The trust hash for OUR SessionEnd handler shape (matcher/None fields omitted). */
export function codexTrustHash(command: string): string {
- const identity = {
- event_name: 'session_end',
- hooks: [{ type: 'command', command, timeout: SESSION_END_TIMEOUT_SEC, async: false }],
- };
- return 'sha256:' + createHash('sha256').update(canonicalJson(identity), 'utf8').digest('hex');
+ return codexHookTrustHash('session_end', command, SESSION_END_TIMEOUT_SEC);
}
interface HooksJson {
@@ -149,8 +158,9 @@ interface HooksJson {
[k: string]: unknown;
}
+/** A bootstrap-lane group: carries the ownership token and is not a `gbrain setup` group (those are owned by hash). */
function isOurGroup(group: { hooks?: Array<{ command?: unknown }> }): boolean {
- return (group.hooks ?? []).some((h) => typeof h.command === 'string' && h.command.includes(CODEX_HOOK_OWNERSHIP_TOKEN));
+ return (group.hooks ?? []).some((h) => typeof h.command === 'string' && h.command.includes(CODEX_HOOK_OWNERSHIP_TOKEN) && !h.command.includes(CODEX_SETUP_LANE_TOKEN));
}
export interface WriteCodexHooksResult {
@@ -337,3 +347,129 @@ export function removeCodexHooks(opts: { hooksPath?: string; configPath?: string
}
return { hooksPath, configPath, removed, notes };
}
+
+// ── `gbrain setup codex` lane: owned by exact hash, never by token ──────────
+//
+// Setup's groups carry `GBRAIN_HOOK_LANE=setup` so the bootstrap lane above
+// (token-owned) never claims or strips them; setup itself recognizes its
+// groups only by the sha256 fingerprint its connection receipt recorded
+// (src/core/setup/codex.ts), so an edited group is preserved, never removed.
+
+export const CODEX_SETUP_LANE_TOKEN = 'GBRAIN_HOOK_LANE=setup';
+export const CODEX_SETUP_EVENTS = ['SessionStart', 'UserPromptSubmit', 'SessionEnd'] as const;
+export type CodexSetupEvent = (typeof CODEX_SETUP_EVENTS)[number];
+
+/** State label, normalized timeout and `gbrain hook` subcommand per event. The
+ * context events run synchronously within 15s (above session-start's own
+ * deadline); SessionEnd keeps the detached 3s capture command. */
+const SETUP_EVENT_SPECS: Record<CodexSetupEvent, { stateName: string; timeout: number; subcommand: string }> = {
+ SessionStart: { stateName: 'session_start', timeout: 15, subcommand: 'session-start' },
+ UserPromptSubmit: { stateName: 'user_prompt_submit', timeout: 15, subcommand: 'user-prompt' },
+ SessionEnd: { stateName: 'session_end', timeout: SESSION_END_TIMEOUT_SEC, subcommand: 'session-end' },
+};
+
+export interface CodexHookGroup { hooks: Array<{ type: 'command'; command: string; timeout: number }> }
+
+/** Setup's group for one event. `env` is POSIX `env` (any $SHELL parses it); the values pin this install. */
+export function codexSetupHookGroup(gbrainBin: string, event: CodexSetupEvent, env: { GBRAIN_HOME?: string; GBRAIN_SOURCE?: string }): CodexHookGroup {
+ const assignments = [CODEX_SETUP_LANE_TOKEN, ...(env.GBRAIN_HOME ? [`GBRAIN_HOME=${env.GBRAIN_HOME}`] : []), ...(env.GBRAIN_SOURCE ? [`GBRAIN_SOURCE=${env.GBRAIN_SOURCE}`] : [])];
+ const spec = SETUP_EVENT_SPECS[event];
+ const command = event === 'SessionEnd'
+ ? ['env', ...assignments].map(shellQuote).join(' ') + ' ' + buildCodexSessionEndCommand(gbrainBin)
+ : ['env', ...assignments, gbrainBin, 'hook', spec.subcommand, '--harness', 'codex'].map(shellQuote).join(' ');
+ return { hooks: [{ type: 'command', command, timeout: spec.timeout }] };
+}
+
+/** The `[hooks.state."<key>"]` entry that trusts `group` at `index` of `event` in `hooksPath`. */
+export function codexSetupTrustEntry(hooksPath: string, event: CodexSetupEvent, index: number, group: CodexHookGroup): { key: string; trusted_hash: string } {
+ const { stateName } = SETUP_EVENT_SPECS[event];
+ const handler = group.hooks[0]!;
+ return { key: `${hooksPath}:${stateName}:${index}:0`, trusted_hash: codexHookTrustHash(stateName, handler.command, handler.timeout) };
+}
+
+export interface CodexHookCensusGroup { event: string; index: number; hash: string; lane: 'setup' | 'bootstrap' | 'other'; commands: string[] }
+
+function loadHooksJson(hooksPath: string): { doc: HooksJson; hooks: NonNullable<HooksJson['hooks']> } {
+ if (!existsSync(hooksPath)) return { doc: {}, hooks: {} };
+ const text = readFileSync(hooksPath, 'utf8');
+ if (text.trim() === '') return { doc: {}, hooks: {} };
+ let doc: HooksJson;
+ try {
+ doc = JSON.parse(text) as HooksJson;
+ if (typeof doc !== 'object' || doc === null || Array.isArray(doc)) throw new Error('not an object');
+ } catch {
+ throw new Error(`${hooksPath} does not parse as a JSON object; setup never rewrites a file it cannot parse (codex skips it too). Fix it by hand, then run setup again.`);
+ }
+ if (doc.hooks !== undefined && (typeof doc.hooks !== 'object' || doc.hooks === null || Array.isArray(doc.hooks))) {
+ throw new Error(`${hooksPath} has a "hooks" key that is not an object; setup leaves it untouched.`);
+ }
+ return { doc, hooks: (doc.hooks ?? {}) as NonNullable<HooksJson['hooks']> };
+}
+
+const CONTEXT_LANE_TOKENS = ['hook session-start --harness codex', 'hook user-prompt --harness codex', CODEX_HOOK_OWNERSHIP_TOKEN];
+
+/** Every matcher group under setup's events, fingerprinted. Throws on an unparseable file. */
+export function codexHookCensus(hooksPath: string): CodexHookCensusGroup[] {
+ const { hooks } = loadHooksJson(hooksPath);
+ const out: CodexHookCensusGroup[] = [];
+ for (const event of CODEX_SETUP_EVENTS) {
+ const groups = hooks[event];
+ if (!Array.isArray(groups)) continue;
+ groups.forEach((group, index) => {
+ const commands = (Array.isArray(group?.hooks) ? group.hooks : []).map((h) => h?.command).filter((c): c is string => typeof c === 'string');
+ const lane = commands.some((c) => c.includes(CODEX_SETUP_LANE_TOKEN)) ? 'setup'
+ : commands.some((c) => CONTEXT_LANE_TOKENS.some((t) => c.includes(t))) ? 'bootstrap' : 'other';
+ out.push({ event, index, hash: ownedEntryFingerprint(group), lane, commands });
+ });
+ }
+ return out;
+}
+
+/**
+ * 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 by
+ * the wanted group (extra owned copies dropped), else the wanted group is
+ * appended; an unwanted event loses only its owned groups. Events in
+ * `preserve` (edited by the user) get no write. Foreign and edited groups are
+ * never touched. Returns each wanted group's final index (the trust key).
+ */
+export function writeCodexSetupHooks(hooksPath: string, opts: {
+ want: Partial<Record<CodexSetupEvent, CodexHookGroup>>;
+ owned: ReadonlySet<string>;
+ preserve: ReadonlySet<string>;
+ dryRun?: boolean;
+}): { changed: boolean; indexes: Partial<Record<CodexSetupEvent, number>>; notes: string[] } {
+ const { doc, hooks } = loadHooksJson(hooksPath);
+ const notes: string[] = [];
+ const indexes: Partial<Record<CodexSetupEvent, number>> = {};
+ const nextHooks: NonNullable<HooksJson['hooks']> = { ...hooks };
+ let changed = false;
+ for (const event of CODEX_SETUP_EVENTS) {
+ const groups = Array.isArray(hooks[event]) ? hooks[event]! : [];
+ const wanted = opts.preserve.has(event) ? undefined : opts.want[event];
+ const wantedHash = wanted ? ownedEntryFingerprint(wanted) : null;
+ const ours = groups.flatMap((g, i) => {
+ const h = ownedEntryFingerprint(g);
+ return opts.owned.has(h) || h === wantedHash ? [i] : [];
+ });
+ let next: typeof groups;
+ if (wanted) {
+ const first = ours[0];
+ next = first === undefined ? [...groups, wanted] : groups.flatMap((g, i) => (i === first ? [wanted] : ours.includes(i) ? [] : [g]));
+ indexes[event] = first ?? next.length - 1;
+ if (first !== undefined && ownedEntryFingerprint(groups[first]) === wantedHash && ours.length === 1) continue;
+ } else {
+ if (ours.length === 0) continue;
+ next = groups.filter((_, i) => !ours.includes(i));
+ }
+ const lastDropped = Math.max(-1, ...ours.filter((i) => !(wanted && i === ours[0])));
+ if (lastDropped >= 0 && lastDropped < groups.length - 1) {
+ notes.push(`${event}: removing setup's group shifted the ${groups.length - 1 - lastDropped} group(s) after it down one index, so codex treats their trust entries as stale; re-trust them in codex (/hooks) if they stop firing.`);
+ }
+ changed = true;
+ if (next.length > 0) nextHooks[event] = next;
+ else delete nextHooks[event];
+ }
+ if (changed && !opts.dryRun) atomicWriteTextFile(hooksPath, `${JSON.stringify({ ...doc, hooks: nextHooks }, null, 2)}\n`, { freshMode: 0o600 });
+ return { changed, indexes, notes };
+}
diff --git a/src/core/bootstrap/codex-toml.ts b/src/core/bootstrap/codex-toml.ts
index 69a9061577..c73bb2b339 100644
--- a/src/core/bootstrap/codex-toml.ts
+++ b/src/core/bootstrap/codex-toml.ts
@@ -323,3 +323,111 @@ export function removeCodexHttpServerBlock(
atomicWriteToml(configPath, nextText, crlf);
return { configPath, removed: true, backupPath, notes };
}
+
+// ── Hash-owned single tables (`gbrain setup codex`) ─────────────────────────
+//
+// Setup owns individual tables (`[mcp_servers.<name>]`, each
+// `[hooks.state."<key>"]`) by the fingerprint of their parsed value, not by
+// markers: codex itself may rewrite config.toml and drop comments. A table is
+// appended at EOF and removed by its header line through the next header;
+// both edits are verified by parsing: everything else in the file must parse
+// to exactly what it parsed to before, or the file is left as it was.
+
+export type CodexTomlValue = string | string[] | Record<string, string>;
+
+const tomlKey = (k: string): string => (/^[A-Za-z0-9_-]+$/.test(k) ? k : tomlString(k));
+
+export function codexTomlHeader(path: string[]): string {
+ return `[${path.map(tomlKey).join('.')}]`;
+}
+
+function renderTomlValue(v: CodexTomlValue): string {
+ if (typeof v === 'string') return tomlString(v);
+ if (Array.isArray(v)) return `[${v.map(tomlString).join(', ')}]`;
+ return `{ ${Object.entries(v).map(([k, val]) => `${tomlKey(k)} = ${tomlString(val)}`).join(', ')} }`;
+}
+
+/** The parsed value at `path`, or undefined. Throws when the file does not parse. */
+export function readCodexTomlTable(configPath: string, path: string[]): unknown {
+ if (!existsSync(configPath)) return undefined;
+ let node: unknown = parseToml(readFileSync(configPath, 'utf8'));
+ for (const seg of path) node = node && typeof node === 'object' && !Array.isArray(node) ? (node as Record<string, unknown>)[seg] : undefined;
+ return node;
+}
+
+const canonicalJson = (v: unknown): string => JSON.stringify(v, (_k, val) =>
+ val && typeof val === 'object' && !Array.isArray(val) ? Object.fromEntries(Object.keys(val).sort().map((k) => [k, (val as Record<string, unknown>)[k]])) : val);
+
+/** Delete `path` from a parsed document, then drop the ancestors that deletion emptied. */
+function withoutPath(doc: Record<string, unknown>, path: string[]): Record<string, unknown> {
+ const copy = JSON.parse(JSON.stringify(doc)) as Record<string, unknown>;
+ const chain: Array<Record<string, unknown>> = [copy];
+ for (const seg of path.slice(0, -1)) {
+ const next = chain[chain.length - 1]![seg];
+ if (!next || typeof next !== 'object' || Array.isArray(next)) return copy;
+ chain.push(next as Record<string, unknown>);
+ }
+ delete chain[chain.length - 1]![path[path.length - 1]!];
+ for (let i = chain.length - 1; i > 0; i--) {
+ if (Object.keys(chain[i]!).length > 0) break;
+ delete chain[i - 1]![path[i - 1]!];
+ }
+ return copy;
+}
+
+/**
+ * Append `[path]` with `value` at EOF (after an optional comment line). Refuses
+ * when the table already exists anywhere in the file (a duplicate table is a
+ * hard parse error that bricks codex) or when the result would not parse to
+ * the old document plus exactly this table.
+ */
+export function appendCodexTomlTable(configPath: string, path: string[], value: Record<string, CodexTomlValue>, comment?: string): void {
+ const raw = existsSync(configPath) ? readFileSync(configPath, 'utf8') : '';
+ const crlf = raw.includes('\r\n');
+ const text = raw.replace(/\r\n/g, '\n');
+ const before = parseToml(text);
+ if (readCodexTomlTable(configPath, path) !== undefined) throw new Error(`${configPath} already defines ${codexTomlHeader(path)}; setup never defines a table twice.`);
+ const block = [...(comment ? [`# ${comment}`] : []), codexTomlHeader(path), ...Object.entries(value).map(([k, v]) => `${tomlKey(k)} = ${renderTomlValue(v)}`)];
+ const body = text.replace(/\n*$/, '');
+ const next = `${body ? `${body}\n\n` : ''}${block.join('\n')}\n`;
+ const after = parseToml(next);
+ if (canonicalJson(withoutPath(after, path)) !== canonicalJson(before)) throw new Error(`appending ${codexTomlHeader(path)} to ${configPath} would change other settings; the file is left as it was.`);
+ let node: unknown = after;
+ for (const seg of path) node = (node as Record<string, unknown> | undefined)?.[seg];
+ if (canonicalJson(node) !== canonicalJson(value)) throw new Error(`${codexTomlHeader(path)} in ${configPath} did not parse back to what setup wrote; the file is left as it was.`);
+ atomicWriteTextFile(configPath, crlf ? next.replace(/\n/g, '\r\n') : next, { freshMode: 0o600 });
+}
+
+/**
+ * Remove `[path]`: its header line through the line before the next header
+ * (plus a directly preceding `# gbrain setup` comment and one separating blank
+ * line). `unlocatable` when no such header line exists or the edit would change
+ * anything but this table (it was split, re-rendered or extended); the file is
+ * then left as it was. The caller checks the table's fingerprint first.
+ */
+export function removeCodexTomlTable(configPath: string, path: string[], opts: { dryRun?: boolean } = {}): 'removed' | 'absent' | 'unlocatable' {
+ if (!existsSync(configPath)) return 'absent';
+ const raw = readFileSync(configPath, 'utf8');
+ const crlf = raw.includes('\r\n');
+ const lines = raw.replace(/\r\n/g, '\n').split('\n');
+ const before = parseToml(lines.join('\n'));
+ if (readCodexTomlTable(configPath, path) === undefined) return 'absent';
+ const header = codexTomlHeader(path);
+ const quoted = `[${path.map((seg) => tomlString(seg)).join('.')}]`;
+ const start = lines.findIndex((l) => l.trim() === header || l.trim() === quoted);
+ if (start < 0) return 'unlocatable';
+ let end = lines.findIndex((l, i) => i > start && /^\s*\[/.test(l));
+ if (end < 0) end = lines.length;
+ while (end > start + 1 && /^\s*(#.*)?$/.test(lines[end - 1]!)) end--;
+ let from = start;
+ if (from > 0 && lines[from - 1]!.startsWith('# gbrain setup')) from--;
+ if (from > 0 && lines[from - 1]!.trim() === '') from--;
+ const kept = [...lines.slice(0, from), ...lines.slice(end)];
+ while (kept.length > 0 && kept[kept.length - 1]!.trim() === '') kept.pop();
+ const next = kept.length > 0 ? `${kept.join('\n')}\n` : '';
+ let after: Record<string, unknown>;
+ try { after = parseToml(next); } catch { return 'unlocatable'; }
+ if (canonicalJson(after) !== canonicalJson(withoutPath(before, path))) return 'unlocatable';
+ if (!opts.dryRun) atomicWriteTextFile(configPath, crlf ? next.replace(/\n/g, '\r\n') : next, { freshMode: 0o600 });
+ return 'removed';
+}
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index fa5754c755..3a1363114c 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -547,6 +547,7 @@ export function buildConsentBlock(p: {
wireOpencode: boolean;
hooks: boolean;
capture: boolean;
+ codexCapture?: boolean; // Codex SessionEnd capture hook (hooks.json + its config.toml trust entry)
hookScope: string;
name: string;
userSettingsPath: string;
@@ -599,6 +600,7 @@ export function buildConsentBlock(p: {
` ${n++}. Codex (user-global): write [mcp_servers.${p.name}] with the bearer token INLINE into ` +
`${p.codexConfig} (0600) — framework-spawned codex inherits no shell env, so an env-var token would not reach it.`,
);
+ if (p.codexCapture) lines.push(` ${n++}. Codex session-transcript capture: a SessionEnd hook (hooks.json + its trust entry in ${p.codexConfig}) secret-scans and captures every Codex session's transcript into the brain's corpus. Opt out with the no-capture flag.`);
}
if (p.wireOpencode) {
lines.push(
@@ -624,8 +626,8 @@ export function buildConsentBlock(p: {
...(p.wireOpencode ? ['opencode'] : []),
];
const hosts = `EVERY ${hostNames.join(' and ')} session`;
- const hookLine = !p.wireClaude || !p.hooks
- ? 'No hooks are wired by this invocation.'
+ const hookLine = !(p.wireClaude && p.hooks)
+ ? (p.codexCapture ? 'One hook is wired: Codex SessionEnd transcript capture.' : 'No hooks are wired by this invocation.')
: p.capture
? 'Hooks run in every Claude Code session (context injection + transcript capture); auto-commit/push lanes stay inert outside gbrain agent workspaces.'
: 'Hooks run in every Claude Code session (context injection only — capture is OFF); auto-commit/push lanes stay inert outside gbrain agent workspaces.';
@@ -939,11 +941,8 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
// serve, but hooks always talk to the LOCAL brain (gbrain bin + local
// config) — wiring them here would split-brain the box. MCP only.
const registrarMode = flags.url !== undefined && !isLoopbackHostname(hostname);
- if (registrarMode && !flags.noHooks && wireClaude) {
- d.log(
- 'registrar mode (non-loopback url): hooks are NOT wired — they would talk to the LOCAL brain, ' +
- 'not the registered remote serve. MCP registration only.',
- );
+ if (registrarMode && !flags.noHooks && (wireClaude || wireCodex)) {
+ d.log('registrar mode (non-loopback url): hooks are NOT wired — they would talk to the LOCAL brain, not the registered remote serve. MCP registration only.');
}
const health = await probeServeHealth(url, d.fetchFn);
if (!health.ok) {
@@ -979,7 +978,8 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
: [];
// 3. Consent (connect --install shape; never the interview/A8 ledger).
- const wireHooks = wireClaude && !flags.noHooks && !registrarMode;
+ const wireHooks = wireClaude && !flags.noHooks && !registrarMode; // Codex capture below: same consent, never registrar
+ const wireCodexCapture = wireCodex && !flags.noHooks && !flags.noCapture && !registrarMode;
const priorState = readHarnessReceiptState(d.gbrainHome);
const prior = priorState.state === 'ok' ? priorState.receipt : null;
const skillsPolicy = flags.skills ?? prior?.skills_policy ?? (priorState.state === 'absent' ? 'follow' : 'memory-only');
@@ -995,6 +995,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
wireOpencode,
hooks: wireHooks,
capture: !flags.noCapture,
+ codexCapture: wireCodexCapture,
hookScope,
name: flags.name,
userSettingsPath: d.userSettingsPath,
@@ -1558,7 +1559,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
// (codex-hooks.ts) — idempotent, so a workspace-lane bootstrap and this
// harness lane converge on the same entry. No GBRAIN_SOURCE in the
// command (machine-global file; session-end resolves from the payload).
- if (!flags.noHooks) {
+ if (wireCodexCapture) {
const hooksBin = flags.gbrainBin ?? d.gbrainBin;
if (!hooksBin) {
d.logError('codex hooks skipped: cannot resolve an absolute gbrain binary path — pass --gbrain-bin <abs path>.');
diff --git a/src/core/bootstrap/host-specs.ts b/src/core/bootstrap/host-specs.ts
index 810010365c..c905bca761 100644
--- a/src/core/bootstrap/host-specs.ts
+++ b/src/core/bootstrap/host-specs.ts
@@ -110,7 +110,8 @@ export const TARGETS: Record<string, HostSpecTarget> = {
'remove` rewrites config.toml wholesale and drops comments, so the ' +
'stdio lane (runHooks) must never manage a name the harness block ' +
'owns, and vice versa. Codex 0.147.0 also ships a real hook system ' +
- '(hooks.json; PreToolUse…SessionEnd) — gbrain wires SessionEnd only ' +
+ '(hooks.json; PreToolUse…SessionEnd) — bootstrap wires SessionEnd; ' +
+ '`gbrain setup codex` also wires SessionStart/UserPromptSubmit, hash-owned ' +
'(CODEX_HAS_HOOKS=true; codex-hooks.ts owns the two-file write incl. ' +
'the config.toml trust entry, see CODEX_HOOKS_SPEC_TARGET there). ' +
'Some codex builds gate HTTP MCP servers behind ' +
diff --git a/src/core/setup/capabilities.ts b/src/core/setup/capabilities.ts
index bf10f1d340..34dd98fbd6 100644
--- a/src/core/setup/capabilities.ts
+++ b/src/core/setup/capabilities.ts
@@ -10,7 +10,7 @@
* meaning changes.
*/
-export const SETUP_CAPABILITY_TABLE_VERSION = 1;
+export const SETUP_CAPABILITY_TABLE_VERSION = 2;
export const SETUP_HARNESSES = ['claude-code', 'codex', 'openclaw', 'hermes'] as const;
export type SetupHarness = (typeof SETUP_HARNESSES)[number];
@@ -26,6 +26,8 @@ export interface SetupCapabilityRow {
pull: 'connection-verified' | 'manual';
/** Push without a tool call. `native-verified` requires an observed injected event. */
push: 'native-pending' | 'native-verified' | 'unsupported';
+ /** For `native-verified`: the harness version, date and observation that proved it. */
+ push_evidence?: string;
/** Events setup installs on a memory-only setup (read context only). */
read_events: readonly string[];
/** Events installed only after automatic capture is accepted. */
@@ -36,8 +38,9 @@ export interface SetupCapabilityRow {
export const SETUP_CAPABILITIES: readonly SetupCapabilityRow[] = [
{ harness: 'claude-code', transport: 'local-stdio', setup: 'supported', pull: 'connection-verified', push: 'native-pending',
read_events: ['SessionStart', 'UserPromptSubmit'], capture_events: ['Stop', 'SessionEnd'], docs: 'docs/mcp/CLAUDE_CODE.md' },
- { harness: 'codex', transport: 'local-stdio', setup: 'unsupported', pull: 'manual', push: 'native-pending',
- read_events: [], capture_events: ['SessionEnd'], docs: 'docs/mcp/CODEX.md' },
+ { harness: 'codex', transport: 'local-stdio', setup: 'supported', pull: 'connection-verified', push: 'native-verified',
+ push_evidence: 'codex-cli 0.162.1, 2026-10-12: after a fresh `gbrain setup codex`, the UserPromptSubmit hook injected a randomized brain item into a fresh native `codex exec` session, which answered it with no tool call (3/3 installs); a --no-hooks control answered NONE',
+ read_events: ['SessionStart', 'UserPromptSubmit'], capture_events: ['SessionEnd'], docs: 'docs/mcp/CODEX.md' },
{ harness: 'openclaw', transport: 'local-context-engine', setup: 'unsupported', pull: 'manual', push: 'native-pending',
read_events: [], capture_events: [], docs: 'docs/mcp/OPENCLAW.md' },
{ harness: 'openclaw', transport: 'thin-client', setup: 'unsupported', pull: 'manual', push: 'unsupported',
diff --git a/src/core/setup/claude-code.ts b/src/core/setup/claude-code.ts
index c9089b1710..2b8b8b5a50 100644
--- a/src/core/setup/claude-code.ts
+++ b/src/core/setup/claude-code.ts
@@ -23,6 +23,7 @@ import { createHash } from 'node:crypto';
import { existsSync, readFileSync, unlinkSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
+import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';
import { acquireBootstrapLock } from '../bootstrap/lock.ts';
import { buildClaudeHookCommand, classifyHarnessHook, hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../bootstrap/hooks.ts';
import {
@@ -110,11 +111,7 @@ export interface ClaudeInspection {
hooksCurrent: boolean;
}
-const canonical = (v: unknown): unknown =>
- Array.isArray(v) ? v.map(canonical)
- : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v as object).sort().map((k) => [k, canonical((v as Record<string, unknown>)[k])]))
- : v;
-export const entryHash = (v: unknown): string => createHash('sha256').update(JSON.stringify(canonical(v))).digest('hex');
+export const entryHash = ownedEntryFingerprint;
export function claudeSetupPaths(plan: Pick<ClaudeSetupPlan, 'name' | 'scope' | 'projectDir'>): { configPath: string; settingsPath: string; receiptPath: string } {
const configPath = claudeUserMcpConfigPath();
diff --git a/src/core/setup/codex.ts b/src/core/setup/codex.ts
new file mode 100644
index 0000000000..94b195d823
--- /dev/null
+++ b/src/core/setup/codex.ts
@@ -0,0 +1,439 @@
+/**
+ * Codex wiring for `gbrain setup codex`: the stdio MCP table
+ * `[mcp_servers.<name>]` in `$CODEX_HOME/config.toml`, setup's hook groups in
+ * `$CODEX_HOME/hooks.json` (SessionStart + UserPromptSubmit read context;
+ * SessionEnd capture only when accepted) and, for each group, the
+ * `[hooks.state."<hooks.json>:<event>:<index>:0"]` trust table Codex requires
+ * before it runs a user hook (without it the hook is listed and silently
+ * skipped).
+ *
+ * Ownership is a hash: every owned entry (the MCP table, each hooks.json
+ * group, each trust table) is fingerprinted with `ownedEntryFingerprint`
+ * (sha256 over canonical JSON of the exact parsed entry) and recorded per
+ * entry in the connection receipt `.gbrain-connection-codex-<name>.json`
+ * beside config.toml (the name `gbrain connect --install` uses; a receipt
+ * carrying `client_id` is a hosted one and is never adopted). Setup replaces
+ * or removes an entry only when its current fingerprint is one the receipt
+ * recorded (compare-and-swap); an edited entry is preserved and reported.
+ * Receipt schema: `setup_receipt_version: 2` = the claude-code receipt's
+ * fields plus `hooks_path`, `gbrain_home_env` and the per-event `trust` map.
+ *
+ * Write order, each step idempotent and resumable from the receipt:
+ * 1. receipt `prepared`: the consent record (three decisions) and the
+ * pending MCP and hook fingerprints, before anything else is written;
+ * 2. the MCP table, then the receipt records its fingerprint;
+ * 3. the hooks.json groups (inert until trusted), then the receipt records
+ * their fingerprints and the pending trust fingerprints;
+ * 4. the config.toml trust tables (activation, last), stale owned trust
+ * tables removed first; then the receipt records them;
+ * 5. receipt `installed`.
+ * `--remove` runs the reverse: trust, hooks, MCP, receipt. A crash anywhere
+ * leaves pending fingerprints the next run treats as owned, so a resume never
+ * duplicates an entry, and an untrusted hook never runs.
+ */
+import { existsSync, mkdirSync, readFileSync, unlinkSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
+import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';
+import { acquireBootstrapLock } from '../bootstrap/lock.ts';
+import { codexConfigPath } from '../bootstrap/host-specs.ts';
+import { appendCodexTomlTable, readCodexTomlTable, removeCodexTomlTable, type CodexTomlValue } from '../bootstrap/codex-toml.ts';
+import {
+ CODEX_SETUP_EVENTS,
+ CODEX_SETUP_LANE_TOKEN,
+ codexHookCensus,
+ codexSetupHookGroup,
+ codexSetupTrustEntry,
+ writeCodexSetupHooks,
+ type CodexHookGroup,
+ type CodexSetupEvent,
+} from '../bootstrap/codex-hooks.ts';
+import { stdioServeArgv } from '../mcp-registration.ts';
+import type { McpSurface } from '../../mcp/surface.ts';
+import { SetupAbortInjected, type SetupConsent, type SetupStep } from './claude-code.ts';
+
+export const CODEX_SETUP_RECEIPT_VERSION = 2;
+
+type Hashes = Partial<Record<CodexSetupEvent, string>>;
+interface TrustRecord { key: string; hash: string }
+type TrustRecords = Partial<Record<CodexSetupEvent, TrustRecord>>;
+
+export interface CodexSetupReceipt {
+ harness: 'codex';
+ connection: 'local-stdio';
+ setup_receipt_version: typeof CODEX_SETUP_RECEIPT_VERSION;
+ status: 'prepared' | 'installed' | 'removed';
+ name: string;
+ gbrain_home: string;
+ gbrain_home_env?: string;
+ launcher: string;
+ source_id: string | null;
+ surface: McpSurface;
+ config_path: string;
+ hooks_path: string;
+ entry_hash: string | null;
+ pending_entry_hash: string | null;
+ mcp_adopted?: boolean;
+ mcp_plugin?: string;
+ hooks: { owned: Hashes; pending: Hashes; edited: Hashes };
+ trust: { owned: TrustRecords; pending: TrustRecords; edited: TrustRecords };
+ consent: SetupConsent & { recorded_at: string };
+ brain_created_by_setup: boolean;
+ native_harness_verified: false;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface CodexSetupPlan {
+ name: string;
+ launcher: string;
+ brainHome: string;
+ gbrainHomeEnv?: string;
+ sourceId: string | null;
+ surface: McpSurface;
+ events: CodexSetupEvent[];
+}
+
+export type CodexSetupStep = Omit<SetupStep, 'step'> & { step: SetupStep['step'] | 'trust' };
+export interface CodexPreserved { kind: 'mcp' | 'hook' | 'trust'; event?: string; reason: 'edited' | 'adopted' | 'unlocatable' | 'conflict' }
+
+export interface CodexInspection {
+ configPath: string;
+ hooksPath: string;
+ receiptPath: string;
+ prior: CodexSetupReceipt | null;
+ hostedReceipt: { mcp_url?: string } | null;
+ mcp: { state: 'absent' | 'current' | 'owned' | 'remote' | 'unowned'; url?: string };
+ /** Events already wired by gbrain's bootstrap Codex lane (token-owned). */
+ otherLaneEvents: string[];
+ /** Owned events whose group the user edited: preserved, never rewritten. */
+ edited: Hashes;
+ hooksCurrent: boolean;
+ trustCurrent: boolean;
+}
+
+export function codexSetupPaths(name: string): { configPath: string; hooksPath: string; receiptPath: string } {
+ const configPath = codexConfigPath();
+ return { configPath, hooksPath: join(dirname(configPath), 'hooks.json'), receiptPath: join(dirname(configPath), `.gbrain-connection-codex-${name}.json`) };
+}
+
+export function readCodexSetupReceipt(receiptPath: string): { setup: CodexSetupReceipt | null; hosted: { mcp_url?: string } | null } {
+ if (!existsSync(receiptPath)) return { setup: null, hosted: null };
+ let raw: Record<string, unknown>;
+ try {
+ raw = JSON.parse(readFileSync(receiptPath, 'utf8')) as Record<string, unknown>;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('not an object');
+ } catch { throw new Error(`the connection receipt ${receiptPath} is unreadable; move it aside only if you know which install wrote it, then run setup again.`); }
+ if (raw.client_id) return { setup: null, hosted: { mcp_url: typeof raw.mcp_url === 'string' ? raw.mcp_url : undefined } };
+ if (raw.harness === 'codex' && raw.connection === 'local-stdio' && raw.setup_receipt_version === CODEX_SETUP_RECEIPT_VERSION) return { setup: raw as unknown as CodexSetupReceipt, hosted: null };
+ throw new Error(`the connection receipt ${receiptPath} was not written by gbrain setup; it is left untouched. Choose another --name.`);
+}
+
+const writeReceipt = (path: string, receipt: CodexSetupReceipt) => atomicWriteTextFile(path, `${JSON.stringify(receipt, null, 2)}\n`, { forceMode: 0o600 });
+
+export function desiredCodexMcpEntry(plan: Pick<CodexSetupPlan, 'launcher' | 'surface' | 'gbrainHomeEnv' | 'sourceId'>): Record<string, CodexTomlValue> {
+ const env: Record<string, string> = {};
+ if (plan.gbrainHomeEnv) env.GBRAIN_HOME = plan.gbrainHomeEnv;
+ if (plan.sourceId) env.GBRAIN_SOURCE = plan.sourceId;
+ return { command: plan.launcher, args: stdioServeArgv(plan.launcher, plan.surface).slice(1), ...(Object.keys(env).length ? { env } : {}) };
+}
+
+function desiredGroups(plan: CodexSetupPlan): Partial<Record<CodexSetupEvent, CodexHookGroup>> {
+ const env = { GBRAIN_HOME: plan.gbrainHomeEnv, GBRAIN_SOURCE: plan.sourceId ?? undefined };
+ return Object.fromEntries(plan.events.map((e) => [e, codexSetupHookGroup(plan.launcher, e, env)]));
+}
+
+const hashes = (groups: Partial<Record<CodexSetupEvent, CodexHookGroup>>): Hashes =>
+ Object.fromEntries(Object.entries(groups).map(([e, g]) => [e, ownedEntryFingerprint(g)]));
+const values = (h: Hashes | undefined): string[] => Object.values(h ?? {}).filter((v): v is string => typeof v === 'string');
+const trustPath = (key: string) => ['hooks', 'state', key];
+const trustFingerprint = (key: string, table: unknown) => ownedEntryFingerprint({ key, table });
+const consentValues = (c: SetupConsent): string => JSON.stringify([c.wiring_scope.value.hooks, c.capture.value, c.providers.value]);
+
+/** A setup-lane group of THIS install (its launcher and GBRAIN_HOME pin), whatever its fingerprint. */
+function isThisInstallsGroup(commands: string[], launcher: string, homeEnv: string | undefined): boolean {
+ return commands.some((c) => c.includes(CODEX_SETUP_LANE_TOKEN) && c.includes(launcher)
+ && (homeEnv ? c.includes(`GBRAIN_HOME=${homeEnv}`) : !c.includes('GBRAIN_HOME=')));
+}
+
+/** Desired trust records for the wanted groups at their current hooks.json indexes. */
+function desiredTrust(hooksPath: string, groups: Partial<Record<CodexSetupEvent, CodexHookGroup>>, indexes: Partial<Record<CodexSetupEvent, number>>): Array<{ event: CodexSetupEvent; key: string; table: { trusted_hash: string }; hash: string }> {
+ return (Object.keys(groups) as CodexSetupEvent[]).flatMap((event) => {
+ const index = indexes[event];
+ if (index === undefined) return [];
+ const { key, trusted_hash } = codexSetupTrustEntry(hooksPath, event, index, groups[event]!);
+ return [{ event, key, table: { trusted_hash }, hash: trustFingerprint(key, { trusted_hash }) }];
+ });
+}
+
+/** Read-only: what setup would find and own. Throws on an unparseable config or hooks file. */
+export function inspectCodexSetup(plan: CodexSetupPlan): CodexInspection {
+ const paths = codexSetupPaths(plan.name);
+ const { setup: prior, hosted } = readCodexSetupReceipt(paths.receiptPath);
+ const entry = readCodexTomlTable(paths.configPath, ['mcp_servers', plan.name]);
+ const desired = ownedEntryFingerprint(desiredCodexMcpEntry(plan));
+ const entryFp = entry === undefined ? null : ownedEntryFingerprint(entry);
+ const mcp: CodexInspection['mcp'] = entry === undefined ? { state: 'absent' }
+ : entryFp === desired ? { state: 'current' }
+ : typeof (entry as Record<string, unknown>)?.url === 'string' ? { state: 'remote', url: (entry as Record<string, string>).url }
+ : prior && [prior.entry_hash, prior.pending_entry_hash].includes(entryFp) ? { state: 'owned' } : { state: 'unowned' };
+
+ const census = codexHookCensus(paths.hooksPath);
+ const groups = desiredGroups(plan);
+ const want = hashes(groups);
+ const owned = new Set([...values(prior?.hooks.owned), ...values(prior?.hooks.pending), ...values(want)]);
+ const edited: Hashes = {};
+ for (const event of CODEX_SETUP_EVENTS) {
+ const present = census.filter((g) => g.event === event);
+ const priorEdit = prior?.hooks.edited[event];
+ const recorded = prior?.hooks.owned[event];
+ if (priorEdit && present.some((g) => g.hash === priorEdit)) { edited[event] = priorEdit; continue; }
+ const candidate = recorded && !present.some((g) => g.hash === recorded)
+ ? present.find((g) => !owned.has(g.hash) && isThisInstallsGroup(g.commands, plan.launcher, plan.gbrainHomeEnv)) : undefined;
+ if (candidate) edited[event] = candidate.hash;
+ }
+ let hooksCurrent = true;
+ const indexes: Partial<Record<CodexSetupEvent, number>> = {};
+ for (const g of census) {
+ const target = want[g.event as CodexSetupEvent];
+ if (owned.has(g.hash) && g.hash !== target) hooksCurrent = false;
+ if (target && g.hash === target) {
+ if (indexes[g.event as CodexSetupEvent] !== undefined) hooksCurrent = false;
+ indexes[g.event as CodexSetupEvent] = g.index;
+ }
+ }
+ for (const event of plan.events) if (!edited[event] && indexes[event] === undefined) hooksCurrent = false;
+
+ let trustCurrent = hooksCurrent;
+ if (trustCurrent) {
+ const wanted = desiredTrust(paths.hooksPath, Object.fromEntries(Object.entries(groups).filter(([e]) => !edited[e as CodexSetupEvent])), indexes);
+ for (const t of wanted) if (trustFingerprint(t.key, readCodexTomlTable(paths.configPath, trustPath(t.key))) !== t.hash) trustCurrent = false;
+ for (const rec of [...Object.values(prior?.trust.owned ?? {}), ...Object.values(prior?.trust.pending ?? {})]) {
+ if (!rec || wanted.some((t) => t.key === rec.key && t.hash === rec.hash)) continue;
+ if (trustFingerprint(rec.key, readCodexTomlTable(paths.configPath, trustPath(rec.key))) === rec.hash) trustCurrent = false;
+ }
+ }
+ const otherLaneEvents = [...new Set(census.filter((g) => g.lane === 'bootstrap').map((g) => g.event))];
+ return { ...paths, prior, hostedReceipt: hosted, mcp, otherLaneEvents, edited, hooksCurrent, trustCurrent };
+}
+
+export interface CodexApplyResult { steps: CodexSetupStep[]; receipt: CodexSetupReceipt; changed: boolean; preserved: CodexPreserved[]; notes: string[] }
+
+/**
+ * Apply the plan under the Codex config-dir lock, in the write order above.
+ * `pluginOwner` skips the MCP table (the gbrain Codex plugin serves the name);
+ * `beforeMcp` runs after the receipt is prepared (the brain init step);
+ * `abortAfter` is the crash-injection test seam.
+ */
+export async function applyCodexSetup(
+ plan: CodexSetupPlan,
+ consent: SetupConsent,
+ opts: { pluginOwner: string | null; brainCreated: boolean; beforeMcp?: () => Promise<void>; abortAfter?: string },
+): Promise<CodexApplyResult> {
+ const paths = codexSetupPaths(plan.name);
+ mkdirSync(dirname(paths.configPath), { recursive: true, mode: 0o700 });
+ const lock = await acquireBootstrapLock(dirname(paths.configPath));
+ try {
+ const found = inspectCodexSetup(plan);
+ const prior = found.prior;
+ const now = new Date().toISOString();
+ const desired = desiredCodexMcpEntry(plan);
+ const desiredHash = ownedEntryFingerprint(desired);
+ const groups = desiredGroups(plan);
+ const writeGroups = Object.fromEntries(Object.entries(groups).filter(([e]) => !found.edited[e as CodexSetupEvent])) as Partial<Record<CodexSetupEvent, CodexHookGroup>>;
+ const want = hashes(writeGroups);
+ const steps: CodexSetupStep[] = [];
+ const preserved: CodexPreserved[] = Object.keys(found.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' }));
+ const notes: string[] = [];
+ const mcpDone = opts.pluginOwner !== null || found.mcp.state === 'current';
+ const consentSame = prior?.consent !== undefined && consentValues(prior.consent) === consentValues(consent);
+ if (prior?.status === 'installed' && consentSame && mcpDone && found.hooksCurrent && found.trustCurrent && !opts.brainCreated) {
+ steps.push({ step: 'receipt', action: 'keep', detail: `${paths.receiptPath} already records this install` });
+ steps.push({ step: 'mcp', action: opts.pluginOwner ? 'skip' : 'keep', detail: opts.pluginOwner ? `the '${opts.pluginOwner}' plugin serves '${plan.name}'` : `[mcp_servers.${plan.name}] in ${paths.configPath} is current` });
+ steps.push({ step: 'hooks', action: 'keep', detail: plan.events.length ? `${plan.events.join(', ')} in ${paths.hooksPath} are current` : 'no hooks wanted' });
+ steps.push({ step: 'trust', action: 'keep', detail: plan.events.length ? `trust entries in ${paths.configPath} are current` : 'no trust entries wanted' });
+ for (const p of preserved) steps.push({ step: 'hooks', action: 'preserve', detail: `${p.event} in ${paths.hooksPath} was edited after setup wrote it; kept as is` });
+ return { steps, receipt: prior, changed: false, preserved, notes };
+ }
+
+ const receipt: CodexSetupReceipt = {
+ harness: 'codex', connection: 'local-stdio', setup_receipt_version: CODEX_SETUP_RECEIPT_VERSION, status: 'prepared',
+ name: plan.name, gbrain_home: plan.brainHome, ...(plan.gbrainHomeEnv ? { gbrain_home_env: plan.gbrainHomeEnv } : {}),
+ launcher: plan.launcher, source_id: plan.sourceId, surface: plan.surface,
+ config_path: paths.configPath, hooks_path: paths.hooksPath,
+ entry_hash: prior?.entry_hash ?? null, pending_entry_hash: opts.pluginOwner ? null : desiredHash,
+ ...(prior?.mcp_adopted ? { mcp_adopted: true } : {}),
+ ...(opts.pluginOwner ? { mcp_plugin: opts.pluginOwner } : {}),
+ hooks: { owned: prior?.hooks.owned ?? {}, pending: want, edited: found.edited },
+ trust: { owned: prior?.trust.owned ?? {}, pending: prior?.trust.pending ?? {}, edited: prior?.trust.edited ?? {} },
+ consent: { ...consent, recorded_at: now },
+ brain_created_by_setup: (prior?.brain_created_by_setup ?? false) || opts.brainCreated,
+ native_harness_verified: false,
+ created_at: prior?.created_at ?? now, updated_at: now,
+ };
+ const save = () => writeReceipt(paths.receiptPath, receipt);
+ save();
+ steps.push({ step: 'receipt', action: 'write', detail: `${paths.receiptPath} (prepared: consent and pending fingerprints recorded)` });
+ if (opts.abortAfter === 'receipt') throw new SetupAbortInjected('receipt');
+ await opts.beforeMcp?.();
+
+ // 2. MCP table.
+ if (opts.pluginOwner) {
+ steps.push({ step: 'mcp', action: 'skip', detail: `the '${opts.pluginOwner}' plugin serves '${plan.name}'; no hand-wired table` });
+ } else if (found.mcp.state === 'current') {
+ if (!prior?.entry_hash && !prior?.pending_entry_hash) receipt.mcp_adopted = true;
+ steps.push({ step: 'mcp', action: 'keep', detail: `[mcp_servers.${plan.name}] in ${paths.configPath} is current${receipt.mcp_adopted ? ' (adopted: it was already there, so --remove keeps it)' : ''}` });
+ } else {
+ if (found.mcp.state === 'owned' && removeCodexTomlTable(paths.configPath, ['mcp_servers', plan.name]) === 'unlocatable') {
+ throw new Error(`[mcp_servers.${plan.name}] in ${paths.configPath} is setup's but was re-rendered in a shape setup cannot rewrite safely; remove that table by hand, then run setup again.`);
+ }
+ appendCodexTomlTable(paths.configPath, ['mcp_servers', plan.name], desired, `gbrain setup (${plan.name}): owned by fingerprint; \`gbrain setup codex --remove\` deletes it while unchanged`);
+ delete receipt.mcp_adopted;
+ steps.push({ step: 'mcp', action: 'write', detail: `[mcp_servers.${plan.name}] in ${paths.configPath}` });
+ }
+ if (!opts.pluginOwner) receipt.entry_hash = desiredHash;
+ receipt.pending_entry_hash = null;
+ save();
+ if (opts.abortAfter === 'mcp') throw new SetupAbortInjected('mcp');
+
+ // 3. hooks.json groups (inert until trusted).
+ const ownedHooks = new Set([...values(prior?.hooks.owned), ...values(prior?.hooks.pending), ...values(want)]);
+ const w = writeCodexSetupHooks(paths.hooksPath, { want: writeGroups, owned: ownedHooks, preserve: new Set(Object.keys(found.edited)) });
+ notes.push(...w.notes);
+ const written = Object.keys(writeGroups);
+ steps.push(w.changed
+ ? { step: 'hooks', action: 'write', detail: written.length ? `${written.join(', ')} in ${paths.hooksPath}` : `removed setup's groups from ${paths.hooksPath}` }
+ : { step: 'hooks', action: 'keep', detail: written.length ? `${written.join(', ')} in ${paths.hooksPath} are current` : 'no hooks wanted' });
+ for (const event of Object.keys(found.edited)) steps.push({ step: 'hooks', action: 'preserve', detail: `${event} in ${paths.hooksPath} was edited after setup wrote it; kept as is (and left untrusted by setup)` });
+ receipt.hooks.owned = want;
+ receipt.hooks.pending = {};
+ const wanted = desiredTrust(paths.hooksPath, writeGroups, w.indexes);
+ receipt.trust.pending = Object.fromEntries(wanted.map((t) => [t.event, { key: t.key, hash: t.hash }]));
+ save();
+ if (opts.abortAfter === 'hooks') throw new SetupAbortInjected('hooks');
+
+ // 4. Trust tables: drop stale owned ones (an index or command change), then add the wanted ones.
+ const trustEdited: TrustRecords = { ...receipt.trust.edited };
+ const ownedTrust = [...Object.entries(prior?.trust.owned ?? {}), ...Object.entries(prior?.trust.pending ?? {})] as Array<[CodexSetupEvent, TrustRecord]>;
+ for (const [event, rec] of ownedTrust) {
+ if (wanted.some((t) => t.key === rec.key && t.hash === rec.hash)) continue;
+ const table = readCodexTomlTable(paths.configPath, trustPath(rec.key));
+ if (table === undefined) continue;
+ if (trustFingerprint(rec.key, table) !== rec.hash) {
+ trustEdited[event] = { key: rec.key, hash: trustFingerprint(rec.key, table) };
+ preserved.push({ kind: 'trust', event, reason: 'edited' });
+ steps.push({ step: 'trust', action: 'preserve', detail: `[hooks.state."${rec.key}"] changed after setup wrote it; kept` });
+ continue;
+ }
+ const r = removeCodexTomlTable(paths.configPath, trustPath(rec.key));
+ if (r === 'unlocatable') {
+ preserved.push({ kind: 'trust', event, reason: 'unlocatable' });
+ steps.push({ step: 'trust', action: 'preserve', detail: `[hooks.state."${rec.key}"] could not be located as one table; kept` });
+ } else steps.push({ step: 'trust', action: 'remove', detail: `stale [hooks.state."${rec.key}"] (setup's ${event} group moved or changed)` });
+ }
+ const trusted: TrustRecords = {};
+ for (const t of wanted) {
+ const table = readCodexTomlTable(paths.configPath, trustPath(t.key));
+ if (table !== undefined && trustFingerprint(t.key, table) === t.hash) {
+ trusted[t.event] = { key: t.key, hash: t.hash };
+ steps.push({ step: 'trust', action: 'keep', detail: `${t.event} is trusted in ${paths.configPath}` });
+ } else if (table !== undefined) {
+ preserved.push({ kind: 'trust', event: t.event, reason: 'conflict' });
+ steps.push({ step: 'trust', action: 'preserve', detail: `${paths.configPath} already has a different [hooks.state."${t.key}"]; kept, so codex will ask before running setup's ${t.event} hook` });
+ } else {
+ appendCodexTomlTable(paths.configPath, trustPath(t.key), t.table, `gbrain setup (${plan.name}): trusts setup's ${t.event} hook; owned by fingerprint`);
+ trusted[t.event] = { key: t.key, hash: t.hash };
+ steps.push({ step: 'trust', action: 'write', detail: `${t.event} trust entry in ${paths.configPath}` });
+ }
+ }
+ if (wanted.length === 0 && !steps.some((s) => s.step === 'trust')) steps.push({ step: 'trust', action: 'keep', detail: 'no trust entries wanted' });
+ receipt.trust = { owned: trusted, pending: {}, edited: trustEdited };
+ save();
+ if (opts.abortAfter === 'trust') throw new SetupAbortInjected('trust');
+ receipt.status = 'installed';
+ save();
+ return { steps, receipt, changed: true, preserved, notes };
+ } finally {
+ lock.release();
+ }
+}
+
+export interface CodexRemoveResult { steps: CodexSetupStep[]; preserved: CodexPreserved[]; notes: string[]; receiptRemoved: boolean }
+
+/** Remove exactly what the receipt owns by fingerprint (trust, hooks, MCP, receipt); edited entries survive and are reported. */
+export async function removeCodexSetup(receipt: CodexSetupReceipt, receiptPath: string, opts: { dryRun: boolean }): Promise<CodexRemoveResult> {
+ const lock = await acquireBootstrapLock(dirname(receipt.config_path));
+ try {
+ const steps: CodexSetupStep[] = [];
+ const preserved: CodexPreserved[] = [];
+ const notes: string[] = [];
+ const trustEdited: TrustRecords = {};
+ for (const [event, rec] of [...Object.entries(receipt.trust.owned), ...Object.entries(receipt.trust.pending)] as Array<[CodexSetupEvent, TrustRecord]>) {
+ const table = readCodexTomlTable(receipt.config_path, trustPath(rec.key));
+ if (table === undefined) continue;
+ if (trustFingerprint(rec.key, table) !== rec.hash) {
+ trustEdited[event] = { key: rec.key, hash: trustFingerprint(rec.key, table) };
+ preserved.push({ kind: 'trust', event, reason: 'edited' });
+ steps.push({ step: 'trust', action: 'preserve', detail: `[hooks.state."${rec.key}"] changed after setup wrote it; kept` });
+ } else if (removeCodexTomlTable(receipt.config_path, trustPath(rec.key), { dryRun: opts.dryRun }) === 'unlocatable') {
+ preserved.push({ kind: 'trust', event, reason: 'unlocatable' });
+ steps.push({ step: 'trust', action: 'preserve', detail: `[hooks.state."${rec.key}"] could not be located as one table; kept` });
+ } else steps.push({ step: 'trust', action: 'remove', detail: `${event} trust entry from ${receipt.config_path}` });
+ }
+
+ const owned = new Set([...values(receipt.hooks.owned), ...values(receipt.hooks.pending)]);
+ const census = codexHookCensus(receipt.hooks_path);
+ const removedGroups = census.filter((g) => owned.has(g.hash));
+ const w = writeCodexSetupHooks(receipt.hooks_path, { want: {}, owned, preserve: new Set(), dryRun: opts.dryRun });
+ notes.push(...w.notes);
+ steps.push(removedGroups.length
+ ? { step: 'hooks', action: 'remove', detail: `${removedGroups.map((g) => g.event).join(', ')} from ${receipt.hooks_path}` }
+ : { step: 'hooks', action: 'skip', detail: `no owned groups in ${receipt.hooks_path}` });
+ const edited: Hashes = {};
+ for (const event of CODEX_SETUP_EVENTS) {
+ const recorded = receipt.hooks.owned[event] ?? receipt.hooks.pending[event];
+ const present = census.filter((g) => g.event === event && !owned.has(g.hash));
+ const hit = present.find((g) => g.hash === receipt.hooks.edited[event])
+ ?? (recorded && !census.some((g) => g.hash === recorded) ? present.find((g) => isThisInstallsGroup(g.commands, receipt.launcher, receipt.gbrain_home_env)) : undefined);
+ if (!hit) continue;
+ edited[event] = hit.hash;
+ preserved.push({ kind: 'hook', event, reason: 'edited' });
+ steps.push({ step: 'hooks', action: 'preserve', detail: `${event} in ${receipt.hooks_path} was edited after setup wrote it; kept` });
+ }
+
+ const entry = readCodexTomlTable(receipt.config_path, ['mcp_servers', receipt.name]);
+ const entryFp = entry === undefined ? null : ownedEntryFingerprint(entry);
+ if (receipt.mcp_plugin) {
+ steps.push({ step: 'mcp', action: 'skip', detail: `the '${receipt.mcp_plugin}' plugin serves '${receipt.name}'; setup wrote no table` });
+ } else if (entry === undefined) {
+ steps.push({ step: 'mcp', action: 'skip', detail: `no [mcp_servers.${receipt.name}] in ${receipt.config_path}` });
+ } else if (receipt.mcp_adopted && entryFp === receipt.entry_hash) {
+ preserved.push({ kind: 'mcp', reason: 'adopted' });
+ steps.push({ step: 'mcp', action: 'preserve', detail: `[mcp_servers.${receipt.name}] existed before setup ran; kept` });
+ } else if ([receipt.entry_hash, receipt.pending_entry_hash].includes(entryFp)) {
+ if (removeCodexTomlTable(receipt.config_path, ['mcp_servers', receipt.name], { dryRun: opts.dryRun }) === 'unlocatable') {
+ preserved.push({ kind: 'mcp', reason: 'unlocatable' });
+ steps.push({ step: 'mcp', action: 'preserve', detail: `[mcp_servers.${receipt.name}] could not be located as one table; kept` });
+ } else steps.push({ step: 'mcp', action: 'remove', detail: `[mcp_servers.${receipt.name}] from ${receipt.config_path}` });
+ } else {
+ preserved.push({ kind: 'mcp', reason: 'edited' });
+ steps.push({ step: 'mcp', action: 'preserve', detail: `[mcp_servers.${receipt.name}] in ${receipt.config_path} changed after setup wrote it; kept` });
+ }
+
+ let receiptRemoved = false;
+ if (!opts.dryRun) {
+ if (preserved.some((p) => p.reason === 'edited')) {
+ writeReceipt(receiptPath, { ...receipt, status: 'removed', entry_hash: null, pending_entry_hash: null,
+ hooks: { owned: {}, pending: {}, edited }, trust: { owned: {}, pending: {}, edited: trustEdited }, updated_at: new Date().toISOString() });
+ steps.push({ step: 'receipt', action: 'write', detail: `${receiptPath} (removed; remembers the edited entries so a later setup leaves them alone)` });
+ } else {
+ if (existsSync(receiptPath)) unlinkSync(receiptPath);
+ receiptRemoved = true;
+ steps.push({ step: 'receipt', action: 'remove', detail: receiptPath });
+ }
+ }
+ return { steps, preserved, notes, receiptRemoved };
+ } finally {
+ lock.release();
+ }
+}
diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.ts
index 412d648799..07fa3a0bab 100644
--- a/test/bootstrap-harness.serial.test.ts
+++ b/test/bootstrap-harness.serial.test.ts
@@ -460,6 +460,25 @@ describe('full apply', () => {
expect(readFileSync(f2.codexConfig, 'utf8')).toContain('http://192.168.1.50:3131/mcp');
});
+ test('registrar mode wires no Codex capture hook, the same recorded consent as the Claude lane (MCP only)', async () => {
+ const f = makeFake();
+ const code = await applyHarness(flags(['--url', 'http://192.168.1.50:3131/mcp', '--token', TOKEN_A, '--harness', 'codex']), f.deps);
+ expect(code).toBe(0);
+ expect(f.out.join('\n')).toContain('No hooks are wired by this invocation.');
+ expect(existsSync(join(dirname(f.codexConfig), 'hooks.json'))).toBe(false);
+ expect(readFileSync(f.codexConfig, 'utf8')).not.toContain('gbrain:codex-hooks-trust');
+ });
+
+ test('--no-capture declines the Codex SessionEnd capture hook (capture is its own consent item)', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags(['--harness', 'codex', '--no-capture']), f.deps)).toBe(0);
+ expect(existsSync(join(dirname(f.codexConfig), 'hooks.json'))).toBe(false);
+ const g = makeFake();
+ expect(await applyHarness(flags(['--harness', 'codex']), g.deps)).toBe(0);
+ expect(g.out.join('\n')).toMatch(/Codex session-transcript capture/);
+ expect(readFileSync(join(dirname(g.codexConfig), 'hooks.json'), 'utf8')).toContain('hook session-end --harness codex');
+ });
+
test('--project must exist [F4]', async () => {
const f = makeFake();
const code = await applyHarness(flags(['--project', '/definitely/not/a/dir']), f.deps);
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 4a4310b130..0d8266e87f 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -13,7 +13,8 @@
"SETUP",
" mcp grant <name> --help Grant hosted access; private credential handoff",
" mcp verify --help Verify connection, permissions, and memory",
- " setup claude-code [--dry-run] Give an agent memory: brain + MCP + hooks, verified (--remove undoes)",
+ " setup claude-code|codex [--dry-run]",
+ " Give an agent memory: brain + MCP + hooks, verified (--remove undoes)",
" init [--pglite|--supabase|--url] Create brain (PGLite default, no server)",
" init --prefer-postgres [--allow-docker]",
" Postgres-first install ladder (env URL >",
@@ -227,7 +228,8 @@
"SETUP",
" mcp grant <name> --help Grant hosted access; private credential handoff",
" mcp verify --help Verify connection, permissions, and memory",
- " setup claude-code [--dry-run] Give an agent memory: brain + MCP + hooks, verified (--remove undoes)",
+ " setup claude-code|codex [--dry-run]",
+ " Give an agent memory: brain + MCP + hooks, verified (--remove undoes)",
" init [--pglite|--supabase|--url] Create brain (PGLite default, no server)",
" init --prefer-postgres [--allow-docker]",
" Postgres-first install ladder (env URL >",
@@ -441,7 +443,8 @@
"SETUP",
" mcp grant <name> --help Grant hosted access; private credential handoff",
" mcp verify --help Verify connection, permissions, and memory",
- " setup claude-code [--dry-run] Give an agent memory: brain + MCP + hooks, verified (--remove undoes)",
+ " setup claude-code|codex [--dry-run]",
+ " Give an agent memory: brain + MCP + hooks, verified (--remove undoes)",
" init [--pglite|--supabase|--url] Create brain (PGLite default, no server)",
" init --prefer-postgres [--allow-docker]",
" Postgres-first install ladder (env URL >",
diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.ts
index 0f9019c300..6bd717740f 100644
--- a/test/hook-command.serial.test.ts
+++ b/test/hook-command.serial.test.ts
@@ -454,6 +454,30 @@ describe('user-prompt', () => {
expect(STARTUP_HOOK_SKIP_COMMANDS.has('hook')).toBe(true);
});
+ test('--harness codex confines the transcript to the Codex rollout store and parses it as a rollout (#5941)', async () => {
+ const dataDir = join(tmp, 'data');
+ writePgliteConfig(dataDir);
+ const seen: TurnContextRequest[] = [];
+ await startServer({ dataDir, blockText: 'ok', onRequest: (r) => { seen.push(r); } });
+ const savedCodexHome = process.env.CODEX_HOME;
+ process.env.CODEX_HOME = join(tmp, 'codex');
+ try {
+ const day = join(tmp, 'codex', 'sessions', '2026', '10', '12');
+ mkdirSync(day, { recursive: true });
+ const rollout = join(day, 'rollout-2026-10-12T00-00-00-s-codex.jsonl');
+ writeFileSync(rollout, `${JSON.stringify({ timestamp: 't1', type: 'event_msg', payload: { type: 'user_message', message: 'earlier question about Acme' } })}\n`);
+ const out = collectStdout();
+ expect(await runHook(['user-prompt', '--harness', 'codex'], { ...out.io, stdin: JSON.stringify({ prompt: 'and now?', transcript_path: rollout, session_id: 's-codex' }) })).toBe(0);
+ expect((await lastHeartbeat())?.reason).not.toBe('transcript_outside_projects_dir');
+ expect(seen).toHaveLength(1);
+ expect(seen[0].window.map((t) => t.text)).toEqual(['earlier question about Acme', 'and now?']);
+ expect(JSON.parse(out.get()).hookSpecificOutput.additionalContext).toContain('ok');
+ } finally {
+ if (savedCodexHome === undefined) delete process.env.CODEX_HOME;
+ else process.env.CODEX_HOME = savedCodexHome;
+ }
+ });
+
test('confinement rejection aborts: heartbeat + exit 0 empty [S3#8]', async () => {
const dataDir = join(tmp, 'data');
writePgliteConfig(dataDir);
diff --git a/test/setup.test.ts b/test/setup.test.ts
index 2c0ba06280..07bbecf88c 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -25,6 +25,8 @@ import { join, resolve } from 'node:path';
import { runCli, type CliResult } from './helpers/cli-spawn.ts';
import { hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../src/core/bootstrap/hooks.ts';
import { GBRAIN_HOOK_MARKER_VALUE } from '../src/core/bootstrap/host-specs.ts';
+import { codexHookTrustHash, codexTrustHash, removeCodexHooks, writeCodexHooks } from '../src/core/bootstrap/codex-hooks.ts';
+import { appendCodexTomlTable, removeCodexTomlTable } from '../src/core/bootstrap/codex-toml.ts';
const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');
const roots: string[] = [];
@@ -44,7 +46,7 @@ function box(): Box {
return { root, home, gbrainHome: home, bin };
}
-const CLEAN = { CLAUDE_CONFIG_DIR: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, GBRAIN_HOOKS: undefined, GBRAIN_SETUP_ABORT_AFTER: undefined };
+const CLEAN = { CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, GBRAIN_HOOKS: undefined, GBRAIN_SETUP_ABORT_AFTER: undefined };
async function setup(b: Box, args: string[], env: Record<string, string | undefined> = {}): Promise<CliResult & { doc: any }> {
const r = await runCli(['setup', ...args, '--gbrain-bin', b.bin], { env: { ...CLEAN, HOME: b.home, GBRAIN_HOME: b.gbrainHome, ...env } });
@@ -330,7 +332,7 @@ describe('gbrain setup: consent and refusals', () => {
expect(readJson(claudeJson(b)).mcpServers.gbrain).toBeDefined();
});
- for (const [harness, guide] of [['codex', 'docs/mcp/CODEX.md'], ['openclaw', 'docs/mcp/OPENCLAW.md'], ['hermes', 'docs/mcp/HERMES.md']] as const) {
+ for (const [harness, guide] of [['openclaw', 'docs/mcp/OPENCLAW.md'], ['hermes', 'docs/mcp/HERMES.md']] as const) {
test(`${harness} is a coded refusal that names its guide`, async () => {
const b = box();
const r = await setup(b, [harness, '--json']);
@@ -381,3 +383,341 @@ describe('hooks.ts ownership: hash-keyed for setup, marker-keyed for bootstrap (
expect(hookEntryHash({ type: 'other' })).toBeNull();
});
});
+
+// ── gbrain setup codex ──────────────────────────────────────────────────────
+
+const codexDir = (b: Box) => join(b.home, '.codex');
+const codexToml = (b: Box) => join(codexDir(b), 'config.toml');
+const hooksJson = (b: Box) => join(codexDir(b), 'hooks.json');
+const codexReceipt = (b: Box, name = 'gbrain') => join(codexDir(b), `.gbrain-connection-codex-${name}.json`);
+const toml = (b: Box): any => Bun.TOML.parse(readFileSync(codexToml(b), 'utf8'));
+const trustKeys = (b: Box): string[] => Object.keys(toml(b).hooks?.state ?? {}).sort();
+const trustKey = (b: Box, event: string, index: number) => `${hooksJson(b)}:${event}:${index}:0`;
+/** Matcher groups under one hooks.json event. */
+function groups(b: Box, event: string): any[] {
+ if (!existsSync(hooksJson(b))) return [];
+ return readJson(hooksJson(b)).hooks?.[event] ?? [];
+}
+const setupGroups = (b: Box, event: string) => groups(b, event).filter((g) => g.hooks?.[0]?.command?.includes('GBRAIN_HOOK_LANE=setup'));
+
+describe('gbrain setup codex: install lifecycle', () => {
+ test('fresh install: keyless brain, MCP table, read-context hooks and their trust entries only, verified; a second run changes nothing', async () => {
+ const b = box();
+ const first = await setup(b, ['codex', '--json']);
+ expect(first.exitCode).toBe(0);
+ expect(first.doc.harness).toBe('codex');
+ expect(first.doc.target).toMatchObject({ brain: { kind: 'new-local-pglite' }, launcher: b.bin, config_path: codexToml(b), hooks_path: hooksJson(b) });
+ expect(first.doc.verify.reason).toBe('smoke_passed');
+ expect(first.doc.states).toEqual(['configured', 'connection-verified', 'native-verified']);
+ expect(first.doc.capability).toMatchObject({ harness: 'codex', setup: 'supported', push: 'native-verified', read_events: ['SessionStart', 'UserPromptSubmit'] });
+ expect(first.doc.consent.capture).toMatchObject({ value: 'declined', source: 'default' });
+ expect(readJson(join(b.gbrainHome, '.gbrain', 'config.json')).embedding_disabled).toBe(true);
+ expect(toml(b).mcp_servers.gbrain).toEqual({ command: b.bin, args: ['serve', '--surface', 'full'], env: { GBRAIN_HOME: b.gbrainHome } });
+ expect(Object.keys(readJson(hooksJson(b)).hooks).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);
+ expect(groups(b, 'UserPromptSubmit')).toEqual([{ hooks: [{ type: 'command', timeout: 15,
+ command: `env GBRAIN_HOOK_LANE=setup GBRAIN_HOME=${b.gbrainHome} ${b.bin} hook user-prompt --harness codex` }] }]);
+ expect(trustKeys(b)).toEqual([trustKey(b, 'session_start', 0), trustKey(b, 'user_prompt_submit', 0)]);
+ const r = readJson(codexReceipt(b));
+ expect(r).toMatchObject({ harness: 'codex', connection: 'local-stdio', setup_receipt_version: 2, status: 'installed' });
+ expect(Object.keys(r.hooks.owned).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);
+ expect(Object.keys(r.trust.owned).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);
+
+ const before = [codexToml(b), hooksJson(b), codexReceipt(b)].map((p) => readFileSync(p, 'utf8'));
+ const second = await setup(b, ['codex', '--json']);
+ expect(second.exitCode).toBe(0);
+ expect(second.doc.steps.map((s: any) => [s.step, s.action])).toEqual([['receipt', 'keep'], ['mcp', 'keep'], ['hooks', 'keep'], ['trust', 'keep']]);
+ expect([codexToml(b), hooksJson(b), codexReceipt(b)].map((p) => readFileSync(p, 'utf8'))).toEqual(before);
+ });
+
+ test('--remove deletes exactly the owned entries; foreign config, hooks, trust entries and the brain stay byte-for-byte', async () => {
+ const b = box();
+ mkdirSync(codexDir(b), { recursive: true });
+ const foreignToml = [
+ 'model = "o5"', '',
+ '[mcp_servers.other]', 'command = "/bin/true"', '',
+ '# my own hook trust', `[hooks.state.${JSON.stringify(trustKey(b, 'session_start', 0))}]`, 'trusted_hash = "sha256:mine"', '',
+ ].join('\n');
+ writeFileSync(codexToml(b), foreignToml);
+ const foreignHooks = JSON.stringify({ hooks: { SessionStart: [{ hooks: [{ type: 'command', command: 'echo user-hook', timeout: 2 }] }] } }, null, 2);
+ writeFileSync(hooksJson(b), foreignHooks);
+ const installed = await setup(b, ['codex', '--json']);
+ expect(installed.exitCode).toBe(0);
+ expect(groups(b, 'SessionStart')).toHaveLength(2);
+ expect(trustKeys(b)).toEqual([trustKey(b, 'session_start', 0), trustKey(b, 'session_start', 1), trustKey(b, 'user_prompt_submit', 0)]);
+ expect(toml(b).hooks.state[trustKey(b, 'session_start', 0)]).toEqual({ trusted_hash: 'sha256:mine' });
+
+ const preview = await setup(b, ['codex', '--remove', '--dry-run', '--json']);
+ expect(preview.exitCode).toBe(0);
+ expect(toml(b).mcp_servers.gbrain).toBeDefined();
+ expect(existsSync(codexReceipt(b))).toBe(true);
+
+ const removed = await setup(b, ['codex', '--remove', '--json']);
+ expect(removed.exitCode).toBe(0);
+ expect(removed.doc.preserved).toEqual([]);
+ expect(readFileSync(codexToml(b), 'utf8')).toBe(foreignToml);
+ expect(readJson(hooksJson(b))).toEqual(JSON.parse(foreignHooks));
+ expect(existsSync(codexReceipt(b))).toBe(false);
+ expect(existsSync(join(b.gbrainHome, '.gbrain', 'brain.pglite'))).toBe(true);
+ });
+
+ test('a crash after the MCP write and before the hook write resumes without duplicating anything', async () => {
+ const b = box();
+ const crashed = await setup(b, ['codex'], { GBRAIN_SETUP_ABORT_AFTER: 'mcp' });
+ expect(crashed.exitCode).toBe(1);
+ expect(crashed.stderr).toContain('aborted after mcp');
+ expect(toml(b).mcp_servers.gbrain).toBeDefined();
+ expect(existsSync(hooksJson(b))).toBe(false);
+ const mid = readJson(codexReceipt(b));
+ expect(mid.status).toBe('prepared');
+ expect(mid.consent.capture.value).toBe('declined');
+ expect(Object.keys(mid.hooks.pending).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);
+
+ const resumed = await setup(b, ['codex', '--json']);
+ expect(resumed.exitCode).toBe(0);
+ expect(resumed.doc.target.brain.kind).toBe('local-pglite');
+ expect(resumed.doc.steps.find((s: any) => s.step === 'mcp').action).toBe('keep');
+ expect(readFileSync(codexToml(b), 'utf8').match(/^\[mcp_servers\.gbrain\]$/gm)).toHaveLength(1);
+ expect(groups(b, 'SessionStart')).toHaveLength(1);
+ expect(groups(b, 'UserPromptSubmit')).toHaveLength(1);
+ expect(trustKeys(b)).toEqual([trustKey(b, 'session_start', 0), trustKey(b, 'user_prompt_submit', 0)]);
+ expect(readJson(codexReceipt(b))).toMatchObject({ status: 'installed', brain_created_by_setup: true });
+ });
+
+ test('a crash after the hook write and before the trust write leaves untrusted (inert) hooks; resume trusts them once', async () => {
+ const b = box();
+ expect((await setup(b, ['codex'], { GBRAIN_SETUP_ABORT_AFTER: 'hooks' })).exitCode).toBe(1);
+ expect(groups(b, 'UserPromptSubmit')).toHaveLength(1);
+ expect(trustKeys(b)).toEqual([]);
+ expect(Object.keys(readJson(codexReceipt(b)).trust.pending).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);
+ expect((await setup(b, ['codex'])).exitCode).toBe(0);
+ expect(groups(b, 'UserPromptSubmit')).toHaveLength(1);
+ expect(trustKeys(b)).toEqual([trustKey(b, 'session_start', 0), trustKey(b, 'user_prompt_submit', 0)]);
+ });
+
+ test('a user-edited owned hook survives --remove, is reported, and a later setup neither rewrites nor trusts it', async () => {
+ const b = box();
+ expect((await setup(b, ['codex'])).exitCode).toBe(0);
+ const doc = readJson(hooksJson(b));
+ doc.hooks.SessionStart[0].hooks[0].command += ' --verbose';
+ const edited = doc.hooks.SessionStart[0];
+ writeFileSync(hooksJson(b), JSON.stringify(doc, null, 2));
+
+ const removed = await setup(b, ['codex', '--remove', '--json']);
+ expect(removed.exitCode).toBe(0);
+ expect(removed.doc.preserved).toEqual([{ kind: 'hook', event: 'SessionStart', reason: 'edited' }]);
+ expect(groups(b, 'SessionStart')).toEqual([edited]);
+ expect(groups(b, 'UserPromptSubmit')).toEqual([]);
+ expect(toml(b).mcp_servers?.gbrain).toBeUndefined();
+ expect(trustKeys(b)).toEqual([]);
+ expect(readJson(codexReceipt(b)).status).toBe('removed');
+
+ const again = await setup(b, ['codex', '--json']);
+ expect(again.exitCode).toBe(0);
+ expect(again.doc.preserved).toEqual([{ kind: 'hook', event: 'SessionStart', reason: 'edited' }]);
+ expect(groups(b, 'SessionStart')).toEqual([edited]);
+ expect(setupGroups(b, 'UserPromptSubmit')).toHaveLength(1);
+ expect(trustKeys(b)).toEqual([trustKey(b, 'user_prompt_submit', 0)]);
+ });
+
+ test('a changed hook index (a group inserted before setup\'s) re-trusts only what setup owns', async () => {
+ const b = box();
+ expect((await setup(b, ['codex'])).exitCode).toBe(0);
+ const doc = readJson(hooksJson(b));
+ const userGroup = { hooks: [{ type: 'command', command: 'echo mine', timeout: 5 }] };
+ doc.hooks.UserPromptSubmit.unshift(userGroup);
+ writeFileSync(hooksJson(b), JSON.stringify(doc, null, 2));
+ const userTrust = `\n[hooks.state.${JSON.stringify(`${hooksJson(b)}:stop:0:0`)}]\ntrusted_hash = "sha256:user-owned"\n`;
+ writeFileSync(codexToml(b), readFileSync(codexToml(b), 'utf8') + userTrust);
+
+ const dry = await setup(b, ['codex', '--dry-run', '--json']);
+ expect(dry.doc.steps.find((s: any) => s.step === 'trust').action).toBe('write');
+ const r = await setup(b, ['codex', '--json']);
+ expect(r.exitCode).toBe(0);
+ expect(r.doc.steps.filter((s: any) => s.step === 'trust').map((s: any) => s.action)).toEqual(['remove', 'keep', 'write']);
+ expect(groups(b, 'UserPromptSubmit')[0]).toEqual(userGroup);
+ expect(setupGroups(b, 'UserPromptSubmit')).toHaveLength(1);
+ expect(trustKeys(b)).toEqual([trustKey(b, 'session_start', 0), `${hooksJson(b)}:stop:0:0`, trustKey(b, 'user_prompt_submit', 1)].sort());
+ expect(toml(b).hooks.state[`${hooksJson(b)}:stop:0:0`]).toEqual({ trusted_hash: 'sha256:user-owned' });
+ expect(readJson(codexReceipt(b)).trust.owned.UserPromptSubmit.key).toBe(trustKey(b, 'user_prompt_submit', 1));
+ });
+
+ test('two installs on one machine each own their own entries; removing one leaves the other', async () => {
+ const a = box();
+ const b: Box = { ...a, gbrainHome: join(a.root, 'second') };
+ mkdirSync(b.gbrainHome);
+ expect((await setup(a, ['codex'])).exitCode).toBe(0);
+ const clash = await setup(b, ['codex', '--json']);
+ expect(clash.exitCode).toBe(1);
+ expect(clash.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'other_install' });
+
+ expect((await setup(b, ['codex', '--name', 'gbrain-b'])).exitCode).toBe(0);
+ expect(Object.keys(toml(a).mcp_servers).sort()).toEqual(['gbrain', 'gbrain-b']);
+ expect(setupGroups(a, 'UserPromptSubmit')).toHaveLength(2);
+ const aGroups = { ss: groups(a, 'SessionStart')[0], ups: groups(a, 'UserPromptSubmit')[0] };
+ expect(aGroups.ups.hooks[0].command).toContain(`GBRAIN_HOME=${a.gbrainHome} `);
+ const aTrust = { ss: toml(a).hooks.state[trustKey(a, 'session_start', 0)], ups: toml(a).hooks.state[trustKey(a, 'user_prompt_submit', 0)] };
+
+ expect((await setup(b, ['codex', '--name', 'gbrain-b', '--remove'])).exitCode).toBe(0);
+ expect(Object.keys(toml(a).mcp_servers)).toEqual(['gbrain']);
+ expect(groups(a, 'SessionStart')).toEqual([aGroups.ss]);
+ expect(groups(a, 'UserPromptSubmit')).toEqual([aGroups.ups]);
+ expect(trustKeys(a)).toEqual([trustKey(a, 'session_start', 0), trustKey(a, 'user_prompt_submit', 0)]);
+ expect(toml(a).hooks.state[trustKey(a, 'session_start', 0)]).toEqual(aTrust.ss);
+ expect(toml(a).hooks.state[trustKey(a, 'user_prompt_submit', 0)]).toEqual(aTrust.ups);
+ expect(existsSync(codexReceipt(a))).toBe(true);
+ expect(existsSync(codexReceipt(a, 'gbrain-b'))).toBe(false);
+ });
+
+ test('an MCP table setup did not write is refused; an identical one is adopted and kept on --remove; a remote one is a hosted connection', async () => {
+ const b = box();
+ mkdirSync(codexDir(b), { recursive: true });
+ const foreign = '[mcp_servers.gbrain]\ncommand = "/opt/other/gbrain"\nargs = ["serve"]\n';
+ writeFileSync(codexToml(b), foreign);
+ const refused = await setup(b, ['codex', '--json']);
+ expect(refused.exitCode).toBe(1);
+ expect(refused.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'unowned_entry' });
+ expect(readFileSync(codexToml(b), 'utf8')).toBe(foreign);
+ expect(existsSync(hooksJson(b))).toBe(false);
+
+ const same = `[mcp_servers.gbrain]\ncommand = ${JSON.stringify(b.bin)}\nargs = ["serve", "--surface", "full"]\nenv = { GBRAIN_HOME = ${JSON.stringify(b.gbrainHome)} }\n`;
+ writeFileSync(codexToml(b), same);
+ expect((await setup(b, ['codex'])).exitCode).toBe(0);
+ expect(readJson(codexReceipt(b)).mcp_adopted).toBe(true);
+ const removed = await setup(b, ['codex', '--remove', '--json']);
+ expect(removed.doc.preserved).toEqual([{ kind: 'mcp', reason: 'adopted' }]);
+ expect(readFileSync(codexToml(b), 'utf8')).toBe(same);
+
+ const hosted = box();
+ mkdirSync(codexDir(hosted), { recursive: true });
+ const remote = '[mcp_servers.gbrain]\nurl = "https://brain.example.test/mcp"\nhttp_headers = { Authorization = "Bearer x" }\n';
+ writeFileSync(codexToml(hosted), remote);
+ const h = await setup(hosted, ['codex', '--json']);
+ expect(h.exitCode).toBe(1);
+ expect(h.doc.code).toBe('setup_hosted_connection');
+ expect(readFileSync(codexToml(hosted), 'utf8')).toBe(remote);
+ expect(existsSync(join(hosted.gbrainHome, '.gbrain'))).toBe(false);
+ });
+});
+
+describe('gbrain setup codex: consent and flags', () => {
+ test('provider keys present + capture declined + existing opt-outs: no capture hook, no provider traffic, keyless brain', async () => {
+ const seen: string[] = [];
+ const recorder: Server = createServer((sock) => {
+ sock.once('data', (d) => { seen.push(d.toString('utf8').split('\r\n')[0] ?? ''); sock.destroy(); });
+ });
+ await new Promise<void>((ok) => recorder.listen(0, '127.0.0.1', ok));
+ const port = (recorder.address() as { port: number }).port;
+ const providerEnv = {
+ OPENAI_API_KEY: 'sk-test-setup', ANTHROPIC_API_KEY: 'sk-ant-test-setup', VOYAGE_API_KEY: 'pa-test-setup', GEMINI_API_KEY: 'gm-test-setup',
+ HTTPS_PROXY: `http://127.0.0.1:${port}`, HTTP_PROXY: `http://127.0.0.1:${port}`, https_proxy: `http://127.0.0.1:${port}`, http_proxy: `http://127.0.0.1:${port}`,
+ OPENAI_BASE_URL: `http://127.0.0.1:${port}/v1`, ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}`,
+ };
+ try {
+ const fresh = box();
+ const r = await setup(fresh, ['codex', '--no-capture', '--json'], providerEnv);
+ expect(r.exitCode).toBe(0);
+ expect(r.doc.consent.capture).toMatchObject({ value: 'declined', source: 'flag' });
+ expect(r.doc.consent.providers).toMatchObject({ value: 'declined', source: 'default' });
+ expect(readJson(join(fresh.gbrainHome, '.gbrain', 'config.json')).embedding_disabled).toBe(true);
+ expect(groups(fresh, 'SessionEnd')).toEqual([]);
+ expect(trustKeys(fresh).some((k) => k.includes(':session_end:'))).toBe(false);
+
+ const optedOut = box();
+ expect((await runCli(['init', '--pglite', '--no-embedding'], { home: optedOut.home })).exitCode).toBe(0);
+ const cfgPath = join(optedOut.gbrainHome, '.gbrain', 'config.json');
+ writeFileSync(cfgPath, JSON.stringify({ ...readJson(cfgPath), memory: { auto_writeback: 'off' } }));
+ const o = await setup(optedOut, ['codex', '--capture', '--json'], providerEnv);
+ expect(o.exitCode).toBe(0);
+ expect(o.doc.consent.capture).toMatchObject({ value: 'declined', source: 'opt_out' });
+ expect(o.doc.notes.join(' ')).toContain('--capture ignored');
+ expect(Object.keys(readJson(hooksJson(optedOut)).hooks).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);
+
+ const hooksOff = box();
+ const k = await setup(hooksOff, ['codex', '--capture', '--json'], { ...providerEnv, GBRAIN_HOOKS: '0' });
+ expect(k.exitCode).toBe(0);
+ expect(k.doc.consent.wiring_scope).toMatchObject({ value: { hooks: 'none' }, source: 'opt_out' });
+ expect(existsSync(hooksJson(hooksOff))).toBe(false);
+ expect(trustKeys(hooksOff)).toEqual([]);
+ expect(k.doc.states).toEqual(['configured', 'connection-verified', 'native-pending']);
+
+ expect(seen.filter((l) => /openai|anthropic|voyage|googleapis|\/v1\//i.test(l))).toEqual([]);
+ for (const b of [fresh, optedOut, hooksOff]) expect(existsSync(join(b.gbrainHome, '.gbrain', 'corpus'))).toBe(false);
+ } finally {
+ recorder.close();
+ }
+ });
+
+ test('--capture adds the SessionEnd capture group and its trust; --no-hooks then removes every owned hook and trust entry', async () => {
+ const b = box();
+ const r = await setup(b, ['codex', '--capture', '--json']);
+ expect(r.exitCode).toBe(0);
+ expect(Object.keys(readJson(hooksJson(b)).hooks).sort()).toEqual(['SessionEnd', 'SessionStart', 'UserPromptSubmit']);
+ const end = groups(b, 'SessionEnd')[0].hooks[0];
+ expect(end.timeout).toBe(3);
+ expect(end.command).toMatch(/^env GBRAIN_HOOK_LANE=setup GBRAIN_HOME=\S+ sh -c '.*hook session-end --harness codex/);
+ expect(trustKeys(b)).toContain(trustKey(b, 'session_end', 0));
+ const off = await setup(b, ['codex', '--no-hooks', '--json']);
+ expect(off.exitCode).toBe(0);
+ expect(readJson(hooksJson(b)).hooks).toEqual({});
+ expect(trustKeys(b)).toEqual([]);
+ expect(toml(b).mcp_servers.gbrain).toBeDefined();
+ });
+
+ test('--dry-run writes nothing and honours GBRAIN_SURFACE; --scope project is refused for codex', async () => {
+ const b = box();
+ const r = await setup(b, ['codex', '--dry-run', '--json'], { GBRAIN_SURFACE: 'starter' });
+ expect(r.exitCode).toBe(0);
+ expect(r.doc.target).toMatchObject({ transport: 'local-stdio', surface: 'starter', registration_owner: 'none', scope: 'user' });
+ expect(r.doc.steps.map((s: any) => s.step)).toEqual(['receipt', 'brain', 'mcp', 'hooks', 'trust']);
+ expect(existsSync(codexDir(b))).toBe(false);
+ expect(existsSync(join(b.gbrainHome, '.gbrain'))).toBe(false);
+ const p = await setup(b, ['codex', '--scope', 'project']);
+ expect(p.exitCode).toBe(2);
+ expect(p.stderr).toContain('user scope only');
+ });
+
+ test('the bootstrap Codex SessionEnd lane is an owner conflict for --capture, and bootstrap never claims setup\'s groups', async () => {
+ const b = box();
+ mkdirSync(codexDir(b), { recursive: true });
+ expect(writeCodexHooks({ gbrainBin: b.bin, hooksPath: hooksJson(b), configPath: codexToml(b) }).ok).toBe(true);
+ const refused = await setup(b, ['codex', '--capture', '--json']);
+ expect(refused.exitCode).toBe(1);
+ expect(refused.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'harness_lane' });
+ expect(existsSync(codexReceipt(b))).toBe(false);
+
+ const c = box();
+ expect((await setup(c, ['codex', '--capture'])).exitCode).toBe(0);
+ const before = readFileSync(hooksJson(c), 'utf8');
+ removeCodexHooks({ hooksPath: hooksJson(c), configPath: codexToml(c) });
+ expect(readFileSync(hooksJson(c), 'utf8')).toBe(before);
+ });
+});
+
+describe('codex trust hash and hash-owned TOML tables', () => {
+ test('codexHookTrustHash reproduces trust entries a live codex-cli 0.162.1 accepted (the hooks ran)', () => {
+ const base = '/home/user/.capy/work/d8/obs-2';
+ const cmd = (sub: string) => `env GBRAIN_HOOK_LANE=setup GBRAIN_HOME=${base}/home ${base}/bin/gbrain hook ${sub} --harness codex`;
+ expect(codexHookTrustHash('user_prompt_submit', cmd('user-prompt'), 15)).toBe('sha256:14aa503e53d2b5dd658bec9232f3021e8169c2799b6332dc4514dfdf71fb44ae');
+ expect(codexHookTrustHash('session_start', cmd('session-start'), 15)).toBe('sha256:86d30bf0ab9b998a4121df4a83de0662ea94f69d94d4311c61589c26d5191737');
+ expect(codexHookTrustHash('session_end', 'x', 3)).toBe(codexTrustHash('x'));
+ });
+
+ test('append then remove is byte-exact, keeps the next table\'s comment, and refuses a re-rendered table', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-codex-toml-'));
+ roots.push(dir);
+ const path = join(dir, 'config.toml');
+ const original = 'model = "o5"\n\n[profiles.fast]\nmodel = "o5-mini"\n';
+ writeFileSync(path, original);
+ appendCodexTomlTable(path, ['mcp_servers', 'gbrain'], { command: '/bin/gbrain', args: ['serve'], env: { GBRAIN_HOME: '/h' } }, 'gbrain setup (gbrain): test');
+ writeFileSync(path, `${readFileSync(path, 'utf8')}\n# user note about the next table\n[profiles.slow]\nmodel = "o5"\n`);
+ expect(() => appendCodexTomlTable(path, ['mcp_servers', 'gbrain'], { command: '/x' })).toThrow(/never defines a table twice/);
+ expect(removeCodexTomlTable(path, ['mcp_servers', 'gbrain'])).toBe('removed');
+ expect(readFileSync(path, 'utf8')).toBe(`${original}\n# user note about the next table\n[profiles.slow]\nmodel = "o5"\n`);
+ expect(removeCodexTomlTable(path, ['mcp_servers', 'gbrain'])).toBe('absent');
+
+ writeFileSync(path, '[mcp_servers.gbrain]\ncommand = "/bin/gbrain"\n\n[mcp_servers.gbrain.env]\nGBRAIN_HOME = "/h"\n');
+ const split = readFileSync(path, 'utf8');
+ expect(removeCodexTomlTable(path, ['mcp_servers', 'gbrain'])).toBe('unlocatable');
+ expect(readFileSync(path, 'utf8')).toBe(split);
+ });
+});