Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(setup): gbrain setup claude-code — one-command local stdio wiring over bootstrap (GBRA-60 D8)
garrytan685f0ef5d449
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex dd35665595..43a2bd1d11 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -107,6 +107,22 @@ 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:++```bash+gbrain setup claude-code --dry-run --json # the resolved target; writes nothing+gbrain setup claude-code --json # brain (if none) + MCP + read-context hooks, verified+```++It runs `gbrain init --pglite --no-embedding` only when no brain exists, and its+`--json` document carries init's first-run decision bundle in `notices`: relay+the search-mode matrix (Step 3.5) and the decisions in one reply. Capture+(`--capture`) and providers (`--providers`) stay off unless the user accepts+them. A coded refusal (`setup_owner_conflict`, `setup_hosted_connection`) means+another owner or a hosted brain holds the target; follow its `fix`.+`--remove` undoes only what setup wrote. Guide:+[docs/guides/setup.md](docs/guides/setup.md). Otherwise:+```bashgbrain init --pglite --no-embedding # keyless memory, no server neededgbrain doctor --json # inspect diagnostics and any warningsdiff --git a/README.md b/README.mdindex 8e1e402ab9..bf91113d60 100644--- a/README.md+++ b/README.md@@ -100,6 +100,15 @@ 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:**++```bash+bun install -g github:garrytan/gbrain+gbrain setup claude-code # --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).+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:```text@@ -173,14 +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.** Spin up a local brain and connect it in two commands — zero server, zero token, zero tunnel. `--surface full` (the registration default) serves every operation, the seven-verb memory protocol ([MEMORY_VERBS v1](docs/protocol/MEMORY_VERBS_v1.md)) and `put_pages` included; a harness that caps its tool count can register `--surface verbs` or `--surface starter`:--```bash-gbrain init --pglite --no-embedding # keyless local brain (no Docker)-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface full # or: codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full-```--If `claude` is not found, install Claude Code first — or use the per-harness blocks in the [protocol doc](docs/protocol/MEMORY_VERBS_v1.md). Heads-up: memories agents save default to brain-wide visibility (every connected agent can recall them); pass `visibility: "private"` for local-only facts.+**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.**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.mdindex d0ec4eee61..0451f0819d 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -16,8 +16,9 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/bootstrap/render.ts` — token substitution with interview values treated as data (line-leading `#`/`<!--`/fence escaping), hard-fail on unresolved tokens, never-clobber + timestamped backups on `--force`, blank-line collapse, byte floors scaled to answered count. `--minimal` is the deterministic placeholder mode the template-repo generator uses (byte-identical across runs; leaves required tokens as literal fill-me markers; writes `initialized:false`). `--only` never writes agent.json.- `src/core/bootstrap/lock.ts` — the bootstrap-run mutex (atomic mkdir + pid liveness + age guard + ownership token; steal requires dead pid AND stale age) and the family's shared typed `BootstrapError` (GH_MISSING/GH_AUTH carry exit 2 = human action needed).- `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`.+- `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/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`.`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.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 9e76065c24..c5cf2f7968 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -28,6 +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/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`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` remain because `gbrain skillpack diff` uses `diffSkill` from there.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex eb01803137..fe05e25417 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2390,6 +2390,38 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-cReasons: `lock_held`, `no_brain`, `config_unreadable`, `missing_brain`, `brain_unopenable`, `repair_failed`, `unavailable`.+### setup_harness_unsupported++<a id="setup_harness_unsupported"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain setup does not wire this harness yet; its guide has the manual connection steps. | Only harnesses with a supported row in the setup capability table are wired automatically, so setup never guesses another host's config format. | Correct the request using the message above, then retry. Run: gbrain setup --help | agent | `repeat the read that failed` | 2 | no |++More: [docs/guides/repair.md#setup-harness-unsupported](../../docs/guides/repair.md#setup-harness-unsupported)++### setup_hosted_connection++<a id="setup_hosted_connection"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| This machine already reaches a hosted brain, so gbrain setup will not create a second, local brain. | A new local brain would split memory: sessions would read and write the empty local brain while useful memory stays on the hosted one. | Correct the request using the message above, then retry. Run: gbrain doctor --only harness_wiring --json | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/repair.md#setup-hosted-connection](../../docs/guides/repair.md#setup-hosted-connection)++### setup_owner_conflict++<a id="setup_owner_conflict"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Another owner holds what gbrain setup would change: a live server owns this PGLite brain, or the harness configuration holds an entry setup did not write. | A PGLite brain has one writer, so a second server would fail on its lock; an entry setup did not record by hash is the user's or another install's and is never overwritten. | Correct the request using the message above, then retry. Run: gbrain setup claude-code --dry-run --json | agent | `repeat the read that failed` | 1 | no |++Reasons: `live_serve`, `unowned_entry`, `other_install`, `harness_lane`.++More: [docs/guides/repair.md#setup-owner-conflict](../../docs/guides/repair.md#setup-owner-conflict)+### shared_skills_unavailable<a id="shared_skills_unavailable"></a>diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 9f2a76cf27..d3f08e5714 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1856,6 +1856,59 @@ files and counts the page in `fix_pending`; the cycle's lint phase reports`warn`, not `fail`. Make the file writable by the user running gbrain, or passits directory or file name to `gbrain lint --exclude`, then run lint again.+## Setup refusals++`gbrain setup <harness>` resolves the brain, source, transport, launcher and+registration owner before it writes anything, and refuses with one of these+codes when that target is not safe to wire. A refusal writes nothing. Guide:+[connect an agent with gbrain setup](setup.md).++### 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:+[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.++### Setup owner conflict++`setup_owner_conflict`: something setup does not own holds the target. The+`reason` says which:++- `live_serve`: a running `gbrain serve` holds this PGLite brain's+ single-writer lock and is not the server this setup registered. A stdio+ 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`.+- `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+ another name with `--name`, or remove that entry yourself and run setup+ again.+- `other_install`: the connection receipt for this name belongs to a gbrain+ install with a different `GBRAIN_HOME`. Run setup with `--name <other>` so+ 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.++`gbrain setup claude-code --dry-run --json` shows the resolved target and the+blocking owner without writing anything.++### Setup hosted connection++`setup_hosted_connection`: this machine already reaches a hosted brain (a+thin-client config from `gbrain init --mcp-only`, a remote `gbrain` entry in+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+which brain the registration reaches.+## Related- [Write refusal reasons](write-refusals.md) — what a refused write means and the recovery commanddiff --git a/docs/guides/setup.md b/docs/guides/setup.mdnew file mode 100644index 0000000000..6b2bb4b8b6--- /dev/null+++ b/docs/guides/setup.md@@ -0,0 +1,107 @@+# 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.++**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`).++```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+```++## Target first++Before it writes anything, setup resolves and prints:++| Part | How it is chosen |+|---|---|+| 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>`. |+| 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). |++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).+Each code's fix is in [setup refusals](repair.md#setup-refusals).++## Three decisions++Setup records three separate decisions in its receipt. Running it again keeps+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`. |+| 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.++## States++Setup reports how far the wiring is proven:++1. `configured`: the MCP entry and hooks are written.+2. `connection-verified`: the registered command answered initialize,+ 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.++## Ownership and removal++Setup owns entries by exact hash, recorded in the connection receipt+`~/.gbrain-connection-claude-code-<name>.json` (the receipt `gbrain connect+--install` uses, with `connection: "local-stdio"`). The write order is+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.++`--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.+Two installs on one machine (different `GBRAIN_HOME`) each use their own+`--name` and remove only their own entries.++## Harness capability table++The table is data (`src/core/setup/capabilities.ts`, version 1). 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 |+| 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 |++## How setup relates to the other entry points++- `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.+- `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+ points to it when a live HTTP server owns the brain.+- `gbrain mcp expose` and `gbrain agent register`: host-side steps that publish+ a brain to other devices or mint scoped clients; setup does not run them.+- `gbrain onboard`: improves an existing brain's content (link and timeline+ coverage, embeddings) after setup has connected it.diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.mdindex ae3a0bd210..b7a4b05d0e 100644--- a/docs/mcp/CLAUDE_CODE.md+++ b/docs/mcp/CLAUDE_CODE.md@@ -13,6 +13,21 @@ For an existing agent, start with the [memory-only walkthrough](../tutorials/con> Open a new empty folder (bootstrap creates the private repo for you), or make an> empty private repo under your own account and open the clone — bootstrap adopts it.+## Fastest: `gbrain setup claude-code`++```bash+gbrain setup claude-code --dry-run # the brain, source, launcher and owner it resolved; writes nothing+gbrain setup claude-code # keyless brain if none, stdio MCP entry, read-context hooks, verified+```++Setup writes the same stdio entry as Option 1 into `~/.claude.json` plus the+`SessionStart` and `UserPromptSubmit` hooks into `~/.claude/settings.json`,+owned by hash through a connection receipt, and smoke-tests the registration.+Capture hooks (`--capture`) and providers (`--providers`) stay off unless you+accept them; `--remove` deletes only unchanged entries it wrote. It refuses+instead of starting a second owner on a live PGLite brain or creating a local+brain next to a hosted one. Details: [gbrain setup](../guides/setup.md).+## Option 0: Install as a Claude Code plugingbrain ships as a native Claude Code plugin — MCP server + the curateddiff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.mdindex ff9a8a9215..09e39d1594 100644--- a/docs/mcp/DEPLOY.md+++ b/docs/mcp/DEPLOY.md@@ -63,7 +63,8 @@ gbrain serve --surface full # full operation catalog (what registrations pin;```Works with Claude Code, Cursor, Windsurf, and any MCP client that supports stdio.-No server, no tunnel, no token needed. Works on both PGLite and Postgres engines.+On Claude Code, `gbrain setup claude-code` writes and verifies this registration+for you ([setup guide](../guides/setup.md)). No server, no tunnel, no token needed. Works on both PGLite and Postgres engines.`--surface full` serves every operation. For a client that cannot hold the fullcatalog, `--surface verbs` exposes exactly the seven-verb memory protocol(`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`,diff --git a/docs/mcp/README.md b/docs/mcp/README.mdindex 57f2e1f2fa..d33cf25839 100644--- a/docs/mcp/README.md+++ b/docs/mcp/README.md@@ -8,6 +8,7 @@ different credentials.| Run an HTTP MCP server | [Deployment](DEPLOY.md) | Access to the brain host and its service configuration || Open the admin panel or manage clients | [MCP administration](ADMIN.md) | The running server's separate owner bootstrap credential || Connect an existing agent | [Hosted harness setup](../guides/hosted-harness-access.md) | Native OAuth/PKCE, or a private machine-client handoff |+| Wire Claude Code to a local brain in one command | [`gbrain setup claude-code`](../guides/setup.md) | A local GBrain installation; setup resolves the brain, writes MCP and read-context hooks, and verifies them || Run a local MCP pipe | [Local stdio](DEPLOY.md#local-stdio-zero-setup) | A local GBrain installation; no HTTP admin panel is created || Diagnose a failed connection | [Recovery table](ADMIN.md#recover-a-failed-step) | Start with the failed stage and the authority you actually hold || A tool call returned an error | [A tool call returned an error](#a-tool-call-returned-an-error) | None: the error says who acts |diff --git a/llms-full.txt b/llms-full.txtindex 8c83337c98..b9532a260c 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -2598,6 +2598,22 @@ 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:++```bash+gbrain setup claude-code --dry-run --json # the resolved target; writes nothing+gbrain setup claude-code --json # brain (if none) + MCP + read-context hooks, verified+```++It runs `gbrain init --pglite --no-embedding` only when no brain exists, and its+`--json` document carries init's first-run decision bundle in `notices`: relay+the search-mode matrix (Step 3.5) and the decisions in one reply. Capture+(`--capture`) and providers (`--providers`) stay off unless the user accepts+them. A coded refusal (`setup_owner_conflict`, `setup_hosted_connection`) means+another owner or a hosted brain holds the target; follow its `fix`.+`--remove` undoes only what setup wrote. Guide:+[docs/guides/setup.md](docs/guides/setup.md). Otherwise:+```bashgbrain init --pglite --no-embedding # keyless memory, no server neededgbrain doctor --json # inspect diagnostics and any warnings@@ -4698,6 +4714,15 @@ 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:**++```bash+bun install -g github:garrytan/gbrain+gbrain setup claude-code # --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).+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:```text@@ -4771,14 +4796,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.** Spin up a local brain and connect it in two commands — zero server, zero token, zero tunnel. `--surface full` (the registration default) serves every operation, the seven-verb memory protocol ([MEMORY_VERBS v1](docs/protocol/MEMORY_VERBS_v1.md)) and `put_pages` included; a harness that caps its tool count can register `--surface verbs` or `--surface starter`:--```bash-gbrain init --pglite --no-embedding # keyless local brain (no Docker)-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface full # or: codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full-```--If `claude` is not found, install Claude Code first — or use the per-harness blocks in the [protocol doc](docs/protocol/MEMORY_VERBS_v1.md). Heads-up: memories agents save default to brain-wide visibility (every connected agent can recall them); pass `visibility: "private"` for local-only facts.+**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.**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/src/cli/command-table.ts b/src/cli/command-table.tsindex 370e9b7017..b06304e6c1 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -178,6 +178,10 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// selfHelp: `gbrain connect --help` prints its own usage (flags + examples) from runConnect; route// around the generic one-line short-circuit.{ name: 'connect', phase: 'pre-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/connect.ts') },+ // D8: `gbrain setup <harness>` orchestrates init + harness wiring. Engine-free (a new brain is+ // created by the `gbrain init` child it runs); thinClient 'none' because it resolves a hosted+ // target itself and refuses with setup_hosted_connection instead of creating a local brain.+ { name: 'setup', phase: 'pre-connect', thinClient: 'none', selfHelp: true, json: 'document', load: () => import('./commands/setup.ts') },// CLI_ONLY: Agent-bootstrap family (ENG-2 three-touchpoint rule): `bootstrap` + `hook` are// ENGINE-FREE (dispatched in handleCliOnly before the connectEngine terminator) and must NEVER// enter THIN_CLIENT_REFUSED_COMMANDS. `sweep` is the trusted local sweep entry [CX2-5] and needsdiff --git a/src/cli/commands/setup.ts b/src/cli/commands/setup.tsnew file mode 100644index 0000000000..bf521703ce--- /dev/null+++ b/src/cli/commands/setup.ts@@ -0,0 +1,12 @@+/**+ * `gbrain setup <harness>`: pre-connect dispatch (engine-free), run by+ * handleCliOnly before the connectEngine() terminator; the record lives in+ * src/cli/command-table.ts. Setup never opens the database itself: a new+ * brain is created by the `gbrain init` child it runs.+ */+import { setCliExitVerdict } from '../../core/cli-force-exit.ts';++export async function run(args: string[]): Promise<void> {+ const { runSetup } = await import('../../commands/setup.ts');+ setCliExitVerdict(await runSetup(args));+}diff --git a/src/cli/top-help.ts b/src/cli/top-help.tsindex 8729af9b85..bb8e9aa3c4 100644--- a/src/cli/top-help.ts+++ b/src/cli/top-help.ts@@ -14,6 +14,7 @@ USAGESETUPmcp grant <name> --help Grant hosted access; private credential handoffmcp verify --help Verify connection, permissions, and memory+ setup claude-code [--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/setup.ts b/src/commands/setup.tsnew file mode 100644index 0000000000..4273e3970a--- /dev/null+++ b/src/commands/setup.ts@@ -0,0 +1,444 @@+/**+ * `gbrain setup <harness>` (D8): one command from an installed CLI to a+ * harness with memory. An orchestrator over the existing pieces, never a new+ * installation system:+ *+ * - target first: resolve the brain (existing local, hosted, or a new+ * keyless PGLite brain through `gbrain init --pglite --no-embedding`), the+ * source, the transport, the absolute launcher and the registration owner,+ * print them, and refuse (coded) before any write when another owner holds+ * the target: a live PGLite server, an unowned entry, another install, the+ * bootstrap harness lane, or a hosted connection (never a new local brain);+ * - consent as three recorded decisions: wiring scope, automatic capture and+ * provider use. Memory-only (the default) installs the read-context hooks+ * SessionStart and UserPromptSubmit only; Stop/SessionEnd capture and+ * provider use need `--capture` / `--providers`; existing opt-outs win;+ * - hash-keyed ownership through the connection receipt+ * (src/core/setup/claude-code.ts), so a resume never duplicates an entry+ * and `--remove` deletes only unchanged owned entries;+ * - verify through the `harness_wiring` smoke (spawn the registered argv,+ * initialize + tools/list + recall), reporting configured /+ * connection-verified / native-pending / native-verified.+ *+ * Engine-free: setup never opens the database itself.+ */+import { realpathSync } from 'node:fs';+import { opError, OperationError } from '../core/ops/contract.ts';+import { renderCliError, type Action } from '../core/agent-output.ts';+import { writeJsonDocument } from '../core/cli-force-exit.ts';+import { configDir, gbrainPath, loadConfig, type GBrainConfig } from '../core/config.ts';+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 { claudeUserSettingsPath, type ClaudeHookEvent } from '../core/bootstrap/host-specs.ts';+import { readHarnessReceiptState } from '../core/bootstrap/format.ts';+import { smokeStdioRegistration } from './doctor/checks/harness-wiring.ts';+import type { McpSurface } from '../mcp/surface.ts';+import {+ SETUP_CAPABILITIES,+ SETUP_CAPABILITY_TABLE_VERSION,+ SETUP_HARNESSES,+ capabilityRows,+ isSetupHarness,+} from '../core/setup/capabilities.ts';+import {+ SetupAbortInjected,+ applyClaudeSetup,+ claudeSetupPaths,+ desiredMcpEntry,+ inspectClaudeSetup,+ readSetupReceipt,+ removeClaudeSetup,+ type ClaudeSetupPlan,+ type ClaudeSetupReceipt,+ type SetupConsent,+ type SetupStep,+ type WiringScope,+} from '../core/setup/claude-code.ts';++export const SETUP_HELP = `gbrain setup <harness> — give an agent harness memory in one command++Usage: gbrain setup claude-code [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.++Flags:+ --dry-run Print the target and every step; write nothing.+ --json One JSON document on stdout (target, decisions, steps, states).+ --surface S MCP tool surface: verbs, starter or full (default: GBRAIN_SURFACE,+ 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).+ --no-hooks Register MCP only; install no hooks (GBRAIN_HOOKS=0 does the same).+ --capture Accept automatic capture: also install Stop and SessionEnd hooks.+ --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).+ --name NAME MCP server name (default gbrain); one name per install.+ --source ID Pin the source the MCP server and hooks use.+ --gbrain-bin PATH Absolute gbrain launcher (default: the gbrain on PATH).+ --remove Remove exactly what setup wrote (unchanged entries only). The+ 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.++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.+`;++interface SetupFlags {+ harness?: string;+ dryRun: boolean;+ json: boolean;+ remove: boolean;+ noHooks: boolean;+ capture?: boolean;+ providers?: boolean;+ scope?: WiringScope;+ surface?: McpSurface;+ name: string;+ source?: string;+ gbrainBin?: string;+}++const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin']);++function parseFlags(args: string[]): SetupFlags | string {+ const value = (flag: string): string | undefined => {+ const i = args.indexOf(flag);+ return i < 0 ? undefined : args[i + 1] ?? '';+ };+ const positionals = args.filter((a, i) => !a.startsWith('-') && !VALUE_FLAGS.has(args[i - 1] ?? ''));+ const surface = value('--surface');+ if (surface !== undefined && !isRegistrationSurface(surface)) return `unknown --surface '${surface}'; pass verbs, starter or full`;+ const scope = value('--scope');+ if (scope !== undefined && scope !== 'user' && scope !== 'project') return `unknown --scope '${scope}'; pass user or project`;+ const name = value('--name') ?? 'gbrain';+ if (!isValidName(name)) return `invalid --name '${name}'; use lowercase letters, digits, '-' or '_'`;+ const source = value('--source');+ if (source !== undefined && !isValidSourceId(source)) return `invalid --source '${source}'`;+ if (args.includes('--capture') && args.includes('--no-capture')) return 'pass --capture or --no-capture, not both';+ if (args.includes('--providers') && args.includes('--no-providers')) return 'pass --providers or --no-providers, not both';+ return {+ harness: positionals[0],+ dryRun: args.includes('--dry-run'),+ json: args.includes('--json'),+ remove: args.includes('--remove'),+ noHooks: args.includes('--no-hooks'),+ capture: args.includes('--capture') ? true : args.includes('--no-capture') ? false : undefined,+ providers: args.includes('--providers') ? true : args.includes('--no-providers') ? false : undefined,+ scope: scope as WiringScope | undefined,+ surface: surface as McpSurface | undefined,+ name,+ source,+ gbrainBin: value('--gbrain-bin'),+ };+}++interface Out { json: boolean; lines: string[]; notes: string[] }++function say(out: Out, line: string): void {+ if (out.json) process.stderr.write(`${line}\n`);+ else console.log(line);+}++async function refuse(e: OperationError, out: Out): Promise<number> {+ const r = renderCliError(e, { json: out.json, command: 'setup', tty: process.stderr.isTTY === true });+ if (r.stdout) await writeJsonDocument(r.stdout, (t) => process.stdout.write(t));+ if (r.stderr) process.stderr.write(r.stderr);+ return r.exitCode;+}++const verifyDryRun = (harness: string, name: string): Action['verify'] => ({ argv: ['gbrain', 'setup', harness, '--dry-run', '--json', ...(name === 'gbrain' ? [] : ['--name', name])] });++function ownerConflict(reason: string, message: string, fix: Pick<Action, 'actor' | 'why'> & Partial<Action>): OperationError {+ return opError('setup_owner_conflict', message, fix.user_message ?? fix.why, {+ reason, docs: 'docs/guides/repair.md#setup-owner-conflict',+ fix: { consent: [], requires_exclusive: false, ...fix },+ });+}++interface Target {+ brain: { kind: 'local-pglite' | 'local-postgres' | 'new-local-pglite'; path?: string; config_dir: string };+ source: { id: string | null; pinned: boolean; from: 'flag' | 'env' | 'brain-default' };+ transport: 'local-stdio';+ launcher: string;+ surface: McpSurface;+ registration_owner: 'none' | 'setup' | 'plugin';+ live_owner: { pid: number; transport: 'stdio' | 'http'; ours: boolean } | null;+ scope: WiringScope;+ name: string;+ config_path: string;+ settings_path: string;+ receipt_path: string;+}++function resolveConsent(flags: SetupFlags, prior: ClaudeSetupReceipt | 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'] = {+ value: { scope, hooks: hooksOff ? 'none' : 'read-context' },+ source: flags.noHooks || flags.scope ? 'flag' : process.env.GBRAIN_HOOKS === '0' ? 'opt_out' : prior ? 'prior' : 'default',+ };+ const writebackOff = String((cfg as { memory?: { auto_writeback?: unknown } } | null)?.memory?.auto_writeback ?? '').toLowerCase() === 'off';+ let capture: SetupConsent['capture'];+ if (writebackOff && flags.capture !== false) {+ capture = { value: 'declined', source: 'opt_out', note: 'memory.auto_writeback is off on this brain; that opt-out wins' };+ if (flags.capture) notes.push('--capture ignored: memory.auto_writeback is off on this brain (an existing opt-out wins). Change it with `gbrain config set memory.auto_writeback salient`, then run setup with --capture.');+ } else if (flags.capture !== undefined) {+ capture = { value: flags.capture ? 'accepted' : 'declined', source: 'flag' };+ } else if (prior) {+ capture = { value: prior.consent.capture.value, source: 'prior' };+ } else {+ capture = { value: 'declined', source: 'default' };+ }+ const providers: SetupConsent['providers'] = flags.providers !== undefined ? { value: flags.providers ? 'accepted' : 'declined', source: 'flag' }+ : prior ? { value: prior.consent.providers.value, source: 'prior' } : { value: 'declined', source: 'default' };+ return { wiring_scope: wiring, capture, providers };+}++function hookEvents(consent: SetupConsent): ClaudeHookEvent[] {+ 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[];+}++function describeTarget(t: Target, out: Out): 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, ` 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}'`}`);+ 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)`);+}++function describeConsent(c: SetupConsent, events: ClaudeHookEvent[], out: Out): void {+ const src = (s: string) => `[${s}]`;+ 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, ` providers ${c.providers.value}${c.providers.value === 'declined' ? ' (keyless: setup configures no paid provider; accept with --providers)' : ''} ${src(c.providers.source)}`);+}++export async function runSetup(args: string[]): Promise<number> {+ if (args.includes('--help') || args.includes('-h') || args.length === 0) {+ console.log(SETUP_HELP);+ return 0;+ }+ const parsed = parseFlags(args);+ const out: Out = { json: args.includes('--json'), lines: [], notes: [] };+ if (typeof parsed === 'string') {+ process.stderr.write(`gbrain setup: ${parsed}\n`);+ return 2;+ }+ const flags = parsed;+ if (!isSetupHarness(flags.harness) || capabilityRows(flags.harness).every((r) => r.setup !== 'supported')) {+ const rows = isSetupHarness(flags.harness) ? capabilityRows(flags.harness) : [];+ const guide = rows[0]?.docs;+ 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`.',+ { 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.',+ ...(guide ? { docs: guide } : {}) } }), out);+ }++ const launcher = flags.gbrainBin ?? resolveGbrainBin();+ if (!launcher || !launcher.startsWith('/')) {+ process.stderr.write('gbrain setup: cannot resolve an absolute gbrain launcher (GUI hosts inherit no PATH). Install gbrain globally (`bun install -g github:garrytan/gbrain`) or pass --gbrain-bin <absolute path>.\n');+ return 2;+ }++ let cfg: GBrainConfig | null;+ try { cfg = loadConfig(); } catch (e) {+ process.stderr.write(`gbrain setup: this install's config cannot be read (${(e as Error).message}); run \`gbrain doctor\`.\n`);+ return 1;+ }+ const brainHome = configDir();+ const scope: WiringScope = flags.scope ?? 'user';+ const projectDir = scope === 'project' ? realpathSync(process.cwd()) : undefined;+ const paths = claudeSetupPaths({ name: flags.name, scope, projectDir });++ try {+ const receiptRead = readSetupReceipt(paths.receiptPath);+ if (flags.remove) return await runRemove(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), 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', 'claude-code', '--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('claude-code', flags.name) }), out);+ }++ const notes: string[] = [];+ const consent = resolveConsent(flags, prior, cfg, scope, 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: 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),+ };+ 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 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, name: flags.name,+ config_path: found.configPath, settings_path: found.settingsPath, receipt_path: found.receiptPath,+ };+ describeTarget(target, out);+ 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 (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'],+ why: 'Preview a setup under another name, or remove that entry yourself and run setup again.', verify: verifyDryRun('claude-code', flags.name) }), out);+ }+ const harnessReceipt = readHarnessReceiptState(brainHome);+ const harnessLane = harnessReceipt.state === 'ok' && harnessReceipt.receipt.targets.some((t) => t.host === 'claude-code');+ 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 Claude Code for this install' : `${found.settingsPath} already wires ${laneEvents.join(', ')} through another gbrain install lane`}; two lanes would fire every hook twice.`, {+ actor: 'agent', argv: ['gbrain', 'bootstrap', 'harness', '--remove', '--dry-run'],+ why: 'Preview removing the bootstrap harness wiring first, or keep it and skip setup.', verify: verifyDryRun('claude-code', flags.name) }), out);+ }++ const brainCreate = !cfg;+ const initArgv = [launcher, 'init', '--pglite', ...(consent.providers.value === 'accepted' ? [] : ['--no-embedding']), ...(out.json ? ['--json'] : [])];+ if (flags.dryRun) {+ const steps: SetupStep[] = [+ { step: 'receipt', action: found.prior?.status === 'installed' && found.hooksCurrent && (found.mcp.state === 'current' || !!pluginOwner) && !brainCreate ? '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: `'${flags.name}' in ${found.configPath}` },+ { step: 'hooks', action: found.hooksCurrent ? 'keep' : 'write', detail: plan.events.length ? `${plan.events.join(', ')} in ${found.settingsPath}` : `no hooks (${found.settingsPath})` },+ ...Object.entries(found.edited).map(([event]) => ({ step: 'hooks' as const, action: 'preserve' as const, detail: `${event} was edited after setup wrote it; kept` })),+ ];+ return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes });+ }++ 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,+ });+ 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.');++ let verify: { ok: boolean; reason: string; message: string } | null;+ if (pluginOwner) verify = { ok: false, reason: 'plugin_lane', message: `The '${pluginOwner}' plugin serves MCP; start a new Claude Code 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 = desiredMcpEntry(plan) as { command: string; args: string[]; env: Record<string, string> };+ verify = await smokeStdioRegistration({ harness: 'claude-code', source: found.configPath, kind: 'stdio', command: entry.command, args: entry.args, env: entry.env });+ }+ const states = ['configured', ...(verify.ok ? ['connection-verified', 'native-pending'] : [])];+ const code = await finish(out, { dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent, steps: result.steps, states, verify, notices, notes,+ preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })) });+ 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;+ }+}++function hostedConnection(url: string, wired: boolean, name: string): OperationError {+ 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\`.`,+ { 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.`,+ verify: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'] } } });+}++async function runRemove(flags: SetupFlags, receipt: ClaudeSetupReceipt | 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, { 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 removeClaudeSetup(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}`);+ say(out, 'The brain, its notes and unrelated Claude Code settings were left as they were.');+ return finish(out, { dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: [], preserved: r.preserved });+}++async function finish(out: Out, doc: {+ dryRun: boolean; remove?: boolean; target?: Target; consent?: SetupConsent; steps: SetupStep[]; states: string[];+ verify: { ok: boolean; reason: string; message: string } | null; notices: unknown[]; notes: string[]; preserved?: unknown[];+}): Promise<number> {+ 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,+ ...(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,+ 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.');+ return 0;+}diff --git a/src/core/bootstrap/hooks.ts b/src/core/bootstrap/hooks.tsindex c8dd2839ba..cac93d4e5c 100644--- a/src/core/bootstrap/hooks.ts+++ b/src/core/bootstrap/hooks.ts@@ -24,6 +24,7 @@* (and GBRAIN_HOME when isolated) ride the registration itself.*/+import { createHash } from 'node:crypto';import { copyFileSync, existsSync, readFileSync } from 'node:fs';import { isAbsolute, join } from 'node:path';import { atomicWriteTextFile } from './atomic-write.ts';@@ -117,6 +118,14 @@ export interface WriteClaudeHooksOpts {* key); harness-looking entries outside it survive and get a note.*/identity?: HarnessHookIdentity;+ /**+ * Hash-keyed ownership (`gbrain setup`): when set, an entry is ours only+ * when its `hookEntryHash` is in this set. A marker match alone never+ * replaces or removes an entry, so a user-edited marked hook survives and+ * is listed in `preserved`; an unmarked entry with an owned hash (the host+ * dropped the marker) is still ours.+ */+ ownedEntryHashes?: ReadonlySet<string>;}export interface WriteClaudeHooksResult {@@ -133,6 +142,8 @@ export interface WriteClaudeHooksResult {notes: string[];/** Seat label rendered into the new commands ('' for none). */seat: string;+ /** With `ownedEntryHashes`: marked entries kept because their hash is not owned. */+ preserved: Array<{ event: string; hash: string }>;}export interface RemoveClaudeHooksResult {@@ -145,6 +156,8 @@ export interface RemoveClaudeHooksResult {unmarked: Array<{ event: string; why: string }>;/** Events holding a harness-looking entry that is not this install's; never deleted. */unowned: string[];+ /** With `ownedEntryHashes`: marked entries kept because their hash is not owned. */+ preserved: Array<{ event: string; hash: string }>;}/** Who may claim an UNMARKED harness hook entry: the launchers, sources and@@ -181,6 +194,20 @@ export function claudeSettingsPath(workspaceDir: string): string {return join(workspaceDir, CLAUDE_SETTINGS_FILE_RELPATH);}+/**+ * The ownership hash of one hook command entry: sha256 over its `type`,+ * `command` and `timeout`, the keys the host keeps when it rewrites the+ * file. The `_gbrain` marker and any other key are excluded, so a dropped+ * marker keeps the hash and an edited command or timeout changes it. Null+ * for anything that is not a command entry.+ */+export function hookEntryHash(entry: unknown): string | null {+ if (typeof entry !== 'object' || entry === null) return null;+ const e = entry as Record<string, unknown>;+ if (e.type !== 'command' || typeof e.command !== 'string') return null;+ return createHash('sha256').update(JSON.stringify([e.type, e.command, e.timeout ?? null])).digest('hex');+}+/*** POSIX single-quote anything not already shell-safe (mirror of connect.ts's* private shellQuote — same contract: `$()`/backticks in a value are inert@@ -452,11 +479,13 @@ function stripOurEntries(groups: unknown[],marker: string = GBRAIN_HOOK_MARKER_VALUE,owned?: { event: string; identity: HarnessHookIdentity },-): { kept: unknown[]; removed: number; unmarked: string[]; unowned: number } {+ ownedHashes?: ReadonlySet<string>,+): { kept: unknown[]; removed: number; unmarked: string[]; unowned: number; preserved: string[] } {const kept: unknown[] = [];let removed = 0;const unmarked: string[] = [];let unowned = 0;+ const preserved: string[] = [];for (const group of groups) {if (typeof group !== 'object' || group === null || !Array.isArray((group as HookMatcherGroup).hooks)) {kept.push(group); // structurally foreign — never touch@@ -465,6 +494,12 @@ function stripOurEntries(const g = group as HookMatcherGroup;const before = g.hooks!.length;const filtered = g.hooks!.filter((h) => {+ if (ownedHashes) {+ const hash = hookEntryHash(h);+ if (hash !== null && ownedHashes.has(hash)) return false;+ if (hash !== null && isOurs(h, marker)) preserved.push(hash);+ return true;+ }if (isOurs(h, marker)) return false;if (!owned) return true;const c = classifyHarnessHook(h, owned.event, owned.identity);@@ -483,7 +518,7 @@ function stripOurEntries(kept.push(group);}}- return { kept, removed, unmarked, unowned };+ return { kept, removed, unmarked, unowned, preserved };}/**@@ -630,6 +665,7 @@ export function writeClaudeHooksAt(: opts.env;let removedPrior = 0;const installed: Array<{ event: ClaudeHookEvent; command: string }> = [];+ const preserved: Array<{ event: string; hash: string }> = [];// [X3] Convergence: strip OUR marker from EVERY event in the file first —// not just the requested subset — so a re-run with fewer events (e.g.@@ -638,7 +674,8 @@ export function writeClaudeHooksAt(for (const event of Object.keys(hooks)) {const groups = hooks[event];if (!Array.isArray(groups)) continue; // structurally foreign — never touch- const { kept, removed, unowned } = stripOurEntries(groups, marker, opts.identity && { event, identity: opts.identity });+ const { kept, removed, unowned, preserved: kept_ } = stripOurEntries(groups, marker, opts.identity && { event, identity: opts.identity }, opts.ownedEntryHashes);+ preserved.push(...kept_.map((hash) => ({ event, hash })));removedPrior += removed;if (unowned > 0) {notes.push(@@ -695,7 +732,7 @@ export function writeClaudeHooksAt(}atomicWriteJson(settingsPath, settings, opts.freshMode);- return { settingsPath, installed, removedPrior, backupPath, brokenBackupPath, notes, seat: env.GBRAIN_SEAT ?? '' };+ return { settingsPath, installed, removedPrior, backupPath, brokenBackupPath, notes, seat: env.GBRAIN_SEAT ?? '', preserved };}/**@@ -790,7 +827,7 @@ export function writeCommittedClaudeHooks();}- return { settingsPath, installed, removedPrior, backupPath, brokenBackupPath, notes, seat: '' };+ return { settingsPath, installed, removedPrior, backupPath, brokenBackupPath, notes, seat: '', preserved: [] };}/**@@ -803,10 +840,10 @@ export function writeCommittedClaudeHooks(export function removeClaudeHooksAt(settingsPath: string,marker: string = GBRAIN_HOOK_MARKER_VALUE,- opts: { identity?: HarnessHookIdentity; dryRun?: boolean } = {},+ opts: { identity?: HarnessHookIdentity; dryRun?: boolean; ownedEntryHashes?: ReadonlySet<string> } = {},): RemoveClaudeHooksResult {const nothing = (note: string): RemoveClaudeHooksResult =>- ({ settingsPath, removed: 0, backupPath: null, notes: [note], unmarked: [], unowned: [] });+ ({ settingsPath, removed: 0, backupPath: null, notes: [note], unmarked: [], unowned: [], preserved: [] });if (!existsSync(settingsPath)) return nothing('no settings file — nothing to remove');let settings: SettingsObject;try {@@ -832,11 +869,13 @@ export function removeClaudeHooksAt(let removed = 0;const unmarked: Array<{ event: string; why: string }> = [];const unowned: string[] = [];+ const preserved: Array<{ event: string; hash: string }> = [];for (const event of Object.keys(hooks)) {const groups = hooks[event];if (!Array.isArray(groups)) continue; // structurally foreign — never touch- const strip = stripOurEntries(groups, marker, opts.identity && { event, identity: opts.identity });+ const strip = stripOurEntries(groups, marker, opts.identity && { event, identity: opts.identity }, opts.ownedEntryHashes);const { kept, removed: n } = strip;+ preserved.push(...strip.preserved.map((hash) => ({ event, hash })));removed += n;unmarked.push(...strip.unmarked.map((why) => ({ event, why })));if (strip.unowned > 0) unowned.push(event);@@ -857,7 +896,7 @@ export function removeClaudeHooksAt(copyFileSync(settingsPath, backupPath);atomicWriteJson(settingsPath, settings);}- return { settingsPath, removed, backupPath, notes: [], unmarked, unowned };+ return { settingsPath, removed, backupPath, notes: [], unmarked, unowned, preserved };}/**@@ -934,6 +973,7 @@ export function removeClaudeHooks(workspaceDir: string): RemoveClaudeHooksResultnotes,unmarked: [],unowned: [],+ preserved: [],};}diff --git a/src/core/bootstrap/host-specs.ts b/src/core/bootstrap/host-specs.tsindex d2f24c3bc1..810010365c 100644--- a/src/core/bootstrap/host-specs.ts+++ b/src/core/bootstrap/host-specs.ts@@ -247,6 +247,14 @@ export const GBRAIN_HOOK_MARKER_VALUE = 'bootstrap-v1';*/export const GBRAIN_HARNESS_MARKER_VALUE = 'bootstrap-harness-v1';+/**+ * Marker VALUE for `gbrain setup` installs. Advisory only: setup owns an+ * entry by the exact hash its connection receipt recorded+ * (hooks.ts hookEntryHash), so an edited marked entry is never replaced or+ * removed, and two installs on one machine each keep their own entries.+ */+export const GBRAIN_SETUP_MARKER_VALUE = 'setup-v1';+/*** User-scope Claude Code settings file (harness-mode hook + permissions* target). Resolution mirrors Claude Code itself: CLAUDE_CONFIG_DIR (itsdiff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 1b164391a5..13f7a34600 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -116,6 +116,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],+ 'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--pglite', '--probe', '--providers', '--pure', '--remove', '--scope', '--source', '--surface', '--token', '--url', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex a8e99d3f74..e23cbe639d 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -76,6 +76,10 @@ export const ERROR_CATALOGUE = {sync_drain_preparation_systemic: { code: 'preparation_systemic', docs: 'docs/guides/write-refusals.md#preparation_systemic' },sync_drain_write_capacity: { code: 'queue_capacity', docs: 'docs/guides/write-refusals.md#drain-write-capacity' },sync_drain_connection_lost: { code: 'connection_lost', docs: 'docs/guides/write-refusals.md#drain-connection-lost' },+ // D8 `gbrain setup <harness>` (src/commands/setup.ts).+ setup_harness_unsupported: { code: 'setup_harness_unsupported', docs: 'docs/guides/repair.md#setup-harness-unsupported' },+ setup_owner_conflict: { code: 'setup_owner_conflict', docs: 'docs/guides/repair.md#setup-owner-conflict' },+ setup_hosted_connection: { code: 'setup_hosted_connection', docs: 'docs/guides/repair.md#setup-hosted-connection' },} as const satisfies Record<string, CatalogueEntry>;export type CatalogueName = keyof typeof ERROR_CATALOGUE;diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 23d5409da9..0153247680 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -360,6 +360,9 @@ export const CODES = {scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },serve_port_in_use: { class: 'unavailable', summary: "gbrain serve --http could not listen: another process already holds that host and port.", suggestion: 'Stop the process on that port, or start the server with another --port and point the harnesses at it.' },serve_status_only: { class: 'unavailable', summary: "gbrain serve is in status-only mode: its brain is locked by another server, missing, damaged, or its config is unreadable.", reasons: ['lock_held', 'no_brain', 'config_unreadable', 'missing_brain', 'brain_unopenable', 'repair_failed', 'unavailable'], suggestion: 'Call gbrain_status for the cause, the fix and what to tell the user.' },+ setup_harness_unsupported: { class: 'caller', summary: "gbrain setup does not wire this harness yet; its guide has the manual connection steps.", why: 'Only harnesses with a supported row in the setup capability table are wired automatically, so setup never guesses another host\'s config format.', docs: 'docs/guides/repair.md#setup-harness-unsupported', exit: 2, fix: { argv: ['gbrain', 'setup', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the harnesses setup wires and the guide for each.' } },+ setup_hosted_connection: { class: 'caller', summary: "This machine already reaches a hosted brain, so gbrain setup will not create a second, local brain.", why: 'A new local brain would split memory: sessions would read and write the empty local brain while useful memory stays on the hosted one.', docs: 'docs/guides/repair.md#setup-hosted-connection', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the harness registration reaches.' } },+ setup_owner_conflict: { class: 'caller', summary: "Another owner holds what gbrain setup would change: a live server owns this PGLite brain, or the harness configuration holds an entry setup did not write.", why: 'A PGLite brain has one writer, so a second server would fail on its lock; an entry setup did not record by hash is the user\'s or another install\'s and is never overwritten.', reasons: ['live_serve', 'unowned_entry', 'other_install', 'harness_lane'], docs: 'docs/guides/repair.md#setup-owner-conflict', fix: { argv: ['gbrain', 'setup', 'claude-code', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolved target and which owner blocks it, without writing anything.' } },shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },shared_skills_unsupported: { class: 'unavailable', summary: "The server does not expose the shared-skills protocol." },skill_asset_not_found: { class: 'caller', summary: "The requested file is not in the approved revision manifest." },diff --git a/src/core/setup/capabilities.ts b/src/core/setup/capabilities.tsnew file mode 100644index 0000000000..bf10f1d340--- /dev/null+++ b/src/core/setup/capabilities.ts@@ -0,0 +1,55 @@+/**+ * The versioned harness x transport capability table behind `gbrain setup`.+ *+ * Data, not prose: one row per harness and transport, saying whether setup+ * wires it, which context it can read (pull through MCP tools) and whether+ * gbrain context reaches a native session without being asked (push). A push+ * row stays `native-pending` until an observed event injects a randomized item+ * into a fresh native session; nothing in this table is claimed from docs or+ * from a shell probe alone. Bump `SETUP_CAPABILITY_TABLE_VERSION` when a row's+ * meaning changes.+ */++export const SETUP_CAPABILITY_TABLE_VERSION = 1;++export const SETUP_HARNESSES = ['claude-code', 'codex', 'openclaw', 'hermes'] as const;+export type SetupHarness = (typeof SETUP_HARNESSES)[number];++export type SetupTransport = 'local-stdio' | 'local-context-engine' | 'thin-client';++export interface SetupCapabilityRow {+ harness: SetupHarness;+ transport: SetupTransport;+ /** `supported`: `gbrain setup <harness>` wires it; `unsupported`: coded refusal with `docs`. */+ setup: 'supported' | 'unsupported';+ /** Pull: memory tools the session can call. `connection-verified` means setup's smoke proves it. */+ pull: 'connection-verified' | 'manual';+ /** Push without a tool call. `native-verified` requires an observed injected event. */+ push: 'native-pending' | 'native-verified' | 'unsupported';+ /** Events setup installs on a memory-only setup (read context only). */+ read_events: readonly string[];+ /** Events installed only after automatic capture is accepted. */+ capture_events: readonly string[];+ docs: string;+}++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: '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',+ read_events: [], capture_events: [], docs: 'docs/mcp/OPENCLAW.md' },+ { harness: 'hermes', transport: 'local-stdio', setup: 'unsupported', pull: 'manual', push: 'unsupported',+ read_events: [], capture_events: [], docs: 'docs/mcp/HERMES.md' },+];++export function isSetupHarness(v: string | undefined): v is SetupHarness {+ return (SETUP_HARNESSES as readonly string[]).includes(v ?? '');+}++export function capabilityRows(harness: SetupHarness): SetupCapabilityRow[] {+ return SETUP_CAPABILITIES.filter((r) => r.harness === harness);+}diff --git a/src/core/setup/claude-code.ts b/src/core/setup/claude-code.tsnew file mode 100644index 0000000000..c9089b1710--- /dev/null+++ b/src/core/setup/claude-code.ts@@ -0,0 +1,423 @@+/**+ * Claude Code wiring for `gbrain setup claude-code`: the MCP entry in+ * Claude Code's own config (`~/.claude.json`, user scope, or that file's+ * `projects[<dir>]` block for project scope) and the hook entries in its+ * settings file, owned by exact hash through a connection receipt.+ *+ * The receipt is the connection receipt `gbrain connect --install` already+ * writes next to the harness config (`.gbrain-connection-claude-code-<name>.json`,+ * `entry_hash` / `pending_entry_hash`, `status: prepared | installed`), with a+ * `connection: 'local-stdio'` marker and the hook hashes added. A hosted+ * receipt (it carries `client_id`) is never adopted.+ *+ * Write order, each step idempotent and resumable from the receipt:+ * 1. receipt `prepared`: consent decisions plus the pending MCP and hook hashes+ * 2. MCP entry, then the receipt records its hash+ * 3. hook entries, then the receipt records their hashes+ * 4. receipt `installed`+ * A crash after any step leaves pending hashes that the next run treats as+ * owned, so a resume never duplicates an entry. An entry whose hash the+ * receipt did not record is never replaced or removed.+ */+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 { acquireBootstrapLock } from '../bootstrap/lock.ts';+import { buildClaudeHookCommand, classifyHarnessHook, hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../bootstrap/hooks.ts';+import {+ CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS,+ CLAUDE_HOOK_EVENTS,+ CLAUDE_SETTINGS_FILE_RELPATH,+ GBRAIN_HOOK_MARKER_KEY,+ GBRAIN_SETUP_MARKER_VALUE,+ claudeUserMcpConfigPath,+ claudeUserSettingsPath,+ type ClaudeHookEvent,+} from '../bootstrap/host-specs.ts';+import { stdioServeArgv } from '../mcp-registration.ts';+import type { McpSurface } from '../../mcp/surface.ts';++export type WiringScope = 'user' | 'project';+export type DecisionSource = 'flag' | 'default' | 'prior' | 'opt_out';+export interface Decision<T> { value: T; source: DecisionSource; note?: string }++/** The three setup decisions, recorded separately (D8). */+export interface SetupConsent {+ wiring_scope: Decision<{ scope: WiringScope; hooks: 'read-context' | 'none' }>;+ capture: Decision<'accepted' | 'declined'>;+ providers: Decision<'accepted' | 'declined'>;+}++type HookHashes = Partial<Record<ClaudeHookEvent, string>>;++export interface ClaudeSetupReceipt {+ harness: 'claude-code';+ connection: 'local-stdio';+ setup_receipt_version: 1;+ status: 'prepared' | 'installed' | 'removed';+ name: string;+ gbrain_home: string;+ launcher: string;+ scope: WiringScope;+ project_dir?: string;+ source_id: string | null;+ surface: McpSurface;+ config_path: string;+ entry_hash: string | null;+ pending_entry_hash: string | null;+ /** The entry existed byte-identical before setup ran; `--remove` keeps it. */+ mcp_adopted?: boolean;+ /** The gbrain plugin serves the MCP name; setup wrote no MCP entry. */+ mcp_plugin?: string;+ hooks: { settings_path: string; owned: HookHashes; pending: HookHashes; edited: HookHashes };+ consent: SetupConsent & { recorded_at: string };+ brain_created_by_setup: boolean;+ native_harness_verified: false;+ created_at: string;+ updated_at: string;+}++export interface ClaudeSetupPlan {+ name: string;+ scope: WiringScope;+ projectDir?: string;+ launcher: string;+ /** `configDir()` of the install: the receipt's identity. */+ brainHome: string;+ /** GBRAIN_HOME as set in this environment, rendered into the entry and the hooks. */+ gbrainHomeEnv?: string;+ sourceId: string | null;+ surface: McpSurface;+ events: ClaudeHookEvent[];+}++export interface SetupStep { step: 'brain' | 'receipt' | 'mcp' | 'hooks'; action: 'write' | 'keep' | 'skip' | 'remove' | 'preserve'; detail: string }++export interface ClaudeInspection {+ configPath: string;+ settingsPath: string;+ receiptPath: string;+ prior: ClaudeSetupReceipt | null;+ /** A hosted `gbrain connect --install` receipt sits at this name. */+ hostedReceipt: { mcp_url?: string } | null;+ mcp: { state: 'absent' | 'current' | 'owned' | 'remote' | 'unowned'; url?: string };+ /** Events wired by another gbrain lane in this settings file. */+ otherLaneEvents: string[];+ /** Owned events whose entry the user edited: preserved, never rewritten. */+ edited: HookHashes;+ /** True when the desired hooks are present and nothing owned is stale. */+ 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 function claudeSetupPaths(plan: Pick<ClaudeSetupPlan, 'name' | 'scope' | 'projectDir'>): { configPath: string; settingsPath: string; receiptPath: string } {+ const configPath = claudeUserMcpConfigPath();+ const suffix = plan.scope === 'project' ? `-project-${createHash('sha256').update(plan.projectDir!).digest('hex').slice(0, 12)}` : '';+ return {+ configPath,+ settingsPath: plan.scope === 'project' ? join(plan.projectDir!, CLAUDE_SETTINGS_FILE_RELPATH) : claudeUserSettingsPath(),+ receiptPath: join(dirname(configPath), `.gbrain-connection-claude-code-${plan.name}${suffix}.json`),+ };+}++function readJsonObject(path: string): Record<string, unknown> {+ if (!existsSync(path)) return {};+ const text = readFileSync(path, 'utf8');+ if (text.trim() === '') return {};+ let parsed: unknown;+ try { parsed = JSON.parse(text); } catch (e) {+ throw new Error(`${path} is not valid JSON (${(e as Error).message}); setup never rewrites a file it cannot parse. Fix it by hand, then run setup again.`);+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`${path} is not a JSON object; setup never rewrites a file it cannot parse.`);+ return parsed as Record<string, unknown>;+}++export function readSetupReceipt(receiptPath: string): { setup: ClaudeSetupReceipt | null; hosted: { mcp_url?: string } | null } {+ if (!existsSync(receiptPath)) return { setup: null, hosted: null };+ let raw: Record<string, unknown>;+ try { raw = readJsonObject(receiptPath); } 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.connection === 'local-stdio' && raw.setup_receipt_version === 1) return { setup: raw as unknown as ClaudeSetupReceipt, hosted: null };+ throw new Error(`the connection receipt ${receiptPath} was not written by gbrain setup; it is left untouched. Choose another --name.`);+}++function writeSetupReceipt(path: string, receipt: ClaudeSetupReceipt): void {+ atomicWriteTextFile(path, `${JSON.stringify(receipt, null, 2)}\n`, { forceMode: 0o600 });+}++function mcpServers(config: Record<string, unknown>, plan: Pick<ClaudeSetupPlan, 'scope' | 'projectDir'>, create: boolean): Record<string, unknown> | undefined {+ let holder: Record<string, unknown> = config;+ if (plan.scope === 'project') {+ const projects = config.projects as Record<string, unknown> | undefined;+ if (projects !== undefined && (typeof projects !== 'object' || projects === null || Array.isArray(projects))) throw new Error('the Claude Code config "projects" key is not an object; setup leaves it untouched.');+ if (!projects && !create) return undefined;+ const all = projects ?? (config.projects = {}) as Record<string, unknown>;+ const project = all[plan.projectDir!] as Record<string, unknown> | undefined;+ if (!project && !create) return undefined;+ holder = project ?? (all[plan.projectDir!] = {}) as Record<string, unknown>;+ }+ const servers = holder.mcpServers;+ if (servers !== undefined && (typeof servers !== 'object' || servers === null || Array.isArray(servers))) throw new Error('the Claude Code "mcpServers" key is not an object; setup leaves it untouched.');+ if (!servers && !create) return undefined;+ return (servers ?? (holder.mcpServers = {})) as Record<string, unknown>;+}++function hookEnv(plan: ClaudeSetupPlan) {+ return { ...(plan.sourceId ? { GBRAIN_SOURCE: plan.sourceId } : {}), ...(plan.gbrainHomeEnv ? { GBRAIN_HOME: plan.gbrainHomeEnv } : {}), GBRAIN_SEAT: '' };+}++export function desiredMcpEntry(plan: ClaudeSetupPlan): Record<string, unknown> {+ const env: Record<string, string> = {};+ if (plan.gbrainHomeEnv) env.GBRAIN_HOME = plan.gbrainHomeEnv;+ if (plan.sourceId) env.GBRAIN_SOURCE = plan.sourceId;+ return { type: 'stdio', command: plan.launcher, args: stdioServeArgv(plan.launcher, plan.surface).slice(1), env };+}++export function desiredHookHashes(plan: ClaudeSetupPlan): HookHashes {+ const out: HookHashes = {};+ for (const event of plan.events) {+ out[event] = hookEntryHash({ type: 'command', command: buildClaudeHookCommand(plan.launcher, event, hookEnv(plan)), timeout: CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS[event] })!;+ }+ return out;+}++const consentValues = (c: SetupConsent): string => JSON.stringify([c.wiring_scope.value.scope, c.wiring_scope.value.hooks, c.capture.value, c.providers.value]);++const values = (h: HookHashes | undefined): string[] => Object.values(h ?? {}).filter((v): v is string => typeof v === 'string');++interface HookCensus { byEvent: Map<string, Array<{ hash: string; marked: boolean }>>; otherLane: Set<string> }++function hookCensus(settingsPath: string): HookCensus {+ const settings = readJsonObject(settingsPath);+ const byEvent = new Map<string, Array<{ hash: string; marked: boolean }>>();+ const otherLane = new Set<string>();+ const hooks = settings.hooks;+ if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) return { byEvent, otherLane };+ for (const [event, groups] of Object.entries(hooks as Record<string, unknown>)) {+ if (!Array.isArray(groups)) continue;+ for (const group of groups) {+ const entries = (group as { hooks?: unknown })?.hooks;+ if (!Array.isArray(entries)) continue;+ for (const entry of entries) {+ const marker = (entry as Record<string, unknown> | null)?.[GBRAIN_HOOK_MARKER_KEY];+ if ((typeof marker === 'string' && marker !== GBRAIN_SETUP_MARKER_VALUE) || classifyHarnessHook(entry, event, 'any')) {+ if ((CLAUDE_HOOK_EVENTS as readonly string[]).includes(event)) otherLane.add(event);+ continue;+ }+ const hash = hookEntryHash(entry);+ if (hash) byEvent.set(event, [...(byEvent.get(event) ?? []), { hash, marked: marker === GBRAIN_SETUP_MARKER_VALUE }]);+ }+ }+ }+ return { byEvent, otherLane };+}++/** Read-only: what setup would find and own. Throws on an unparseable config. */+export function inspectClaudeSetup(plan: ClaudeSetupPlan): ClaudeInspection {+ const paths = claudeSetupPaths(plan);+ const { setup: prior, hosted } = readSetupReceipt(paths.receiptPath);+ const servers = mcpServers(readJsonObject(paths.configPath), plan, false);+ const entry = servers?.[plan.name];+ const desired = entryHash(desiredMcpEntry(plan));+ const mcp: ClaudeInspection['mcp'] = entry === undefined ? { state: 'absent' }+ : entryHash(entry) === 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(entryHash(entry)) ? { state: 'owned' } : { state: 'unowned' };++ const census = hookCensus(paths.settingsPath);+ const want = desiredHookHashes(plan);+ const owned = new Set([...values(prior?.hooks.owned), ...values(prior?.hooks.pending), ...values(want)]);+ const edited: HookHashes = {};+ for (const event of CLAUDE_HOOK_EVENTS) {+ const present = census.byEvent.get(event) ?? [];+ const recorded = prior?.hooks.owned[event];+ const priorEdit = prior?.hooks.edited[event];+ const stillEdited = priorEdit && present.some((p) => p.hash === priorEdit);+ const newlyEdited = recorded && !present.some((p) => p.hash === recorded) && present.find((p) => p.marked && !owned.has(p.hash));+ if (stillEdited) edited[event] = priorEdit;+ else if (newlyEdited) edited[event] = newlyEdited.hash;+ }+ let hooksCurrent = true;+ for (const [event, present] of census.byEvent) {+ const target = want[event as ClaudeHookEvent];+ if (present.some((p) => owned.has(p.hash) && p.hash !== target)) hooksCurrent = false;+ if (target && present.filter((p) => p.hash === target).length > 1) hooksCurrent = false;+ }+ for (const event of plan.events) {+ if (!edited[event] && !(census.byEvent.get(event) ?? []).some((p) => p.hash === want[event])) hooksCurrent = false;+ }+ return { ...paths, prior, hostedReceipt: hosted, mcp, otherLaneEvents: [...census.otherLane], edited, hooksCurrent };+}++export interface ApplyResult { steps: SetupStep[]; receipt: ClaudeSetupReceipt; changed: boolean; edited: HookHashes }++/**+ * Apply the plan under the config-dir lock. `pluginOwner` skips the MCP+ * entry (the plugin serves the name). `beforeMcp` runs after the receipt is+ * prepared and before the MCP write (the brain init step); `abortAfter` is+ * the crash-injection test seam.+ */+export async function applyClaudeSetup(+ plan: ClaudeSetupPlan,+ consent: SetupConsent,+ opts: { pluginOwner: string | null; brainCreated: boolean; beforeMcp?: () => Promise<void>; abortAfter?: string },+): Promise<ApplyResult> {+ const paths = claudeSetupPaths(plan);+ const lock = await acquireBootstrapLock(dirname(paths.configPath));+ try {+ const found = inspectClaudeSetup(plan);+ const now = new Date().toISOString();+ const desired = desiredMcpEntry(plan);+ const desiredHash = entryHash(desired);+ const want = desiredHookHashes(plan);+ const writeEvents = plan.events.filter((e) => !found.edited[e]);+ const prior = found.prior;+ const consentSame = prior?.consent !== undefined && consentValues(prior.consent) === consentValues(consent);+ const mcpDone = opts.pluginOwner !== null || found.mcp.state === 'current';+ const steps: SetupStep[] = [];+ if (prior?.status === 'installed' && consentSame && mcpDone && found.hooksCurrent && !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}'` : `'${plan.name}' in ${paths.configPath} is current` });+ steps.push({ step: 'hooks', action: 'keep', detail: plan.events.length ? `${plan.events.join(', ')} in ${paths.settingsPath} are current` : 'no hooks wanted' });+ return { steps, receipt: prior, changed: false, edited: found.edited };+ }+ const receipt: ClaudeSetupReceipt = {+ harness: 'claude-code', connection: 'local-stdio', setup_receipt_version: 1, status: 'prepared',+ name: plan.name, gbrain_home: plan.brainHome, launcher: plan.launcher, scope: plan.scope,+ ...(plan.projectDir ? { project_dir: plan.projectDir } : {}),+ source_id: plan.sourceId, surface: plan.surface, config_path: paths.configPath,+ 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: { settings_path: paths.settingsPath, owned: prior?.hooks.owned ?? {}, pending: Object.fromEntries(writeEvents.map((e) => [e, want[e]])), edited: found.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 = () => writeSetupReceipt(paths.receiptPath, receipt);+ save();+ steps.push({ step: 'receipt', action: 'write', detail: `${paths.receiptPath} (prepared: consent and pending hashes recorded)` });+ if (opts.abortAfter === 'receipt') throw new SetupAbortInjected('receipt');+ await opts.beforeMcp?.();++ if (opts.pluginOwner) {+ steps.push({ step: 'mcp', action: 'skip', detail: `the '${opts.pluginOwner}' plugin serves '${plan.name}'; no hand-wired entry` });+ } else if (found.mcp.state === 'current') {+ if (!prior?.entry_hash && !prior?.pending_entry_hash) receipt.mcp_adopted = true;+ receipt.entry_hash = desiredHash;+ steps.push({ step: 'mcp', action: 'keep', detail: `'${plan.name}' in ${paths.configPath} is current${receipt.mcp_adopted ? ' (adopted: it was already there, so --remove keeps it)' : ''}` });+ } else {+ const config = readJsonObject(paths.configPath);+ mcpServers(config, plan, true)![plan.name] = desired;+ atomicWriteTextFile(paths.configPath, `${JSON.stringify(config, null, 2)}\n`, { freshMode: 0o600 });+ receipt.entry_hash = desiredHash;+ delete receipt.mcp_adopted;+ steps.push({ step: 'mcp', action: 'write', detail: `'${plan.name}' in ${paths.configPath}` });+ }+ receipt.pending_entry_hash = null;+ save();+ if (opts.abortAfter === 'mcp') throw new SetupAbortInjected('mcp');++ if (found.hooksCurrent) {+ steps.push({ step: 'hooks', action: 'keep', detail: plan.events.length ? `${plan.events.join(', ')} in ${paths.settingsPath} are current` : 'no hooks wanted' });+ } else {+ const ownedHashes = new Set([...values(prior?.hooks.owned), ...values(prior?.hooks.pending), ...values(receipt.hooks.pending)]);+ writeClaudeHooksAt(paths.settingsPath, {+ gbrainBin: plan.launcher, env: hookEnv(plan), events: writeEvents, marker: GBRAIN_SETUP_MARKER_VALUE,+ ownedEntryHashes: ownedHashes, freshMode: 0o600,+ });+ steps.push({ step: 'hooks', action: 'write', detail: writeEvents.length ? `${writeEvents.join(', ')} in ${paths.settingsPath}` : `removed setup's hooks from ${paths.settingsPath}` });+ }+ for (const [event, hash] of Object.entries(found.edited)) {+ steps.push({ step: 'hooks', action: 'preserve', detail: `${event} in ${paths.settingsPath} was edited after setup wrote it (hash ${hash.slice(0, 12)}); kept as is` });+ }+ receipt.hooks.owned = Object.fromEntries(writeEvents.map((e) => [e, want[e]]));+ receipt.hooks.pending = {};+ save();+ if (opts.abortAfter === 'hooks') throw new SetupAbortInjected('hooks');+ receipt.status = 'installed';+ save();+ return { steps, receipt, changed: true, edited: found.edited };+ } finally {+ lock.release();+ }+}++export interface RemoveResult { steps: SetupStep[]; preserved: Array<{ kind: 'mcp' | 'hook'; event?: string; reason: string }>; receiptRemoved: boolean }++/** Remove exactly what the receipt owns by hash; edited entries survive and are reported. */+export async function removeClaudeSetup(receipt: ClaudeSetupReceipt, receiptPath: string, opts: { dryRun: boolean }): Promise<RemoveResult> {+ const plan = { name: receipt.name, scope: receipt.scope, projectDir: receipt.project_dir };+ const lock = await acquireBootstrapLock(dirname(receipt.config_path));+ try {+ const steps: SetupStep[] = [];+ const preserved: RemoveResult['preserved'] = [];+ const config = readJsonObject(receipt.config_path);+ const servers = mcpServers(config, plan, false);+ const entry = servers?.[receipt.name];+ if (receipt.mcp_plugin) {+ steps.push({ step: 'mcp', action: 'skip', detail: `the '${receipt.mcp_plugin}' plugin serves '${receipt.name}'; setup wrote no entry` });+ } else if (entry === undefined) {+ steps.push({ step: 'mcp', action: 'skip', detail: `no '${receipt.name}' entry in ${receipt.config_path}` });+ } else if (receipt.mcp_adopted && entryHash(entry) === receipt.entry_hash) {+ steps.push({ step: 'mcp', action: 'preserve', detail: `'${receipt.name}' existed before setup ran; kept` });+ preserved.push({ kind: 'mcp', reason: 'adopted' });+ } else if ([receipt.entry_hash, receipt.pending_entry_hash].includes(entryHash(entry))) {+ if (!opts.dryRun) {+ delete servers![receipt.name];+ atomicWriteTextFile(receipt.config_path, `${JSON.stringify(config, null, 2)}\n`, { freshMode: 0o600 });+ }+ steps.push({ step: 'mcp', action: 'remove', detail: `'${receipt.name}' from ${receipt.config_path}` });+ } else {+ steps.push({ step: 'mcp', action: 'preserve', detail: `'${receipt.name}' in ${receipt.config_path} changed after setup wrote it; kept` });+ preserved.push({ kind: 'mcp', reason: 'edited' });+ }++ const owned = new Set([...values(receipt.hooks.owned), ...values(receipt.hooks.pending)]);+ let before: HookCensus['byEvent'] = new Map();+ try { before = hookCensus(receipt.hooks.settings_path).byEvent; } catch { /* removeClaudeHooksAt reports an unparseable file */ }+ const r = removeClaudeHooksAt(receipt.hooks.settings_path, GBRAIN_SETUP_MARKER_VALUE, { ownedEntryHashes: owned, dryRun: opts.dryRun });+ steps.push({ step: 'hooks', action: r.removed > 0 ? 'remove' : 'skip', detail: r.removed > 0 ? `${r.removed} hook entr${r.removed === 1 ? 'y' : 'ies'} from ${r.settingsPath}` : (r.notes[0] ?? 'no owned hook entries present') });+ const edited: HookHashes = {};+ for (const p of r.preserved) {+ const event = p.event as ClaudeHookEvent;+ const recorded = receipt.hooks.owned[event] ?? receipt.hooks.pending[event];+ const ours = receipt.hooks.edited[event] === p.hash+ || (recorded !== undefined && !(before.get(event) ?? []).some((e) => e.hash === recorded) && edited[event] === undefined);+ if (!ours) continue;+ edited[p.event as ClaudeHookEvent] = p.hash;+ preserved.push({ kind: 'hook', event: p.event, reason: 'edited' });+ steps.push({ step: 'hooks', action: 'preserve', detail: `${p.event} in ${r.settingsPath} was edited after setup wrote it; kept` });+ }++ let receiptRemoved = false;+ if (!opts.dryRun) {+ if (preserved.some((p) => p.reason === 'edited')) {+ writeSetupReceipt(receiptPath, { ...receipt, status: 'removed', entry_hash: null, pending_entry_hash: null,+ hooks: { ...receipt.hooks, owned: {}, pending: {}, edited }, 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, receiptRemoved };+ } finally {+ lock.release();+ }+}++export class SetupAbortInjected extends Error {+ constructor(readonly phase: string) {+ super(`setup aborted after ${phase} (GBRAIN_SETUP_ABORT_AFTER test seam)`);+ this.name = 'SetupAbortInjected';+ }+}diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.jsonindex 41c1206a02..74f545a511 100644--- a/test/fixtures/goldens/cli/dispatch-phase.json+++ b/test/fixtures/goldens/cli/dispatch-phase.json@@ -1618,6 +1618,25 @@"thinClient": "refuse","thinClientRoutedSubcommands": []},+ "setup": {+ "hasSwitchCase": false,+ "phase": "pre-connect",+ "preConnectRules": [+ {+ "condition": "command === 'setup'",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": false,+ "unconditionalFor": [+ "setup"+ ]+ }+ ],+ "thinClient": "none",+ "thinClientRoutedSubcommands": []+ },"skillify": {"hasSwitchCase": false,"phase": "pre-connect",diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.jsonindex 484ee93e68..d1e72c5249 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -13,6 +13,7 @@"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)"," init [--pglite|--supabase|--url] Create brain (PGLite default, no server)"," init --prefer-postgres [--allow-docker]"," Postgres-first install ladder (env URL >",@@ -225,6 +226,7 @@"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)"," init [--pglite|--supabase|--url] Create brain (PGLite default, no server)"," init --prefer-postgres [--allow-docker]"," Postgres-first install ladder (env URL >",@@ -437,6 +439,7 @@"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)"," 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/fixtures/goldens/cli/membership-sets.json b/test/fixtures/goldens/cli/membership-sets.jsonindex e30920b936..867dad7094 100644--- a/test/fixtures/goldens/cli/membership-sets.json+++ b/test/fixtures/goldens/cli/membership-sets.json@@ -189,6 +189,7 @@"schema","self-upgrade","serve",+ "setup","skillify","skillopt","skillpack",@@ -286,6 +287,7 @@"salience","schema","self-upgrade",+ "setup","skillify","skillopt","skillpack",diff --git a/test/setup.test.ts b/test/setup.test.tsnew file mode 100644index 0000000000..0754d11a1e--- /dev/null+++ b/test/setup.test.ts@@ -0,0 +1,383 @@+/**+ * `gbrain setup claude-code` (D8): the CLI-only command row's behavior test,+ * spawning `bun src/cli.ts setup` against a temp HOME / GBRAIN_HOME.+ *+ * Authoring gate:+ * 1. Protects: setup resolves its target before writing, owns harness+ * entries by exact hash (resume never duplicates, --remove deletes only+ * unchanged owned entries, another install's entries survive), records+ * three consent decisions with memory-only defaults, and never falls back+ * from a hosted connection or starts a second PGLite owner.+ * 2. Fails on: marker-only ownership (an edited hook removed), a resume that+ * appends a second hook, a capture hook installed without acceptance or+ * over an opt-out, a local brain created next to a hosted one, a+ * registration written while a foreign live serve holds the lock.+ * 3. New command; bootstrap's tests cover its own lanes, and the+ * hooks.ts unit block below pins that their marker-only behavior is+ * unchanged.+ * 4. One seam: GBRAIN_SETUP_ABORT_AFTER (crash injection between files).+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { createServer, type Server } from 'node:net';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+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';++const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');+const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++interface Box { root: string; home: string; gbrainHome: string; bin: string }++function box(): Box {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-setup-'));+ roots.push(root);+ const home = join(root, 'home');+ mkdirSync(home, { recursive: true });+ const bin = join(root, 'bin', 'gbrain');+ mkdirSync(join(root, 'bin'));+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);+ chmodSync(bin, 0o755);+ 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 };++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 } });+ let doc: any = null;+ if (args.includes('--json')) { try { doc = JSON.parse(r.stdout); } catch { doc = null; } }+ return { ...r, doc };+}++const readJson = (p: string): any => JSON.parse(readFileSync(p, 'utf8'));+const claudeJson = (b: Box) => join(b.home, '.claude.json');+const settings = (b: Box) => join(b.home, '.claude', 'settings.json');+const receipt = (b: Box, name = 'gbrain') => join(b.home, `.gbrain-connection-claude-code-${name}.json`);++/** Every hook entry under an event, flattened. */+function entries(b: Box, event: string): any[] {+ if (!existsSync(settings(b))) return [];+ return (readJson(settings(b)).hooks?.[event] ?? []).flatMap((g: any) => g.hooks ?? []);+}++describe('gbrain setup claude-code: install lifecycle', () => {+ test('fresh install creates a keyless brain, wires MCP + read-context hooks only, verifies; a second run changes nothing', async () => {+ const b = box();+ const first = await setup(b, ['claude-code', '--json']);+ expect(first.exitCode).toBe(0);+ expect(first.doc.target.brain.kind).toBe('new-local-pglite');+ expect(first.doc.target.launcher).toBe(b.bin);+ expect(first.doc.states).toEqual(['configured', 'connection-verified', 'native-pending']);+ expect(first.doc.verify.reason).toBe('smoke_passed');+ expect(first.doc.consent.capture).toMatchObject({ value: 'declined', source: 'default' });+ expect(first.doc.consent.providers).toMatchObject({ value: 'declined', source: 'default' });+ expect(readJson(join(b.gbrainHome, '.gbrain', 'config.json')).embedding_disabled).toBe(true);+ const entry = readJson(claudeJson(b)).mcpServers.gbrain;+ expect(entry).toEqual({ type: 'stdio', command: b.bin, args: ['serve', '--surface', 'full'], env: { GBRAIN_HOME: b.gbrainHome } });+ expect(Object.keys(readJson(settings(b)).hooks).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);+ expect(readJson(receipt(b)).status).toBe('installed');++ const before = [readFileSync(claudeJson(b), 'utf8'), readFileSync(settings(b), 'utf8'), readFileSync(receipt(b), 'utf8')];+ const second = await setup(b, ['claude-code', '--json']);+ expect(second.exitCode).toBe(0);+ expect(second.doc.steps.map((s: any) => s.action)).toEqual(['keep', 'keep', 'keep']);+ expect([readFileSync(claudeJson(b), 'utf8'), readFileSync(settings(b), 'utf8'), readFileSync(receipt(b), 'utf8')]).toEqual(before);+ expect(existsSync(`${settings(b)}.bak`)).toBe(false);+ }, 60_000);++ test('--remove deletes exactly the owned entries; foreign hooks, other MCP servers and the brain stay', async () => {+ const b = box();+ mkdirSync(join(b.home, '.claude'), { recursive: true });+ const foreign = { type: 'command', command: 'echo user-hook', timeout: 2 };+ writeFileSync(settings(b), JSON.stringify({ theme: 'dark', hooks: { SessionStart: [{ hooks: [foreign] }] } }));+ writeFileSync(claudeJson(b), JSON.stringify({ mcpServers: { other: { type: 'stdio', command: '/bin/true', args: [] } }, numStartups: 3 }));+ expect((await setup(b, ['claude-code'])).exitCode).toBe(0);+ expect(entries(b, 'SessionStart')).toHaveLength(2);++ const preview = await setup(b, ['claude-code', '--remove', '--dry-run', '--json']);+ expect(preview.exitCode).toBe(0);+ expect(readJson(claudeJson(b)).mcpServers.gbrain).toBeDefined();++ const removed = await setup(b, ['claude-code', '--remove', '--json']);+ expect(removed.exitCode).toBe(0);+ expect(removed.doc.preserved).toEqual([]);+ const cfg = readJson(claudeJson(b));+ expect(cfg.mcpServers).toEqual({ other: { type: 'stdio', command: '/bin/true', args: [] } });+ expect(cfg.numStartups).toBe(3);+ const s = readJson(settings(b));+ expect(s.theme).toBe('dark');+ expect(s.hooks).toEqual({ SessionStart: [{ hooks: [foreign] }] });+ expect(existsSync(receipt(b))).toBe(false);+ expect(existsSync(join(b.gbrainHome, '.gbrain', 'brain.pglite'))).toBe(true);+ }, 60_000);++ 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, ['claude-code'], { GBRAIN_SETUP_ABORT_AFTER: 'mcp' });+ expect(crashed.exitCode).toBe(1);+ expect(crashed.stderr).toContain('aborted after mcp');+ expect(readJson(claudeJson(b)).mcpServers.gbrain).toBeDefined();+ expect(existsSync(settings(b))).toBe(false);+ const mid = readJson(receipt(b));+ expect(mid.status).toBe('prepared');+ expect(Object.keys(mid.hooks.pending).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);++ const resumed = await setup(b, ['claude-code', '--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(Object.keys(readJson(claudeJson(b)).mcpServers)).toEqual(['gbrain']);+ expect(entries(b, 'SessionStart')).toHaveLength(1);+ expect(entries(b, 'UserPromptSubmit')).toHaveLength(1);+ expect(readJson(receipt(b)).status).toBe('installed');+ expect(readJson(receipt(b)).brain_created_by_setup).toBe(true);+ }, 60_000);++ test('a user-edited owned hook survives --remove, is reported, and a later setup leaves it alone', async () => {+ const b = box();+ expect((await setup(b, ['claude-code'])).exitCode).toBe(0);+ const s = readJson(settings(b));+ const edited = s.hooks.SessionStart[0].hooks[0];+ edited.command = `${edited.command} --verbose`;+ expect(edited._gbrain).toBe('setup-v1');+ writeFileSync(settings(b), JSON.stringify(s, null, 2));++ const removed = await setup(b, ['claude-code', '--remove', '--json']);+ expect(removed.exitCode).toBe(0);+ expect(removed.doc.preserved).toEqual([{ kind: 'hook', event: 'SessionStart', reason: 'edited' }]);+ expect(entries(b, 'SessionStart')).toEqual([edited]);+ expect(entries(b, 'UserPromptSubmit')).toEqual([]);+ expect(readJson(claudeJson(b)).mcpServers.gbrain).toBeUndefined();++ const again = await setup(b, ['claude-code', '--json']);+ expect(again.exitCode).toBe(0);+ expect(again.doc.preserved).toEqual([{ kind: 'hook', event: 'SessionStart', reason: 'edited' }]);+ expect(entries(b, 'SessionStart')).toEqual([edited]);+ expect(entries(b, 'UserPromptSubmit')).toHaveLength(1);+ }, 60_000);++ test('an MCP entry setup did not write is refused (setup_owner_conflict), an identical one is adopted and kept on --remove', async () => {+ const b = box();+ const foreignCfg = JSON.stringify({ mcpServers: { gbrain: { type: 'stdio', command: '/opt/other/gbrain', args: ['serve'] } } });+ writeFileSync(claudeJson(b), foreignCfg);+ const refused = await setup(b, ['claude-code', '--json']);+ expect(refused.exitCode).toBe(1);+ expect(refused.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'unowned_entry' });+ expect(readFileSync(claudeJson(b), 'utf8')).toBe(foreignCfg);+ expect(existsSync(settings(b))).toBe(false);++ const same = { type: 'stdio', command: b.bin, args: ['serve', '--surface', 'full'], env: { GBRAIN_HOME: b.gbrainHome } };+ writeFileSync(claudeJson(b), JSON.stringify({ mcpServers: { gbrain: same } }));+ const adopted = await setup(b, ['claude-code', '--json']);+ expect(adopted.exitCode).toBe(0);+ expect(readJson(receipt(b)).mcp_adopted).toBe(true);+ const removed = await setup(b, ['claude-code', '--remove', '--json']);+ expect(removed.exitCode).toBe(0);+ expect(readJson(claudeJson(b)).mcpServers.gbrain).toEqual(same);+ }, 60_000);++ 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, ['claude-code'])).exitCode).toBe(0);+ const clash = await setup(b, ['claude-code', '--json']);+ expect(clash.exitCode).toBe(1);+ expect(clash.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'other_install' });++ expect((await setup(b, ['claude-code', '--name', 'gbrain-b'])).exitCode).toBe(0);+ expect(Object.keys(readJson(claudeJson(a)).mcpServers).sort()).toEqual(['gbrain', 'gbrain-b']);+ expect(entries(a, 'SessionStart')).toHaveLength(2);+ const aOnly = entries(a, 'SessionStart').filter((e) => e.command.includes(`GBRAIN_HOME=${a.gbrainHome} `));++ expect((await setup(b, ['claude-code', '--name', 'gbrain-b', '--remove'])).exitCode).toBe(0);+ expect(Object.keys(readJson(claudeJson(a)).mcpServers)).toEqual(['gbrain']);+ expect(entries(a, 'SessionStart')).toEqual(aOnly);+ expect(existsSync(receipt(a))).toBe(true);+ expect(existsSync(receipt(a, 'gbrain-b'))).toBe(false);+ }, 60_000);+});++describe('gbrain setup claude-code: target first', () => {+ test('--dry-run prints the target and writes nothing; GBRAIN_SURFACE is honoured', async () => {+ const b = box();+ const r = await setup(b, ['claude-code', '--dry-run', '--json'], { GBRAIN_SURFACE: 'starter' });+ expect(r.exitCode).toBe(0);+ expect(r.doc.target).toMatchObject({ transport: 'local-stdio', surface: 'starter', registration_owner: 'none', launcher: b.bin });+ expect(r.doc.steps.find((s: any) => s.step === 'brain').detail).toContain('--no-embedding');+ expect(existsSync(claudeJson(b))).toBe(false);+ expect(existsSync(join(b.gbrainHome, '.gbrain'))).toBe(false);+ }, 60_000);++ test('a hosted connection never falls back to a new local brain', async () => {+ const thin = box();+ mkdirSync(join(thin.gbrainHome, '.gbrain'));+ writeFileSync(join(thin.gbrainHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', remote_mcp: {+ issuer_url: 'https://brain.example.test', mcp_url: 'https://brain.example.test/mcp', oauth_client_id: 'client-a', oauth_client_secret: 'secret-a' } }));+ const r = await setup(thin, ['claude-code', '--json']);+ expect(r.exitCode).toBe(1);+ expect(r.doc.code).toBe('setup_hosted_connection');+ expect(r.doc.message).toContain('https://brain.example.test/mcp');+ expect(existsSync(join(thin.gbrainHome, '.gbrain', 'brain.pglite'))).toBe(false);+ expect(existsSync(claudeJson(thin))).toBe(false);++ const wired = box();+ const hostedCfg = JSON.stringify({ mcpServers: { gbrain: { type: 'http', url: 'https://brain.example.test/mcp', headers: { Authorization: 'Bearer x' } } } });+ writeFileSync(claudeJson(wired), hostedCfg);+ writeFileSync(receipt(wired), JSON.stringify({ client_id: 'client-a', mcp_url: 'https://brain.example.test/mcp', status: 'installed', harness: 'claude-code' }));+ const w = await setup(wired, ['claude-code', '--json']);+ expect(w.exitCode).toBe(1);+ expect(w.doc.code).toBe('setup_hosted_connection');+ expect(readFileSync(claudeJson(wired), 'utf8')).toBe(hostedCfg);+ expect(existsSync(join(wired.gbrainHome, '.gbrain'))).toBe(false);+ }, 60_000);++ test('a live PGLite owner that this setup did not register is an owner conflict; setup writes nothing', async () => {+ const b = box();+ const init = await runCli(['init', '--pglite', '--no-embedding'], { home: b.home });+ expect(init.exitCode).toBe(0);+ const serve = Bun.spawn([process.execPath, '--no-env-file', CLI, 'serve'], {+ env: { ...process.env, HOME: b.home, GBRAIN_HOME: b.gbrainHome, GBRAIN_SKIP_STARTUP_HOOKS: '1', DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },+ stdin: 'pipe', stdout: 'pipe', stderr: 'pipe',+ });+ try {+ const lockFile = join(b.gbrainHome, '.gbrain', 'brain.pglite', '.gbrain-lock', 'lock');+ for (let i = 0; i < 300 && !existsSync(lockFile); i++) await Bun.sleep(50);+ expect(existsSync(lockFile)).toBe(true);+ const r = await setup(b, ['claude-code', '--json']);+ expect(r.exitCode).toBe(1);+ expect(r.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'live_serve' });+ expect(r.doc.fix.argv).toEqual(['kill', String(serve.pid)]);+ expect(existsSync(claudeJson(b))).toBe(false);+ expect(existsSync(receipt(b))).toBe(false);+ } finally {+ serve.kill();+ await serve.exited;+ }+ }, 60_000);++ test('a live stdio serve started by this setup\'s own registration is reused, not a conflict', async () => {+ const b = box();+ expect((await setup(b, ['claude-code'])).exitCode).toBe(0);+ const entry = readJson(claudeJson(b)).mcpServers.gbrain;+ const serve = Bun.spawn([entry.command, ...entry.args], {+ env: { ...process.env, ...entry.env, HOME: b.home, GBRAIN_SKIP_STARTUP_HOOKS: '1', DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },+ stdin: 'pipe', stdout: 'pipe', stderr: 'pipe',+ });+ try {+ const lockFile = join(b.gbrainHome, '.gbrain', 'brain.pglite', '.gbrain-lock', 'lock');+ for (let i = 0; i < 300 && !existsSync(lockFile); i++) await Bun.sleep(50);+ const r = await setup(b, ['claude-code', '--json']);+ expect(r.exitCode).toBe(0);+ expect(r.doc.target.live_owner).toMatchObject({ pid: serve.pid, transport: 'stdio', ours: true });+ expect(r.doc.verify.reason).toBe('wired_running');+ } finally {+ serve.kill();+ await serve.exited;+ }+ }, 60_000);+});++describe('gbrain setup: consent and refusals', () => {+ test('provider keys present + capture declined + an existing opt-out: no capture hooks, 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, ['claude-code', '--no-capture', '--json'], providerEnv);+ expect(r.exitCode).toBe(0);+ expect(r.doc.consent.capture).toMatchObject({ value: 'declined', source: 'flag' });+ expect(readJson(join(fresh.gbrainHome, '.gbrain', 'config.json')).embedding_disabled).toBe(true);+ expect(entries(fresh, 'Stop')).toEqual([]);+ expect(entries(fresh, 'SessionEnd')).toEqual([]);++ 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, ['claude-code', '--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(settings(optedOut)).hooks).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);+ expect(seen.filter((l) => /openai|anthropic|voyage|googleapis|\/v1\//i.test(l))).toEqual([]);+ } finally {+ recorder.close();+ }+ }, 60_000);++ test('--capture, accepted and not opted out, adds Stop and SessionEnd; --no-hooks then removes every owned hook', async () => {+ const b = box();+ const r = await setup(b, ['claude-code', '--capture', '--json']);+ expect(r.exitCode).toBe(0);+ expect(Object.keys(readJson(settings(b)).hooks).sort()).toEqual(['SessionEnd', 'SessionStart', 'Stop', 'UserPromptSubmit']);+ const off = await setup(b, ['claude-code', '--no-hooks', '--json']);+ expect(off.exitCode).toBe(0);+ expect(readJson(settings(b)).hooks ?? {}).toEqual({});+ expect(readJson(claudeJson(b)).mcpServers.gbrain).toBeDefined();+ }, 60_000);++ for (const [harness, guide] of [['codex', 'docs/mcp/CODEX.md'], ['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']);+ expect(r.exitCode).toBe(2);+ expect(r.doc.code).toBe('setup_harness_unsupported');+ expect(r.doc.message).toContain(guide);+ expect(existsSync(claudeJson(b))).toBe(false);+ }, 30_000);+ }+});++describe('hooks.ts ownership: hash-keyed for setup, marker-keyed for bootstrap (unchanged)', () => {+ const env = { GBRAIN_SOURCE: 'default' };+ function editedFile(): string {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-hooks-own-'));+ roots.push(dir);+ const path = join(dir, 'settings.json');+ writeClaudeHooksAt(path, { gbrainBin: '/usr/local/bin/gbrain', env, events: ['SessionStart'] });+ const s = readJson(path);+ s.hooks.SessionStart[0].hooks[0].command += ' --edited';+ writeFileSync(path, JSON.stringify(s));+ return path;+ }++ test('without ownedEntryHashes a marked entry is removed even when edited (bootstrap lanes keep their behavior)', () => {+ const path = editedFile();+ const r = removeClaudeHooksAt(path, GBRAIN_HOOK_MARKER_VALUE);+ expect(r.removed).toBe(1);+ expect(readJson(path).hooks).toBeUndefined();+ });++ test('with ownedEntryHashes an edited marked entry survives removal and rewrite, and is reported', () => {+ const path = editedFile();+ const before = readJson(path).hooks.SessionStart[0].hooks[0];+ const r = removeClaudeHooksAt(path, GBRAIN_HOOK_MARKER_VALUE, { ownedEntryHashes: new Set(['not-this-one']) });+ expect(r.removed).toBe(0);+ expect(r.preserved).toEqual([{ event: 'SessionStart', hash: hookEntryHash(before)! }]);+ const w = writeClaudeHooksAt(path, { gbrainBin: '/usr/local/bin/gbrain', env, events: ['UserPromptSubmit'], ownedEntryHashes: new Set() });+ expect(w.preserved).toHaveLength(1);+ expect(readJson(path).hooks.SessionStart[0].hooks[0]).toEqual(before);+ });++ test('hookEntryHash ignores the marker key and changes with the command or timeout', () => {+ const base = { type: 'command', command: 'env A=1 /bin/gbrain hook session-start', timeout: 5 };+ expect(hookEntryHash({ ...base, _gbrain: 'setup-v1' })).toBe(hookEntryHash(base));+ expect(hookEntryHash({ ...base, timeout: 6 })).not.toBe(hookEntryHash(base));+ expect(hookEntryHash({ ...base, command: `${base.command} x` })).not.toBe(hookEntryHash(base));+ expect(hookEntryHash({ type: 'other' })).toBeNull();+ });+});