Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(bootstrap): harness hooks that lost their _gbrain marker are still ours (#6092, #6171)

garrytan10bb219608d6
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.md
index f570504435..ccc50e0ac5 100644
--- a/docs/architecture/key-files/agent-bootstrap.md
+++ b/docs/architecture/key-files/agent-bootstrap.md
@@ -16,7 +16,8 @@ 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`.
+- `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/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 or unmarked, any install) and `harnessHookCarrierStatus` (`--status` text line + `hook_carriers` JSON).
- `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.
@@ -24,7 +25,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/bootstrap/serve-health.ts` — serve `/health` probe + scopes version-skew floor, re-exported by `harness.ts`. `probeServeHealth(mcpUrl, fetchFn, timeoutMs=3000)` GETs `<base>/health` and returns `{ok, version?, engine?, detail?}`, never throws; `fetchFn` is an explicit argument (no ambient fetch, no engine, no config). `isServeOlderThanScopes(v)` compares against the PINNED `SCOPES_MIN_SERVE_VERSION` constant — a comparison against the moving CLI VERSION would false-flag every scope-aware serve on the next release. An older serve verifies scoped tokens as FULL ACCESS, so callers print the floor line unconditionally.
- `src/core/bootstrap/opencode-json.ts` — the ONE direct opencode-config writer (workspace stdio lane, harness remote lane, connect `--install`). ALL edits ride jsonc-parser `modify`/`applyEdits` (comments/formatting/EOLs survive byte-for-byte outside the edited range — opencode's own `mcp add` preserves comments, and JSONC is its effective grammar for BOTH `.json` and `.jsonc` filenames, which MERGE when both exist). Ownership is a 4-state STRUCTURAL FINGERPRINT (`opencodeEntryKind` → ours-same-source | ours-other-source | foreign | absent; GBRAIN_SOURCE EQUALITY for local entries, receipt-url match or the `{env:GBRAIN_REMOTE_TOKEN}` interpolation for remote), never a marker key (a future strict-schema flip must not brick the host). Distinct read-failure classes (ENOENT create / empty-as-{} / unreadable refuse); foreign refusal on write AND remove; post-render validation (our entry round-trips + every other key survives) keeps the original on failure; 0600 for inline-bearer targets; backups are UNIQUE per operation (`<config>.bak-<hex>`, returned in the result with `writtenText`, the exact rendered bytes) so overlapping runs can never clobber each other's snapshot, and a backup is chmod'd 0600 whenever the COPIED content carries an inline bearer (write AND remove paths); the ours-other-source refusal is caller-appropriate (url + `--force` wording on the remote/expect-url path, GBRAIN_SOURCE wording on the local path); `removeOpencodeMcpEntry` takes a caller expectation + optional `skipOtherSource` — the uninstall lane passes THIS workspace's source id so an ours-other-source match becomes a calm skip-with-note (another workspace's registration is never deleted; foreign still refuses); `reconcileOpencodeSiblingGlobal` clears a same-name gbrain entry from the OTHER global filename before a global write (foreign → refuse naming both files) — opencode merges both, so a leftover sibling entry is a shadow registration; the bun-run ownership lane is ANCHORED (an exact `gbrain`/`gbrain-*` path segment in some arg — a gbrainy-fork cli path is NOT ours, fail-closed); `parseOpencodeEntryBearer` recovers the harness `--status` token url-matched only; `opencodeRemoteEntryExists` is the stdio-lane ownership arbiter (codexBlockOwnsName analog). Callers hold `acquireBootstrapLock` (config-dir → opencode-dir ordering). Pinned by `test/opencode-json.test.ts` (incl. the fingerprint truth-table suite).
- `src/core/bootstrap/atomic-write.ts` — the ONE atomic config-file writer for bootstrap host surfaces: symlink-target-resolving, mode-inheriting (`freshMode` for new files, `forceMode` for secret-bearing targets), random-suffix tmp + rename, tmp unlinked best-effort when write/chmod/rename throws (ENOSPC/EACCES never strand `.tmp-` litter), and the existsSync→realpathSync race falls back to fresh-path resolution instead of throwing raw ENOENT. hooks.ts (JSON), codex-toml.ts (TOML+EOL), and opencode-json.ts (JSONC) all swap through it; serialization and EOL policy stay caller-side.
-- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). An explicit private posture (file-plane `memory.visibility_posture`) prints a pre-consent WARNING outside registrar mode: the wired HTTP sessions read world facts only, so they cannot read back what they save as private. Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath), then `requireConsent` via `consentGate` (effects `persistent_install`, plus `credentials` when it mints the token; `--yes` approves; the TTY prompt runs only when `isInteractive()`, and EOF/decline or no human at the terminal writes nothing and exits 3 with the consent payload, whose argv never repeats `--token`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`. The production mint (`mintHarnessToken`, exported) rotates each host's token from the token it replaces via `carryLegacyGrant`. `--refresh-skills` (`src/core/bootstrap/harness-skills.ts`, `refreshHarnessSkills`) re-joins each live shared-skills entry under its recorded credential so the receipt and native router adopt the server's current enrollment epoch, with no token rotation; `localEnrollment` reads the adapter receipt epoch for `--status`, and `supersededEnrollments` is doctor's read-only comparison against `shared_skill_members` (`bootstrap_harness_health` warn, code `shared_skills_epoch_superseded`). Pinned by `test/harness-skills-epoch.test.ts`.
+- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). An explicit private posture (file-plane `memory.visibility_posture`) prints a pre-consent WARNING outside registrar mode: the wired HTTP sessions read world facts only, so they cannot read back what they save as private. Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath), then `requireConsent` via `consentGate` (effects `persistent_install`, plus `credentials` when it mints the token; `--yes` approves; the TTY prompt runs only when `isInteractive()`, and EOF/decline or no human at the terminal writes nothing and exits 3 with the consent payload, whose argv never repeats `--token`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve; it removes hook entries that lost their marker when their command is this install's (`harness-hooks.ts`), keeps the hooks target failed on an unowned lookalike, and `--remove --dry-run` previews without a lock or any write. Hooks targets record `launcher` and `seat` on the receipt (the ownership identity for later runs); the permission target carries `mechanism: 'added'` forward from a prior confirmed receipt target so a re-run never relabels its own `mcp__<name>` as pre-existing, and the failed-smoke rollback removes only an entry added this run. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`. The production mint (`mintHarnessToken`, exported) rotates each host's token from the token it replaces via `carryLegacyGrant`. `--refresh-skills` (`src/core/bootstrap/harness-skills.ts`, `refreshHarnessSkills`) re-joins each live shared-skills entry under its recorded credential so the receipt and native router adopt the server's current enrollment epoch, with no token rotation; `localEnrollment` reads the adapter receipt epoch for `--status`, and `supersededEnrollments` is doctor's read-only comparison against `shared_skill_members` (`bootstrap_harness_health` warn, code `shared_skills_epoch_superseded`). Pinned by `test/harness-skills-epoch.test.ts`.
- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor, `[]` stored as the explicit no-source grant; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). `carryLegacyGrant` + `readActiveTokenPermissions` are the harness rotation carry-over: takes holders and the source grant carry as stored (explicit empty lists included; an explicit `--source` wins), a stored operation snapshot narrows to the run's snapshot plus only skills-policy-added operations, and newer operations are reported as withheld (pinned by `test/harness-rotation-grants.test.ts`). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`. `insertUnifiedToken` (shared with `auth create`) births every token on the unified grant columns at revision 1 plus the `permissions` mirror; a brain whose schema predates the columns refuses with `migrations_pending` (fix: `gbrain apply-migrations --yes`) and nothing is written; `carryLegacyGrant` parses the prior grant from its JSONB through `tokenGrantFromPermissions`, so a drifted prior carries its JSON edit (the `--adopt-permissions` resolution).
- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune via `gcCorpusTurnFiles`: an extracted `.txt` goes at `corpus_retention_days`, one with no `.ingested` sidecar only at `CORPUS_UNINGESTED_RETENTION_FACTOR` (3) times that, E-N1, pinned by `test/corpus-retention-uningested.serial.test.ts`; an assistant-only whole-file parse heartbeats `degraded`/`no_user_turns`, E-N4; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`. Seat identity (#4618): session-end (before any corpus write of the session), compact (before `bankCompactSegment`) and the stop hook's writeback bank (before `bankWritebackTurn`) record `<sessionId>.seat.json` through `context/seat.ts` — `GBRAIN_SEAT` when valid, else the hashed harness-home seat; `seat_label_invalid`, `seat_conflict` (first seat kept) and `seat_write_failed` are heartbeat reasons with a fixed `hint` (session-end applies them last, like the deferred reasons). `gcCorpusArtifacts` reaps a seat sidecar once no `.txt` of its session remains, after a 10-minute grace. Pinned by `test/session-seat-capture.serial.test.ts`.
- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). Both the hook-tail and full-session parsers skip root `isSidechain`, `isMeta`, or `isCompactSummary` exactly `true`; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string root `origin.kind` other than `'human'` is excluded; missing, empty, or unstructured origins stay compatible, without guessing from message text. Assistant text and non-text placeholders remain eligible, while skipped metadata entries also contribute no collected tool calls. `test/claude-code-jsonl-origin.test.ts` uses synthetic fixtures, not new live-harness validation. `genuineUserTurnIndexes` separately records accepted user-role turns containing real text blocks (harness tags and paste blocks removed first), because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index fe5dc9514c..ad219064b6 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -41,7 +41,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
-- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped).
+- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped).
- `src/commands/doctor/checks/default-source-path.ts` — the gathering wrapper on the doctor surface: reads the `default` sources row, page counts (live + file-backed), `sync.repo_path` resolution, and the leak-guard collision, then delegates the verdict to `assessDefaultSourcePath`. Only gathers the fallback-topology inputs when the pointer is actually null; returns null for the skip verdict.
diff --git a/docs/guides/bootstrap.md b/docs/guides/bootstrap.md
index 37351f0f41..448221d9fe 100644
--- a/docs/guides/bootstrap.md
+++ b/docs/guides/bootstrap.md
@@ -281,6 +281,21 @@ mode wires them in one command, with no `agent.json` and no interview:
and run even while a serve is live; the token revoke defers with exact
instructions if a live PGLite serve holds the brain. `gbrain bootstrap
uninstall` removes harness wiring first, automatically.
+ `gbrain bootstrap harness --remove --dry-run` lists what removal would do
+ (including each unmarked hook entry it would delete) and writes nothing.
+- Hook ownership survives a missing marker. Claude Code can drop keys it does
+ not know (the `_gbrain` marker) when it rewrites `settings.json`, so the
+ marker is advisory there and the command is the durable carrier. An entry
+ without the marker is this install's when its command is exactly the
+ harness hook gbrain writes for that event (`env … GBRAIN_HOOK_LANE=harness
+ <launcher> hook <event>`, nothing before or after) and its launcher, source
+ and seat match the running install or what the harness receipt recorded.
+ Re-running the install replaces such entries (one entry per event, never a
+ second set), and `--remove` deletes them, listing each by event and why it
+ matched. Anything else that merely looks like a harness hook is left alone
+ (see `harness_hook_unowned` below). `bootstrap_harness_health` in
+ `gbrain doctor` reads each receipt-named hook file: unmarked entries alone
+ are an `ok` note, duplicated events warn `harness_hook_duplicates`.
- Everything is stated before it happens; non-interactive runs require
`--yes`. Close active Claude Code sessions for the cleanest user-scope
settings writes (the host also writes that file).
@@ -298,6 +313,28 @@ verify path never reads the scopes column). If you
downgrade after a harness install, revoke the scoped tokens first
(`gbrain auth revoke` with the id flag) and re-mint once you upgrade again.
+### harness_hook_unowned
+
+An entry under an event gbrain wires looks like gbrain's harness hook but is
+not this install's exact command: it was edited (an appended pipe or flag), or
+another install or launcher wrote it. gbrain never deletes it. `--remove`
+removes everything it does own, keeps the hooks target failed on the receipt,
+exits 1 and prints the file and event; it does not report the harness as
+removed while that entry remains. If the entry is a leftover, delete it from
+the named file by hand and run `gbrain bootstrap harness --remove` again; keep
+it only if you added it on purpose. `gbrain bootstrap harness --status` shows
+each hook file and the events holding such entries. Doctor reports the same
+finding as a warning on `bootstrap_harness_health`.
+
+### harness_hook_duplicates
+
+One event in a harness hook file is wired more than once by this install
+(marked or unmarked entries), so the hook fires twice per event. It is left
+behind when an older gbrain re-ran the install after the host had dropped the
+markers. The doctor fix re-runs `gbrain bootstrap harness` with the
+install's own `--project` and `--no-capture` choices; it rewrites the hook
+entries and rotates the harness token, so ask the user first.
+
## Multi-device
Clone your agent repo on machine two and run `gbrain bootstrap attach` — it
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 5aad9b8b8f..19edddab4a 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1204,6 +1204,26 @@ More: [docs/guides/move-to-postgres.md#verify](../../docs/guides/move-to-postgre
|---|---|---|---|---|---|---|
| Source relationship reconciliation is incomplete. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |
+### harness_hook_duplicates
+
+<a id="harness_hook_duplicates"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A harness hook carrier wires one Claude Code event more than once with this install's own entries (marked or not), so the hook fires twice per event. | Claude Code can drop the `_gbrain` marker when it rewrites settings.json; installs before wave 11 then appended a second set on every re-run. | Correct the request using the message above, then retry. Run: gbrain doctor --only bootstrap_harness_health --json | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/bootstrap.md#harness_hook_duplicates](../../docs/guides/bootstrap.md#harness_hook_duplicates)
+
+### harness_hook_unowned
+
+<a id="harness_hook_unowned"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A hook entry looks like gbrain's harness hook but is not this install's exact command, so gbrain left it in place. | An unmarked entry is deleted only when its command is exactly what this install (or its receipt) wrote; an edited command or another install's launcher is never removed, and removal is not reported complete while it remains. | Correct the request using the message above, then retry. Run: gbrain bootstrap harness --status | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/bootstrap.md#harness_hook_unowned](../../docs/guides/bootstrap.md#harness_hook_unowned)
+
### held_out_overlaps_benchmark
<a id="held_out_overlaps_benchmark"></a>
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index d3da366183..3150a84e71 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in
src/commands/hook.ts 1924 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
src/core/config.ts 1896 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS
-src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported)
+src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 671 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose
src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part)
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index 63984f9c29..491359a64c 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -146,14 +146,14 @@ Subcommands (run \`gbrain bootstrap status\` first — it is the resume entrypoi
attach [--harness H] Machine two: adopt a cloned agent workspace.
harness [--harness claude-code|codex|opencode|all] [--url U | --port N] [--source ID]
[--token-name NAME | --token TOK] [--name MCPNAME] [--project DIR]...
- [--no-hooks] [--no-capture] [--force] [--status] [--remove] [--refresh-skills] [--yes] [--json]
+ [--no-hooks] [--no-capture] [--force] [--status] [--remove [--dry-run]] [--refresh-skills] [--yes] [--json]
[--seat <label> | --no-seat]
Wire framework-spawned Claude Code / Codex / opencode
sessions to a RUNNING \`gbrain serve --http\` on this box
(#4043): scoped bearer token, user-scope MCP + headless
pre-approval, lifecycle hooks (user scope, or per --project
dir), codex config block, opencode config entry. No
- agent.json needed. Idempotent; --remove tears it down.
+ agent.json needed. Idempotent; --remove tears it down (--dry-run previews).
--source ID: the source the hooks + token bind to
(default: sources.default, else the sole populated
non-default source, else default).
@@ -225,7 +225,7 @@ const SUBCOMMAND_HELP: Record<string, string> = {
harness:
'gbrain bootstrap harness [--harness claude-code|codex|opencode|all] [--url U | --port N] [--source ID]\n' +
' [--token-name NAME | --token TOK] [--name MCPNAME] [--project DIR]...\n' +
- ' [--no-hooks] [--no-capture] [--force] [--status] [--remove] [--yes] [--json]\n' +
+ ' [--no-hooks] [--no-capture] [--force] [--status] [--remove [--dry-run]] [--yes] [--json]\n' +
' [--seat <label> | --no-seat]\n' +
' Wire framework-spawned Claude Code / Codex / opencode sessions to a RUNNING `gbrain serve --http`\n' +
' on this box (#4043). Idempotent; --remove tears it down. (--local is an accepted no-op alias.)\n' +
@@ -1755,10 +1755,10 @@ async function runHarness(rest: string[], home: string, runner: ExecRunner, dete
prompt: promptLine,
...harnessDetectDeps(detect),
};
- // [X12] --status is READ-ONLY: no home mkdir, no lock — it must work (and
- // stay side-effect-free) even while an apply/remove holds the mutex.
- if (flags.status) {
- return statusHarness(flags, deps);
+ // [X12] --status and --remove --dry-run are READ-ONLY: no home mkdir, no
+ // lock — they must work (and stay side-effect-free) while the mutex is held.
+ if (flags.status || (flags.remove && rest.includes('--dry-run'))) {
+ return flags.status ? statusHarness(flags, deps) : removeHarness(flags, deps);
}
ensureHarnessHome(home);
return withLock(home, async () => {
diff --git a/src/commands/doctor/bootstrap-checks.ts b/src/commands/doctor/bootstrap-checks.ts
index 87e46e9287..499c5727ea 100644
--- a/src/commands/doctor/bootstrap-checks.ts
+++ b/src/commands/doctor/bootstrap-checks.ts
@@ -225,6 +225,8 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise
});
}
}
+ const { harnessHookCarrierChecks } = await import('./harness-hook-checks.ts');
+ checks.push(...harnessHookCarrierChecks(hr));
} else if (harnessState.state !== 'absent') {
checks.push({
name: 'bootstrap_harness_health',
diff --git a/src/commands/doctor/harness-hook-checks.ts b/src/commands/doctor/harness-hook-checks.ts
new file mode 100644
index 0000000000..0d4f790e06
--- /dev/null
+++ b/src/commands/doctor/harness-hook-checks.ts
@@ -0,0 +1,73 @@
+/**
+ * bootstrap_harness_health carrier rows (#6171): read each receipt-named
+ * Claude Code hook carrier (read-only) and report what the receipt alone
+ * cannot see. An event wired more than once with this install's entries
+ * (marked or unmarked) fires twice → warn `harness_hook_duplicates` with a
+ * re-run of the install's own flags. Entries the host stripped of their
+ * `_gbrain` marker are expected (Claude Code drops unknown keys when it
+ * rewrites settings.json) → an ok info row. A harness-looking entry that is
+ * not this install's → warn `harness_hook_unowned`. A carrier that does not
+ * parse → warn naming the file.
+ */
+import { harnessHookIdentity, scanHarnessHookCarrier } from '../../core/bootstrap/hooks.ts';
+import type { HarnessReceipt } from '../../core/bootstrap/format.ts';
+import { claudeUserSettingsPath } from '../../core/bootstrap/host-specs.ts';
+import { resolveGbrainBin } from '../../core/gbrain-bin.ts';
+import type { Check } from '../doctor.ts';
+import { doctorVerify } from './check-fix.ts';
+
+const NAME = 'bootstrap_harness_health';
+
+export function harnessHookCarrierChecks(hr: HarnessReceipt, launcher: string | null = resolveGbrainBin()): Check[] {
+ const checks: Check[] = [];
+ const hookTargets = hr.targets.filter((t) => t.host === 'claude-code' && t.kind === 'hooks');
+ for (const t of hookTargets) {
+ const path = t.scope === 'user' ? (t.path ?? claudeUserSettingsPath()) : t.path!;
+ const scan = scanHarnessHookCarrier(path, harnessHookIdentity(hr, t, { launcher }));
+ if (scan.state === 'unparseable') {
+ checks.push({
+ name: NAME, status: 'warn',
+ message: `the harness hook carrier ${path} is not valid JSON (${scan.error}) — Claude Code cannot run its hooks and gbrain cannot inspect them. Fix the JSON by hand, then re-run \`gbrain doctor --only ${NAME}\`.`,
+ details: { reason: 'harness_hook_carrier_unparseable', path },
+ fix_unavailable_reason: 'no_safe_automatic_fix',
+ });
+ continue;
+ }
+ const counts = Object.entries(scan.events);
+ const duplicates = counts.filter(([, c]) => c.marked + c.command > 1).map(([e]) => e);
+ const unowned = counts.filter(([, c]) => c.unowned > 0).map(([e]) => e);
+ const unmarked = counts.reduce((n, [, c]) => n + c.command, 0);
+ if (duplicates.length > 0) {
+ const projects = hookTargets.filter((h) => h.scope !== 'user').flatMap((h) => ['--project', h.scope]);
+ const capture = counts.some(([e, c]) => (e === 'Stop' || e === 'SessionEnd') && c.marked + c.command > 0);
+ checks.push({
+ name: NAME, status: 'warn',
+ message: `${duplicates.map((e) => `hooks.${e}`).join(', ')} in ${path} ${duplicates.length > 1 ? 'are' : 'is'} wired more than once by this harness install, so each fires twice per event. Re-running the install converges to one entry per event.`,
+ details: { code: 'harness_hook_duplicates', path, events: duplicates },
+ fix: {
+ argv: ['gbrain', 'bootstrap', 'harness', ...projects, ...(capture ? [] : ['--no-capture']), '--yes'],
+ consent: ['persistent_install'], actor: 'agent', requires_exclusive: false,
+ why: 'A re-run strips every entry this install owns (marked or not) and writes one per event; it also mints a fresh harness token.',
+ user_message: `gbrain's session hooks are wired twice in ${path}, so they fire twice. May I re-run \`gbrain bootstrap harness\` with the same options to clean that up? It rewrites the hook entries and rotates the harness token.`,
+ verify: doctorVerify(NAME),
+ },
+ });
+ }
+ if (unowned.length > 0) {
+ checks.push({
+ name: NAME, status: 'warn',
+ message: `${unowned.map((e) => `hooks.${e}`).join(', ')} in ${path} looks like gbrain's harness hook but is not this install's exact command (edited, or another install's launcher); gbrain leaves it alone. If it is a leftover it fires next to this install's entry — ask the user whether to delete it by hand.`,
+ details: { code: 'harness_hook_unowned', path, events: unowned },
+ fix_unavailable_reason: 'operator_judgement',
+ });
+ }
+ if (duplicates.length === 0 && unowned.length === 0 && unmarked > 0) {
+ checks.push({
+ name: NAME, status: 'ok', severity: 'info',
+ message: `${unmarked} harness hook entr${unmarked === 1 ? 'y' : 'ies'} in ${path} carry no _gbrain marker (Claude Code drops unknown keys when it rewrites settings.json); gbrain recognizes them by their exact command, so removal and re-runs still find them. Nothing to do.`,
+ details: { reason: 'harness_hook_marker_stripped', path, unmarked },
+ });
+ }
+ }
+ return checks;
+}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index cf31038418..cbd9d62042 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -262,6 +262,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.0.0-wave11', text: 'The MCP initialize instructions are reordered so harnesses that read only the first 2,048 characters (Claude Code) get the essentials: with ambient writeback on, a one-line writeback contract now sits in the memory clause (the full rules stay last), the error protocol follows the data-not-instructions clause in a shorter form, and the forget caveat moved after the scope clause.' },
{ since: '0.0.0-wave11', text: '`gbrain skillpack scaffold --harness` prints its Update lens and remove hints with the `--dest`, `--scope` and `--workspace` you passed, and `gbrain skillpack reference --harness <h>` with no slug no longer exits 2 on the shared-dependency ledger entry.' },
{ since: '0.0.0-wave11', text: 'On a managed brain, doctor `pack_upgrade_available` is now an info row with a read-only preview instead of an apply step it could not run, and `unify-types` apply switches the pack when nothing needs retyping (it still refuses, now naming the counts, when pages would change).' },
+ { since: '0.0.0-wave11', text: '`gbrain bootstrap harness --remove` now also deletes Claude Code hook entries that lost their `_gbrain` marker when their command is exactly what this install wrote, and lists each one it removed; a lookalike it did not write is left in place and removal exits 1 with `harness_hook_unowned`. Re-running the install converges to one entry per event instead of adding a second set. `gbrain bootstrap harness --remove --dry-run` previews the removal without writing anything.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/bootstrap/format.ts b/src/core/bootstrap/format.ts
index 29c6e60976..06ca5cbe65 100644
--- a/src/core/bootstrap/format.ts
+++ b/src/core/bootstrap/format.ts
@@ -247,6 +247,12 @@ export interface HarnessTarget {
entry?: string;
/** Hook marker value (hooks targets). */
marker?: string;
+ /** Absolute gbrain launcher rendered into the hook commands (hooks targets;
+ * absent on receipts written before it was recorded). */
+ launcher?: string;
+ /** Seat label rendered into the hook commands, '' for none (hooks targets;
+ * absent on older receipts). */
+ seat?: string;
/** Write mechanism note, e.g. 'toml-block' vs 'claude-cli'. */
mechanism?: string;
/** One-line failure reason when state === 'failed'. */
diff --git a/src/core/bootstrap/harness-hooks.ts b/src/core/bootstrap/harness-hooks.ts
new file mode 100644
index 0000000000..8548815daa
--- /dev/null
+++ b/src/core/bootstrap/harness-hooks.ts
@@ -0,0 +1,130 @@
+/**
+ * bootstrap/harness-hooks.ts — the harness lane's Claude Code hook entries
+ * after the host dropped their `_gbrain` marker (#6092, #6171). Claude Code
+ * rewrites settings.json through its own schema and can drop unknown keys, so
+ * an entry is this install's when it carries the marker OR its command is
+ * exactly the harness hook this install (or its receipt) rendered
+ * (hooks.ts classifyHarnessHook). This module holds the receipt-aware glue
+ * harness.ts calls: removal of one hooks target (with the `--dry-run`
+ * preview), the `harness_hook_unowned` notice, the cross-HOME `--project`
+ * guard probe and the `--status` carrier census.
+ */
+import { cliRenderContext, noticeBlock, renderNotice } from '../agent-output.ts';
+import type { HarnessReceipt, HarnessTarget } from './format.ts';
+import { GBRAIN_HARNESS_MARKER_VALUE } from './host-specs.ts';
+import { harnessHookIdentity, removeClaudeHooksAt, scanHarnessHookCarrier } from './hooks.ts';
+
+interface HookDeps {
+ userSettingsPath: string;
+ gbrainBin: string | null;
+ log: (line: string) => void;
+ logError: (line: string) => void;
+}
+
+const STATUS_ARGV = ['gbrain', 'bootstrap', 'harness', '--status'];
+
+function carrierPath(t: HarnessTarget, d: Pick<HookDeps, 'userSettingsPath'>): string {
+ return t.scope === 'user' ? (t.path ?? d.userSettingsPath) : t.path!;
+}
+
+/** The agent-first block for harness-looking entries gbrain would not delete. */
+export function harnessHookUnownedNotice(settingsPath: string, events: string[]): string {
+ const where = events.map((e) => `hooks.${e}`).join(', ');
+ const rendered = renderNotice({
+ code: 'harness_hook_unowned',
+ kind: 'safety',
+ why: `${where} in ${settingsPath} looks like gbrain's harness hook but is not this install's exact command ` +
+ '(edited, or written by another install or launcher), so gbrain left it in place and does not report the harness as removed.',
+ fix: {
+ argv: ['gbrain', 'bootstrap', 'harness', '--remove'],
+ consent: [],
+ actor: 'user',
+ requires_exclusive: false,
+ why: 'Only the user can say whether that entry is a leftover; once it is gone the removal completes and consumes the receipt.',
+ user_message: `Open ${settingsPath} and delete the ${where} entry that runs \`gbrain hook\` if you no longer want it ` +
+ '(keep it only if you added it on purpose), then run `gbrain bootstrap harness --remove` again.',
+ verify: { argv: STATUS_ARGV },
+ },
+ }, cliRenderContext());
+ return `${noticeBlock(rendered)}\nverify: ${STATUS_ARGV.join(' ')}`;
+}
+
+/**
+ * Remove one claude-code hooks target: marked entries plus unmarked entries
+ * whose command is this install's (receipt launcher/seat, receipt source, the
+ * running launcher). Logs each unmarked entry by event and why it matched.
+ * Throws when a harness-looking entry that is not ours survives, so the
+ * target stays failed on the receipt (`harness_hook_unowned`). `dryRun`
+ * reports the same lines and writes nothing.
+ */
+export function removeHarnessHooksTarget(t: HarnessTarget, receipt: HarnessReceipt, d: HookDeps, dryRun = false): void {
+ const settingsPath = carrierPath(t, d);
+ const r = removeClaudeHooksAt(settingsPath, t.marker ?? GBRAIN_HARNESS_MARKER_VALUE, {
+ identity: harnessHookIdentity(receipt, t, { launcher: d.gbrainBin }),
+ dryRun,
+ });
+ if (r.notes.some((n) => n.startsWith('WARNING'))) throw new Error(r.notes.join('; '));
+ const verb = dryRun ? 'would remove' : 'removed';
+ for (const u of r.unmarked) d.log(` ${verb} unmarked hooks.${u.event} entry: ${u.why}.`);
+ const entries = `${r.removed} harness hook entr${r.removed === 1 ? 'y' : 'ies'}`;
+ if (r.removed > 0) d.log(dryRun ? `would remove ${entries} from ${settingsPath}.` : `${entries} removed from ${settingsPath}.`);
+ if (r.unowned.length > 0) {
+ d.logError(harnessHookUnownedNotice(settingsPath, r.unowned));
+ throw new Error(
+ `harness_hook_unowned: ${r.unowned.map((e) => `hooks.${e}`).join(', ')} in ${settingsPath} looks like a gbrain harness hook ` +
+ 'this install did not write — left in place; delete it by hand, then re-run `gbrain bootstrap harness --remove`',
+ );
+ }
+ if (r.removed === 0) d.log(`no harness hook entries in ${settingsPath}${dryRun ? '.' : ' — counted as removed.'}`);
+}
+
+/** `gbrain bootstrap harness --remove --dry-run`: what removal would do, with
+ * the unmarked hook entries listed; nothing is written and the receipt stays. */
+export function previewHarnessRemoval(receipt: HarnessReceipt, d: HookDeps): number {
+ d.log('dry run: nothing is written; the receipt stays in place.');
+ let blocked = false;
+ for (const t of receipt.targets) {
+ if (t.host === 'claude-code' && t.kind === 'hooks') {
+ try {
+ removeHarnessHooksTarget(t, receipt, d, true);
+ } catch (e) {
+ blocked = true;
+ d.logError(`would fail ${t.host}/${t.kind}: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ continue;
+ }
+ if (t.kind === 'permission' && t.mechanism === 'pre-existing') {
+ d.log(`would leave permissions.allow entry '${t.entry}' in place (it predates the harness install).`);
+ continue;
+ }
+ d.log(`would remove ${t.host}/${t.kind}${t.name ? ` '${t.name}'` : t.entry ? ` '${t.entry}'` : ''}${t.path ? ` (${t.path})` : ''}.`);
+ }
+ if (receipt.token.minted && receipt.token.id) d.log(`would revoke the harness token (id ${receipt.token.id}).`);
+ return blocked ? 1 : 0;
+}
+
+/** True when the user-scope settings carry any harness hook entry, marked or
+ * not, from any install — `--project` wiring would double-fire next to it. */
+export function harnessHooksPresent(settingsPath: string): boolean {
+ const scan = scanHarnessHookCarrier(settingsPath, 'any');
+ return Object.values(scan.events).some((c) => c.marked + c.command > 0);
+}
+
+/** `--status` census of each receipt-named hook carrier (read-only). */
+export function harnessHookCarrierStatus(receipt: HarnessReceipt, d: Pick<HookDeps, 'userSettingsPath' | 'gbrainBin'>): Array<{
+ path: string; state: string; ours: number; unmarked: number; duplicates: string[]; unowned: string[];
+}> {
+ return receipt.targets.filter((t) => t.host === 'claude-code' && t.kind === 'hooks').map((t) => {
+ const path = carrierPath(t, d);
+ const scan = scanHarnessHookCarrier(path, harnessHookIdentity(receipt, t, { launcher: d.gbrainBin }));
+ const counts = Object.entries(scan.events);
+ return {
+ path,
+ state: scan.state,
+ ours: counts.reduce((n, [, c]) => n + c.marked + c.command, 0),
+ unmarked: counts.reduce((n, [, c]) => n + c.command, 0),
+ duplicates: counts.filter(([, c]) => c.marked + c.command > 1).map(([e]) => e),
+ unowned: counts.filter(([, c]) => c.unowned > 0).map(([e]) => e),
+ };
+ });
+}
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index 6c215d6e83..b4f8a2cd2c 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -98,6 +98,7 @@ import {
addPermissionsAllowEntry,
claudeSettingsPath,
committedHookEvents,
+ harnessHookIdentity,
parseSeatFlags,
removeClaudeHooksAt,
removePermissionsAllowEntry,
@@ -105,6 +106,7 @@ import {
type ClaudeHookEnv,
} from './hooks.ts';
import { codexPluginProvidesName } from './plugin-lanes.ts';
+import { harnessHookCarrierStatus, harnessHooksPresent, previewHarnessRemoval, removeHarnessHooksTarget } from './harness-hooks.ts';
import {
CLAUDE_HOOK_EVENTS,
CODEX_TOML_BLOCK_BEGIN,
@@ -158,6 +160,8 @@ export interface HarnessFlags {
noCapture: boolean;
force: boolean;
remove: boolean;
+ /** `--remove --dry-run`: list what removal would do, write nothing. */
+ dryRun?: boolean;
status: boolean;
refreshSkills: boolean;
yes: boolean;
@@ -262,6 +266,7 @@ export function parseHarnessArgs(rest: string[]): HarnessFlags {
out.noCapture = rest.includes('--no-capture');
out.force = rest.includes('--force');
out.remove = rest.includes('--remove');
+ out.dryRun = rest.includes('--dry-run');
out.status = rest.includes('--status');
out.refreshSkills = rest.includes('--refresh-skills');
out.yes = rest.includes('--yes');
@@ -279,6 +284,7 @@ export function parseHarnessArgs(rest: string[]): HarnessFlags {
out.error = out.error ?? 'pass --status OR --remove, not both';
}
if (out.refreshSkills && (out.status || out.remove)) out.error = out.error ?? 'pass --refresh-skills alone, not with --status or --remove';
+ if (out.dryRun && !out.remove) out.error = out.error ?? '--dry-run previews --remove only: pass `--remove --dry-run`';
// --user-hooks and --local are accepted, documented no-ops (script clarity).
// Unknown/typo'd flags never reach this parser through the CLI: cli.ts
// validates argv against CLI_FLAG_REGISTRY pre-dispatch and rejects them
@@ -697,7 +703,9 @@ async function cleanupStalePriorTargets(
if (r.removed) d.log(`stale ambient-writeback block removed from ${pt.path} (no longer planned).`);
}
} else if (pt.host === 'claude-code' && pt.kind === 'hooks') {
- const r = removeClaudeHooksAt(pt.path ?? d.userSettingsPath, pt.marker ?? GBRAIN_HARNESS_MARKER_VALUE);
+ const r = removeClaudeHooksAt(pt.path ?? d.userSettingsPath, pt.marker ?? GBRAIN_HARNESS_MARKER_VALUE, {
+ identity: harnessHookIdentity(prior, pt, { launcher: d.gbrainBin }),
+ });
if (r.notes.some((n) => n.startsWith('WARNING'))) throw new Error(r.notes.join('; '));
if (r.removed > 0) d.log(`stale harness hooks unwired from ${r.settingsPath} (no longer planned).`);
} else if (pt.host === 'claude-code' && pt.kind === 'permission') {
@@ -1029,20 +1037,15 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
// knowable, so scan it. (The reverse — user-scope wiring vs some other
// home's --project dirs — is not enumerable; the receipt check plus the
// same-file writer refusal are the guards there.)
- if (flags.projects.length > 0 && !flags.noHooks && existsSync(d.userSettingsPath)) {
- try {
- const raw = readFileSync(d.userSettingsPath, 'utf8');
- if (raw.includes(`"${GBRAIN_HARNESS_MARKER_VALUE}"`)) {
- d.logError(
- `user-scope harness hooks already exist in ${d.userSettingsPath} (possibly from another GBRAIN_HOME's ` +
- 'install); --project wiring would double-fire every event. Remove that install first ' +
- '(`gbrain bootstrap harness --remove` under its home).',
- );
- return 2;
- }
- } catch {
- /* unreadable → the writers' own fail-closed paths handle it */
- }
+ // Marked or not (the host may drop the marker): an unreadable file falls
+ // through to the writers' own fail-closed paths.
+ if (flags.projects.length > 0 && !flags.noHooks && harnessHooksPresent(d.userSettingsPath)) {
+ d.logError(
+ `user-scope harness hooks already exist in ${d.userSettingsPath} (possibly from another GBRAIN_HOME's ` +
+ 'install); --project wiring would double-fire every event. Remove that install first ' +
+ '(`gbrain bootstrap harness --remove` under its home).',
+ );
+ return 2;
}
// 4. Plan targets + WRITE-AHEAD receipt [F1/X6] — BEFORE the mint, so a
@@ -1118,6 +1121,10 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
const targets: HarnessTarget[] = [];
if (wireClaude) {
targets.push({ host: 'claude-code', kind: 'mcp', state: 'pending', scope: 'user', name: flags.name, mechanism: 'claude-cli' });
+ // A re-run finds its own earlier entry already allowed: ownership carries
+ // from the prior receipt (a legacy confirmed target without a mechanism
+ // is ours) so it is never relabeled pre-existing.
+ const priorPerm = prior?.targets.find((t) => t.kind === 'permission' && t.path === d.userSettingsPath && t.entry === mcpPermissionEntry(flags.name));
targets.push({
host: 'claude-code',
kind: 'permission',
@@ -1125,6 +1132,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
scope: 'user',
path: d.userSettingsPath,
entry: mcpPermissionEntry(flags.name),
+ ...(priorPerm?.state === 'confirmed' && priorPerm.mechanism !== 'pre-existing' ? { mechanism: 'added' } : {}),
});
if (wireHooks) {
if (flags.projects.length > 0) {
@@ -1293,6 +1301,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
// the codex .bak from THIS run — a failed apply restores a working state
// (the old token is still valid; mint-first means nothing was revoked yet).
let oldClaudeReg: { url: string; token: string } | null = null;
+ let permissionAddedThisRun = false;
let claudeReplaced = false;
let codexRollback: { path: string; backupPath: string | null; replacedPrior: boolean } | null = null;
let opencodeRollback: {
@@ -1378,13 +1387,18 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
}
const r = addPermissionsAllowEntry(t.path!, t.entry!);
for (const note of r.notes) d.logError(note);
- if (r.added === false) {
+ permissionAddedThisRun = r.added === true;
+ if (r.added === false && t.mechanism === 'added') {
+ confirm(t);
+ d.log(`headless pre-approval: '${t.entry}' already in permissions.allow from the previous harness install.`);
+ } else if (r.added === false) {
// [X8] Already allowed before us — record it as pre-existing so
// removal never deletes what we didn't add.
t.mechanism = 'pre-existing';
confirm(t);
d.log(`headless pre-approval: '${t.entry}' was already allowed (pre-existing — remove will leave it).`);
} else {
+ t.mechanism = 'added';
confirm(t);
d.log(`headless pre-approval: '${t.entry}' in permissions.allow (${t.path})`);
}
@@ -1431,6 +1445,8 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
marker: GBRAIN_HARNESS_MARKER_VALUE,
backupStrategy: 'timestamped',
refuseOnForeignGbrainMarker: true,
+ identity: harnessHookIdentity(prior, prior?.targets.find((p) => p.kind === 'hooks' && p.path === t.path),
+ { launcher: bin, source: hookSource, seat: flags.seat }),
...(t.scope === 'user'
? { freshMode: 0o600 }
: // [D12] a --project dir whose COMMITTED settings carry workspace
@@ -1439,6 +1455,8 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
{ carriedEvents: committedHookEvents(dirname(dirname(t.path!))) }),
});
for (const note of r.notes) d.logError(note);
+ t.launcher = bin;
+ t.seat = r.seat;
confirm(t);
d.log(
`hooks wired (${r.installed.length} event(s)${flags.noCapture ? ', capture off' : ''}) in ${r.settingsPath}`,
@@ -1761,7 +1779,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
// registration (red-team CRITICAL): remove the entry we added this run.
// Pre-existing entries [X8] are never touched.
const pt = targets.find((t) => t.host === 'claude-code' && t.kind === 'permission');
- if (pt?.state === 'confirmed' && pt.mechanism !== 'pre-existing') {
+ if (pt?.state === 'confirmed' && permissionAddedThisRun) {
try {
removePermissionsAllowEntry(pt.path!, pt.entry!);
failTarget(pt, 'pre-approval removed after the failed smoke (its registration was rolled back)');
@@ -2045,6 +2063,7 @@ export async function removeHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
return 1;
}
const receipt = state.receipt;
+ if (flags.dryRun) return previewHarnessRemoval(receipt, { ...d, gbrainBin: flags.gbrainBin ?? d.gbrainBin });
const save = () => writeHarnessReceipt(d.gbrainHome, receipt);
let anyFailed = false;
let skillsDone = true;
@@ -2130,14 +2149,7 @@ export async function removeHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
: `permissions.allow entry '${t.entry}' already gone — counted as removed.`,
);
} else if (t.host === 'claude-code' && t.kind === 'hooks') {
- const settingsPath = t.scope === 'user' ? (t.path ?? d.userSettingsPath) : t.path!;
- const r = removeClaudeHooksAt(settingsPath, t.marker ?? GBRAIN_HARNESS_MARKER_VALUE);
- if (r.notes.some((n) => n.startsWith('WARNING'))) throw new Error(r.notes.join('; '));
- d.log(
- r.removed > 0
- ? `${r.removed} harness hook entr${r.removed === 1 ? 'y' : 'ies'} removed from ${settingsPath}.`
- : `no harness hook entries in ${settingsPath} — counted as removed.`,
- );
+ removeHarnessHooksTarget(t, receipt, { ...d, gbrainBin: flags.gbrainBin ?? d.gbrainBin });
} else if (t.host === 'codex') {
const codexPath = t.path ?? d.codexConfig;
const codexDir = dirname(codexPath);
@@ -2479,6 +2491,7 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
return { host: t.host, path: t.path ?? null, probe };
});
const instructionsOk = instructionsProbes.every((p) => p.probe === 'installed');
+ const hookCarriers = harnessHookCarrierStatus(receipt, d);
if (flags.json) {
d.log(
@@ -2499,6 +2512,7 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
degraded_per_turn: degraded,
targets: liveTargets,
...(instructionsProbes.length > 0 ? { instructions_blocks: instructionsProbes } : {}),
+ ...(hookCarriers.length > 0 ? { hook_carriers: hookCarriers } : {}),
pending_previous_tokens: receipt.token.previous_ids ?? [],
receipt_path: harnessReceiptPath(d.gbrainHome),
},
@@ -2525,6 +2539,10 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
: ''),
);
}
+ for (const c of hookCarriers) {
+ d.log(` hook entries in ${c.path}: ${c.state === 'ok' ? `${c.ours} gbrain (${c.unmarked} without the _gbrain marker)` : c.state}` +
+ `${c.duplicates.length ? `; duplicated: ${c.duplicates.join(', ')}` : ''}${c.unowned.length ? `; not this install's (left in place): ${c.unowned.join(', ')}` : ''}`);
+ }
if (receipt.token.previous_ids?.length) {
d.log(` pending: ${receipt.token.previous_ids.length} previous token(s) await revocation (re-run to converge): ${receipt.token.previous_ids.join(', ')}`);
}
diff --git a/src/core/bootstrap/hooks.ts b/src/core/bootstrap/hooks.ts
index 48473e9a3f..a1b7831c87 100644
--- a/src/core/bootstrap/hooks.ts
+++ b/src/core/bootstrap/hooks.ts
@@ -31,12 +31,14 @@ import { normalizeSeatLabel } from '../context/seat.ts';
import { detectExecutionEnvironment } from '../execution-env.ts';
import { stdioServeArgv } from '../mcp-registration.ts';
import type { McpSurface } from '../../mcp/surface.ts';
+import type { HarnessReceipt, HarnessTarget } from './format.ts';
import {
CLAUDE_COMMITTED_SETTINGS_FILE_RELPATH,
CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS,
CLAUDE_HOOK_EVENTS,
CLAUDE_HOOK_SUBCOMMAND,
CLAUDE_SETTINGS_FILE_RELPATH,
+ GBRAIN_HARNESS_MARKER_VALUE,
GBRAIN_HOOK_MARKER_KEY,
GBRAIN_HOOK_MARKER_VALUE,
type ClaudeHookEvent,
@@ -109,6 +111,12 @@ export interface WriteClaudeHooksOpts {
* Claude Code's own convention for that file [X11].
*/
freshMode?: number;
+ /**
+ * Harness lane: unmarked entries whose command is exactly this identity's
+ * harness hook are replaced like marked ones (the host can drop the marker
+ * key); harness-looking entries outside it survive and get a note.
+ */
+ identity?: HarnessHookIdentity;
}
export interface WriteClaudeHooksResult {
@@ -123,15 +131,34 @@ export interface WriteClaudeHooksResult {
* stability. */
brokenBackupPath: string | null;
notes: string[];
+ /** Seat label rendered into the new commands ('' for none). */
+ seat: string;
}
export interface RemoveClaudeHooksResult {
settingsPath: string;
+ /** Entries removed (marked plus unmarked-but-ours). */
removed: number;
backupPath: string | null;
notes: string[];
+ /** Unmarked entries removed because their command is this install's harness hook. */
+ unmarked: Array<{ event: string; why: string }>;
+ /** Events holding a harness-looking entry that is not this install's; never deleted. */
+ unowned: string[];
}
+/** Who may claim an UNMARKED harness hook entry: the launchers, sources and
+ * seats this install (or its harness receipt) rendered. A `null` source is an
+ * unpinned hook (no GBRAIN_SOURCE); `seats` undefined accepts any seat label
+ * (the receipt recorded none). */
+export interface HarnessHookIdentity {
+ launchers: string[];
+ sources: Array<string | null>;
+ seats?: string[];
+}
+
+export type HarnessHookOwnership = 'marked' | 'command' | 'unowned';
+
/** One command object inside a hook matcher group (host-specs shape). */
interface HookCommandEntry {
type: 'command';
@@ -164,7 +191,9 @@ function shellQuote(arg: string): string {
return `'${arg.replace(/'/g, "'\\''")}'`;
}
-/** Render the hook command string: `env K=V… <bin> hook <subcommand>`. */
+/** Render the hook command string: `env K=V… <bin> hook <subcommand>`. The
+ * harness lane recognizes its unmarked entries by parsing exactly this shape
+ * back (parseClaudeHookCommand), so the two change together. */
export function buildClaudeHookCommand(
gbrainBin: string,
event: ClaudeHookEvent,
@@ -179,6 +208,101 @@ export function buildClaudeHookCommand(
return parts.map(shellQuote).join(' ');
}
+const HOOK_ENV_KEYS: ReadonlySet<string> = new Set(['GBRAIN_SOURCE', 'GBRAIN_HOME', 'GBRAIN_HOOK_LANE', 'GBRAIN_SEAT']);
+
+/**
+ * The inverse of buildClaudeHookCommand: `env K=V… <abs bin> hook <sub>` with
+ * nothing before or after, words split the way shellQuote joins them, env keys
+ * limited to the ones the builder writes (each at most once), and a final
+ * check that re-rendering the parse yields the exact input. Null for anything
+ * else (an appended pipe, an extra flag, hand quoting, a relative launcher).
+ */
+export function parseClaudeHookCommand(command: string): { gbrainBin: string; subcommand: string; env: ClaudeHookEnv } | null {
+ const words: string[] = [];
+ const word = /([A-Za-z0-9_.:/@=-]+|'(?:[^']|'\\'')*')(?: |$)/y;
+ while (word.lastIndex < command.length) {
+ const m = word.exec(command);
+ if (!m) return null;
+ words.push(m[1]!.startsWith("'") ? m[1]!.slice(1, -1).replace(/'\\''/g, "'") : m[1]!);
+ }
+ if (words[0] !== 'env' || words.length < 4) return null;
+ const env: Record<string, string> = {};
+ let i = 1;
+ for (; i < words.length - 3; i++) {
+ const eq = words[i]!.indexOf('=');
+ if (eq < 0) break;
+ const key = words[i]!.slice(0, eq);
+ if (!HOOK_ENV_KEYS.has(key) || key in env) return null;
+ env[key] = words[i]!.slice(eq + 1);
+ }
+ const [gbrainBin, verb, subcommand] = words.slice(i) as [string, string, string];
+ if (words.length - i !== 3 || verb !== 'hook' || !isAbsolute(gbrainBin)) return null;
+ const event = CLAUDE_HOOK_EVENTS.find((e) => CLAUDE_HOOK_SUBCOMMAND[e] === subcommand);
+ if (!event || buildClaudeHookCommand(gbrainBin, event, env) !== command) return null;
+ return { gbrainBin, subcommand, env };
+}
+
+/**
+ * Harness-lane ownership of one hook entry under `event`. Claude Code drops
+ * keys it does not know when it rewrites settings.json, so the `_gbrain`
+ * marker is advisory there and the command is the durable carrier:
+ * - `marked`: the entry carries the harness marker.
+ * - `command`: no marker key, the command is exactly the harness hook this
+ * event runs, and its launcher, source and seat belong to `identity` (with
+ * no GBRAIN_HOME: the harness lane never renders one). `'any'` skips the
+ * identity check, for guards that only ask whether a harness hook exists.
+ * - `unowned`: no marker key and it looks like a harness hook (lane token +
+ * `hook`) under an event gbrain wires, but it was edited or belongs to
+ * another install. Never deleted.
+ * Null for everything else (other markers, foreign hooks, events gbrain does
+ * not wire). `why` names the match, never the command text.
+ */
+export function classifyHarnessHook(
+ entry: unknown,
+ event: string,
+ identity: HarnessHookIdentity | 'any',
+): { ownership: HarnessHookOwnership; why: string } | null {
+ if (typeof entry !== 'object' || entry === null) return null;
+ const e = entry as Record<string, unknown>;
+ if (e[GBRAIN_HOOK_MARKER_KEY] === GBRAIN_HARNESS_MARKER_VALUE) return { ownership: 'marked', why: 'carries the harness marker' };
+ if (Object.prototype.hasOwnProperty.call(e, GBRAIN_HOOK_MARKER_KEY) || typeof e.command !== 'string') return null;
+ const sub = (CLAUDE_HOOK_SUBCOMMAND as Record<string, string | undefined>)[event];
+ if (!sub || !/(?:^|[\s'])GBRAIN_HOOK_LANE=harness(?=[\s']|$)/.test(e.command) || !/\shook(?:\s|$)/.test(e.command)) return null;
+ const parsed = parseClaudeHookCommand(e.command);
+ if (!parsed || parsed.env.GBRAIN_HOOK_LANE !== 'harness' || parsed.subcommand !== sub) {
+ return { ownership: 'unowned', why: `not the exact \`hook ${sub}\` command gbrain writes (edited or extended)` };
+ }
+ if (identity === 'any') return { ownership: 'command', why: 'harness hook command shape' };
+ if (parsed.env.GBRAIN_HOME !== undefined) return { ownership: 'unowned', why: 'carries GBRAIN_HOME, which this install never writes' };
+ if (!identity.launchers.includes(parsed.gbrainBin)) return { ownership: 'unowned', why: 'its launcher is not this install\'s' };
+ const source = parsed.env.GBRAIN_SOURCE ?? null;
+ if (!identity.sources.includes(source)) return { ownership: 'unowned', why: 'its source is not this install\'s' };
+ if (identity.seats && !identity.seats.includes(parsed.env.GBRAIN_SEAT ?? '')) return { ownership: 'unowned', why: 'its seat is not this install\'s' };
+ return {
+ ownership: 'command',
+ why: `no _gbrain marker; exact \`hook ${sub}\` command with this install's launcher and ${source === null ? 'no source pin' : `source '${source}'`}`,
+ };
+}
+
+/**
+ * The identity an unmarked harness entry must match: the current install's
+ * launcher/source/seat plus what the receipt recorded for `target` (its
+ * launcher and seat) and the receipt's source binding. Seats constrain only
+ * when the receipt recorded one.
+ */
+export function harnessHookIdentity(
+ receipt: Pick<HarnessReceipt, 'source_id' | 'source_pinned'> | null,
+ target: Pick<HarnessTarget, 'launcher' | 'seat'> | undefined,
+ current: { launcher?: string | null; source?: string | null; seat?: string },
+): HarnessHookIdentity {
+ const launchers = [current.launcher, target?.launcher].filter((l): l is string => typeof l === 'string' && l !== '');
+ const sources: Array<string | null> = [];
+ if (current.source !== undefined) sources.push(current.source);
+ if (receipt) sources.push(receipt.source_pinned === false ? null : receipt.source_id);
+ if (target?.seat === undefined) return { launchers, sources };
+ return { launchers, sources, seats: [target.seat, ...(current.seat !== undefined ? [current.seat] : [])] };
+}
+
/**
* `--seat <label>` / `--no-seat` → the hook env's GBRAIN_SEAT: the validated
* label, '' to clear a carried seat, or undefined to keep the installed one.
@@ -209,17 +333,21 @@ export function parseSeatFlags(rest: string[], harness?: string): { seat?: strin
return { seat };
}
-/** The seat a prior install of `marker` rendered into this file's hook commands. */
-function installedSeat(hooks: Record<string, unknown>, marker: string): string | undefined {
- for (const groups of Object.values(hooks)) {
- if (!Array.isArray(groups)) continue;
- for (const group of groups) {
- const entries = (group as HookMatcherGroup)?.hooks;
- if (!Array.isArray(entries)) continue;
- for (const entry of entries) {
- if (!isOurs(entry, marker) || typeof (entry as HookCommandEntry).command !== 'string') continue;
- const m = /(?:^| )GBRAIN_SEAT=([a-z0-9][a-z0-9._-]{0,63})(?= )/.exec((entry as HookCommandEntry).command);
- if (m) return m[1];
+/** The seat a prior install of `marker` rendered into this file's hook
+ * commands: marked entries first, then unmarked entries `identity` owns. */
+function installedSeat(hooks: Record<string, unknown>, marker: string, identity?: HarnessHookIdentity): string | undefined {
+ for (const claim of identity ? ['marked', 'command'] : ['marked']) {
+ for (const [event, groups] of Object.entries(hooks)) {
+ if (!Array.isArray(groups)) continue;
+ for (const group of groups) {
+ const entries = (group as HookMatcherGroup)?.hooks;
+ if (!Array.isArray(entries)) continue;
+ for (const entry of entries) {
+ const ours = claim === 'marked' ? isOurs(entry, marker) : classifyHarnessHook(entry, event, identity!)?.ownership === 'command';
+ if (!ours || typeof (entry as HookCommandEntry).command !== 'string') continue;
+ const m = /(?:^| )GBRAIN_SEAT=([a-z0-9][a-z0-9._-]{0,63})(?= )/.exec((entry as HookCommandEntry).command);
+ if (m) return m[1];
+ }
}
}
}
@@ -320,9 +448,15 @@ function isForeignGbrainMarked(entry: unknown, marker: string): boolean {
* filter emptied a previously non-empty group, so it can never drop a group a
* different marker still owns.
*/
-function stripOurEntries(groups: unknown[], marker: string = GBRAIN_HOOK_MARKER_VALUE): { kept: unknown[]; removed: number } {
+function stripOurEntries(
+ groups: unknown[],
+ marker: string = GBRAIN_HOOK_MARKER_VALUE,
+ owned?: { event: string; identity: HarnessHookIdentity },
+): { kept: unknown[]; removed: number; unmarked: string[]; unowned: number } {
const kept: unknown[] = [];
let removed = 0;
+ const unmarked: string[] = [];
+ let unowned = 0;
for (const group of groups) {
if (typeof group !== 'object' || group === null || !Array.isArray((group as HookMatcherGroup).hooks)) {
kept.push(group); // structurally foreign — never touch
@@ -330,7 +464,15 @@ function stripOurEntries(groups: unknown[], marker: string = GBRAIN_HOOK_MARKER_
}
const g = group as HookMatcherGroup;
const before = g.hooks!.length;
- const filtered = g.hooks!.filter((h) => !isOurs(h, marker));
+ const filtered = g.hooks!.filter((h) => {
+ if (isOurs(h, marker)) return false;
+ if (!owned) return true;
+ const c = classifyHarnessHook(h, owned.event, owned.identity);
+ if (c?.ownership === 'unowned') unowned++;
+ if (c?.ownership !== 'command') return true;
+ unmarked.push(c.why);
+ return false;
+ });
removed += before - filtered.length;
if (filtered.length === 0 && before > 0 && filtered.length !== before) {
continue; // we emptied it → drop the husk
@@ -341,7 +483,7 @@ function stripOurEntries(groups: unknown[], marker: string = GBRAIN_HOOK_MARKER_
kept.push(group);
}
}
- return { kept, removed };
+ return { kept, removed, unmarked, unowned };
}
/**
@@ -484,7 +626,7 @@ export function writeClaudeHooksAt(
const carried = opts.carriedEvents ?? new Set<ClaudeHookEvent>();
// #4618: a re-install without --seat keeps the seat the prior install chose.
const env = opts.env.GBRAIN_SEAT === undefined
- ? { ...opts.env, GBRAIN_SEAT: installedSeat(hooks, marker) }
+ ? { ...opts.env, GBRAIN_SEAT: installedSeat(hooks, marker, opts.identity) }
: opts.env;
let removedPrior = 0;
const installed: Array<{ event: ClaudeHookEvent; command: string }> = [];
@@ -496,8 +638,14 @@ 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 } = stripOurEntries(groups, marker);
+ const { kept, removed, unowned } = stripOurEntries(groups, marker, opts.identity && { event, identity: opts.identity });
removedPrior += removed;
+ if (unowned > 0) {
+ notes.push(
+ `hooks.${event} in ${settingsPath} holds an entry that looks like gbrain's harness hook but is not this install's ` +
+ `exact command (code harness_hook_unowned); left in place — if it is a leftover it fires next to the new entry, so delete it by hand.`,
+ );
+ }
if (removed === 0) continue;
if (kept.length === 0) {
delete hooks[event]; // emptied by OUR removal — drop the key
@@ -547,7 +695,7 @@ export function writeClaudeHooksAt(
}
atomicWriteJson(settingsPath, settings, opts.freshMode);
- return { settingsPath, installed, removedPrior, backupPath, brokenBackupPath, notes };
+ return { settingsPath, installed, removedPrior, backupPath, brokenBackupPath, notes, seat: env.GBRAIN_SEAT ?? '' };
}
/**
@@ -642,7 +790,7 @@ export function writeCommittedClaudeHooks(
);
}
- return { settingsPath, installed, removedPrior, backupPath, brokenBackupPath, notes };
+ return { settingsPath, installed, removedPrior, backupPath, brokenBackupPath, notes, seat: '' };
}
/**
@@ -655,45 +803,43 @@ export function writeCommittedClaudeHooks(
export function removeClaudeHooksAt(
settingsPath: string,
marker: string = GBRAIN_HOOK_MARKER_VALUE,
+ opts: { identity?: HarnessHookIdentity; dryRun?: boolean } = {},
): RemoveClaudeHooksResult {
- const notes: string[] = [];
- if (!existsSync(settingsPath)) {
- return { settingsPath, removed: 0, backupPath: null, notes: ['no settings file — nothing to remove'] };
- }
+ const nothing = (note: string): RemoveClaudeHooksResult =>
+ ({ settingsPath, removed: 0, backupPath: null, notes: [note], unmarked: [], unowned: [] });
+ if (!existsSync(settingsPath)) return nothing('no settings file — nothing to remove');
let settings: SettingsObject;
try {
const raw = readFileSync(settingsPath, 'utf8');
- if (raw.trim() === '') {
- return { settingsPath, removed: 0, backupPath: null, notes: ['settings file empty — nothing to remove'] };
- }
+ if (raw.trim() === '') return nothing('settings file empty — nothing to remove');
const parsed = JSON.parse(raw) as unknown;
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
throw new Error('settings root is not a JSON object');
}
settings = parsed as SettingsObject;
} catch (e) {
- return {
- settingsPath,
- removed: 0,
- backupPath: null,
- notes: [
- `WARNING: ${settingsPath} is not valid JSON (${(e as Error).message}); ` +
- `left untouched — remove gbrain hook entries by hand or fix the JSON and re-run.`,
- ],
- };
+ return nothing(
+ `WARNING: ${settingsPath} is not valid JSON (${(e as Error).message}); ` +
+ `left untouched — remove gbrain hook entries by hand or fix the JSON and re-run.`,
+ );
}
const hooks = settings.hooks as Record<string, unknown> | undefined;
if (typeof hooks !== 'object' || hooks === null || Array.isArray(hooks)) {
- return { settingsPath, removed: 0, backupPath: null, notes: ['no hooks object — nothing to remove'] };
+ return nothing('no hooks object — nothing to remove');
}
let removed = 0;
+ const unmarked: Array<{ event: string; why: string }> = [];
+ const unowned: string[] = [];
for (const event of Object.keys(hooks)) {
const groups = hooks[event];
if (!Array.isArray(groups)) continue; // structurally foreign — never touch
- const { kept, removed: n } = stripOurEntries(groups, marker);
+ const strip = stripOurEntries(groups, marker, opts.identity && { event, identity: opts.identity });
+ const { kept, removed: n } = strip;
removed += n;
+ unmarked.push(...strip.unmarked.map((why) => ({ event, why })));
+ if (strip.unowned > 0) unowned.push(event);
if (n === 0) continue;
if (kept.length === 0) {
delete hooks[event]; // emptied by OUR removal — drop the key
@@ -706,12 +852,65 @@ export function removeClaudeHooksAt(
}
let backupPath: string | null = null;
- if (removed > 0) {
+ if (removed > 0 && !opts.dryRun) {
backupPath = `${settingsPath}.bak`;
copyFileSync(settingsPath, backupPath);
atomicWriteJson(settingsPath, settings);
}
- return { settingsPath, removed, backupPath, notes };
+ return { settingsPath, removed, backupPath, notes: [], unmarked, unowned };
+}
+
+/**
+ * Read-only census of one harness carrier: per wired event, how many entries
+ * are marked, unmarked-but-ours (`command`) and harness-looking but not ours
+ * (`unowned`). Doctor, `--status` and the cross-HOME `--project` guard use it;
+ * nothing is written.
+ */
+export function scanHarnessHookCarrier(
+ settingsPath: string,
+ identity: HarnessHookIdentity | 'any',
+): { state: 'absent' | 'unparseable' | 'ok'; error?: string; events: Partial<Record<ClaudeHookEvent, Record<HarnessHookOwnership, number>>> } {
+ const events: Partial<Record<ClaudeHookEvent, Record<HarnessHookOwnership, number>>> = {};
+ if (!existsSync(settingsPath)) return { state: 'absent', events };
+ let hooks: unknown;
+ try {
+ const raw = readFileSync(settingsPath, 'utf8');
+ if (raw.trim() === '') return { state: 'ok', events };
+ const parsed = JSON.parse(raw) as unknown;
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) throw new Error('settings root is not a JSON object');
+ hooks = (parsed as SettingsObject).hooks;
+ } catch (e) {
+ return { state: 'unparseable', error: (e as Error).message, events };
+ }
+ if (typeof hooks !== 'object' || hooks === null) return { state: 'ok', events };
+ for (const event of CLAUDE_HOOK_EVENTS) {
+ const groups = (hooks as Record<string, unknown>)[event];
+ if (!Array.isArray(groups)) continue;
+ for (const group of groups) {
+ const entries = (group as HookMatcherGroup)?.hooks;
+ if (!Array.isArray(entries)) continue;
+ for (const entry of entries) {
+ const c = classifyHarnessHook(entry, event, identity);
+ if (!c) continue;
+ const counts = (events[event] ??= { marked: 0, command: 0, unowned: 0 });
+ counts[c.ownership]++;
+ }
+ }
+ }
+ return { state: 'ok', events };
+}
+
+/** True when an event's matcher groups carry any gbrain hook: an entry with a
+ * `_gbrain` marker key, or an unmarked harness hook command (the host may have
+ * dropped its marker). hook_carrier_overlap counts carriers with this. */
+export function groupsCarryGbrainHook(groups: unknown, event: string): boolean {
+ if (!Array.isArray(groups)) return false;
+ return groups.some((group) => {
+ const entries = (group as HookMatcherGroup)?.hooks;
+ return Array.isArray(entries) && entries.some((entry) =>
+ (typeof entry === 'object' && entry !== null && Object.prototype.hasOwnProperty.call(entry, GBRAIN_HOOK_MARKER_KEY)) ||
+ classifyHarnessHook(entry, event, 'any')?.ownership === 'command');
+ });
}
/**
@@ -733,6 +932,8 @@ export function removeClaudeHooks(workspaceDir: string): RemoveClaudeHooksResult
removed: local.removed + committed.removed,
backupPath: local.backupPath,
notes,
+ unmarked: [],
+ unowned: [],
};
}
diff --git a/src/core/bootstrap/host-specs.ts b/src/core/bootstrap/host-specs.ts
index 985404637e..d2f24c3bc1 100644
--- a/src/core/bootstrap/host-specs.ts
+++ b/src/core/bootstrap/host-specs.ts
@@ -58,8 +58,9 @@ export const TARGETS: Record<string, HostSpecTarget> = {
'hooks: [{type:"command", command, timeout}]}] with timeout in SECONDS. ' +
'Hook commands are shell strings (no env map) — env vars are embedded via ' +
'an `env K=V …` prefix. Unknown properties on the command object are ' +
- 'tolerated by the harness, which is what makes the `_gbrain` marker key ' +
- 'safe. UserPromptSubmit context injection: stdout JSON ' +
+ 'tolerated at run time, but a host rewrite of settings.json can drop them, ' +
+ 'so the `_gbrain` marker key is advisory and the harness lane also ' +
+ 'recognizes its own exact command. UserPromptSubmit context injection: stdout JSON ' +
'{hookSpecificOutput: {hookEventName: "UserPromptSubmit", ' +
'additionalContext}}; SessionStart plain stdout becomes context. Hook ' +
'stdout is capped at 10000 chars — overflow is diverted to a file and ' +
@@ -235,6 +236,14 @@ export const GBRAIN_HOOK_MARKER_VALUE = 'bootstrap-v1';
* install (bootstrap-v1 in settings.local.json) AND a harness install
* (bootstrap-harness-v1 in user settings.json or a project settings.local.json)
* — each removal path strips only its own entries.
+ *
+ * The marker is advisory on Claude Code settings: when the host rewrites
+ * settings.json through its own schema it can drop keys it does not know,
+ * keeping only type/command/timeout. The harness lane therefore also owns an
+ * UNMARKED entry whose command is exactly the one it writes for that event
+ * and whose launcher/source/seat match the install or its receipt
+ * (hooks.ts classifyHarnessHook); the command string is the durable carrier.
+ * The workspace lane (bootstrap-v1) still keys on the marker alone.
*/
export const GBRAIN_HARNESS_MARKER_VALUE = 'bootstrap-harness-v1';
diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.ts
index 8bcd4cb20b..3f44bdace8 100644
--- a/src/core/bootstrap/verify.ts
+++ b/src/core/bootstrap/verify.ts
@@ -51,7 +51,8 @@ import {
import { shellQuote } from '../mcp-registration.ts';
import { FACTS_DEFAULT_VISIBILITY_KEY } from '../facts/visibility.ts';
import { byteFloors } from './render.ts';
-import { CLAUDE_HOOK_EVENTS, GBRAIN_HOOK_MARKER_KEY, claudeUserSettingsPath } from './host-specs.ts';
+import { CLAUDE_HOOK_EVENTS, claudeUserSettingsPath } from './host-specs.ts';
+import { groupsCarryGbrainHook } from './hooks.ts';
import { BOOTSTRAP_TEMPLATES, loadQuestionBank } from './assets.ts';
import { readManifest, writeManifest } from './format.ts';
import { status as interviewStatus } from './interview.ts';
@@ -436,7 +437,7 @@ export function checkHookCarrierOverlap(
try {
const parsed = JSON.parse(readFileSync(path, 'utf8')) as { hooks?: Record<string, unknown> };
const groups = parsed?.hooks?.[event];
- return Array.isArray(groups) && JSON.stringify(groups).includes(`"${GBRAIN_HOOK_MARKER_KEY}"`);
+ return groupsCarryGbrainHook(groups, event);
} catch {
return false;
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 3826b34f09..474eb32a99 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -24,7 +24,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
'book-mirror': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
- 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--exit-code', '--file', '--force', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--oauth-client-id', '--oauth-client-secret', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
+ 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--env', '--error-unmatch', '--exclude-standard', '--exit-code', '--file', '--force', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--oauth-client-id', '--oauth-client-secret', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--probe', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
'calibration': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -72,14 +72,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--seat', '--session', '--show-current', '--show-toplevel', '--source'],
'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--budget-ms', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--force', '--full', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--path', '--pglite', '--plan', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--yes'],
+ 'init': ['--access', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--budget-ms', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--force', '--full', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--path', '--pglite', '--plan', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-capture', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
@@ -125,7 +125,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 2929f26e3c..be97ff8ae1 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -185,6 +185,8 @@ export const CODES = {
graduation_unsupported_platform: { class: 'host_only', summary: "Moving a brain with write history to Postgres is not available on this platform yet.", docs: 'docs/guides/move-to-postgres.md#platforms' },
graduation_verify_failed: { class: 'server', summary: "The moved copy did not verify against the source; the target stays fenced and the source stays authoritative.", docs: 'docs/guides/move-to-postgres.md#verify', reasons: ['count', 'digest', 'sequence', 'fk', 'trigger', 'relation_set', 'replay', 'doctor'] },
graph_incomplete: { class: 'server', summary: "Source relationship reconciliation is incomplete." },
+ harness_hook_duplicates: { class: 'caller', summary: "A harness hook carrier wires one Claude Code event more than once with this install's own entries (marked or not), so the hook fires twice per event.", why: "Claude Code can drop the `_gbrain` marker when it rewrites settings.json; installs before wave 11 then appended a second set on every re-run.", docs: 'docs/guides/bootstrap.md#harness_hook_duplicates', fix: { argv: ['gbrain', 'doctor', '--only', 'bootstrap_harness_health', '--json'], consent: [], actor: 'agent', why: "Names the carrier, the duplicated events and the re-run (with the install's own flags) that converges them, read-only.", requires_exclusive: false } },
+ harness_hook_unowned: { class: 'caller', summary: "A hook entry looks like gbrain's harness hook but is not this install's exact command, so gbrain left it in place.", why: "An unmarked entry is deleted only when its command is exactly what this install (or its receipt) wrote; an edited command or another install's launcher is never removed, and removal is not reported complete while it remains.", docs: 'docs/guides/bootstrap.md#harness_hook_unowned', fix: { argv: ['gbrain', 'bootstrap', 'harness', '--status'], consent: [], actor: 'agent', why: 'Shows each hook carrier with the events holding entries that are not this install\'s, read-only.', requires_exclusive: false } },
held_out_overlaps_benchmark: { class: 'caller', summary: "Held out overlaps benchmark." },
held_out_required_for_bundled: { class: 'caller', summary: "Held out required for bundled." },
idempotency_conflict: { class: 'caller', summary: "The request_id already belongs to a different accepted operation." },
diff --git a/test/bootstrap-doctor-checks.test.ts b/test/bootstrap-doctor-checks.test.ts
index 31612ce97c..add649ff68 100644
--- a/test/bootstrap-doctor-checks.test.ts
+++ b/test/bootstrap-doctor-checks.test.ts
@@ -23,6 +23,8 @@ import { bootstrapDoctorChecks, type Check } from '../src/commands/doctor.ts';
import { finalizeCheckFixes } from '../src/commands/doctor/check-fix.ts';
import { readBootId, readPidNs } from '../src/core/pglite-lock.ts';
import { writeHarnessReceipt } from '../src/core/bootstrap/format.ts';
+import { buildClaudeHookCommand } from '../src/core/bootstrap/hooks.ts';
+import { GBRAIN_HARNESS_MARKER_VALUE } from '../src/core/bootstrap/host-specs.ts';
import { LATEST_VERSION } from '../src/core/migrate.ts';
import { VERSION } from '../src/version.ts';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -275,6 +277,103 @@ describe('bootstrap_harness_health (#4043)', () => {
}, T);
});
+// ── 0b. harness hook carrier rows (#6171) ──────────────────────────────────
+
+const HOOK_BIN = '/opt/fake/gbrain';
+const HOOK_ENV = { GBRAIN_SOURCE: 'default', GBRAIN_HOOK_LANE: 'harness' };
+
+/** A receipt whose claude-code hooks target names `settingsPath` (recorded launcher, no seat). */
+function writeHookReceipt(home: string, settingsPath: string, scope = 'user'): void {
+ writeHarnessReceipt(home, harnessReceiptFixture([{ state: 'confirmed' }], {
+ targets: [
+ { host: 'claude-code', kind: 'mcp', scope: 'user', name: 'gbrain', state: 'confirmed' },
+ { host: 'claude-code', kind: 'hooks', scope, path: settingsPath, marker: GBRAIN_HARNESS_MARKER_VALUE, launcher: HOOK_BIN, seat: '', state: 'confirmed' },
+ ],
+ }));
+}
+
+function hookGroups(events: readonly string[], marked: boolean, bin = HOOK_BIN): Record<string, unknown[]> {
+ return Object.fromEntries(events.map((e) => [e, [{ hooks: [{
+ type: 'command', command: buildClaudeHookCommand(bin, e as never, HOOK_ENV), ...(marked ? { _gbrain: GBRAIN_HARNESS_MARKER_VALUE } : {}),
+ }] }]]));
+}
+
+describe('bootstrap_harness_health hook carrier (#6171)', () => {
+ const rows = (checks: Check[]) => checks.filter((c) => c.name === 'bootstrap_harness_health' && (c.details?.code || c.details?.reason));
+ /** The serve /health probe is irrelevant here; fail it at once instead of waiting out its timeout. */
+ const offlineRun = async (parent: string): Promise<Check[]> => {
+ const fetchSpy = spyOn(globalThis, 'fetch').mockRejectedValue(new Error('offline'));
+ try {
+ return await run(parent);
+ } finally {
+ fetchSpy.mockRestore();
+ }
+ };
+
+ test('a duplicated event warns harness_hook_duplicates with a consented re-run of the install\'s own flags', async () => {
+ const { parent, home } = makeHome();
+ const settings = join(parent, 'settings.json');
+ const marked = hookGroups(['SessionStart', 'UserPromptSubmit', 'PreCompact'], true);
+ const unmarked = hookGroups(['SessionStart', 'UserPromptSubmit', 'PreCompact'], false);
+ const hooks = Object.fromEntries(Object.keys(marked).map((e) => [e, [...marked[e]!, ...unmarked[e]!]]));
+ writeFileSync(settings, JSON.stringify({ hooks }));
+ const project = join(parent, 'proj');
+ writeHookReceipt(home, settings, project);
+ const [row] = rows(await offlineRun(parent));
+ expect(row?.status).toBe('warn');
+ expect(row?.details?.code).toBe('harness_hook_duplicates');
+ expect(row?.details?.events).toEqual(['SessionStart', 'UserPromptSubmit', 'PreCompact']);
+ const fix = row?.fix as { argv: string[]; consent: string[]; user_message?: string };
+ expect(fix.argv).toEqual(['gbrain', 'bootstrap', 'harness', '--project', project, '--no-capture', '--yes']);
+ expect(fix.consent).toEqual(['persistent_install']);
+ expect(fix.user_message).toBeTruthy();
+ const { parseHarnessArgs } = await import('../src/core/bootstrap/harness.ts');
+ const parsed = parseHarnessArgs(fix.argv.slice(3));
+ expect(parsed.error).toBeUndefined();
+ expect(parsed.projects).toEqual([project]);
+ expect(parsed.noCapture).toBe(true);
+ const [rendered] = finalizeCheckFixes([row!]);
+ expect((rendered!.fix as { next: string }).next).toBe('ask_user');
+ }, T);
+
+ test('marker-stripped entries only → ok info note, never a warning', async () => {
+ const { parent, home } = makeHome();
+ const settings = join(parent, 'settings.json');
+ writeFileSync(settings, JSON.stringify({ hooks: hookGroups(['SessionStart', 'Stop'], false) }));
+ writeHookReceipt(home, settings);
+ const [row] = rows(await offlineRun(parent));
+ expect(row?.status).toBe('ok');
+ expect(row?.details?.reason).toBe('harness_hook_marker_stripped');
+ expect(row?.message).toMatch(/2 harness hook entries .* carry no _gbrain marker/);
+ }, T);
+
+ test('another launcher\'s lookalike → warn harness_hook_unowned; an unparseable carrier → warn naming the file', async () => {
+ const { parent, home } = makeHome();
+ const settings = join(parent, 'settings.json');
+ writeFileSync(settings, JSON.stringify({ hooks: { ...hookGroups(['Stop'], true), ...hookGroups(['SessionEnd'], false, '/opt/other/gbrain') } }));
+ writeHookReceipt(home, settings);
+ const [row] = rows(await offlineRun(parent));
+ expect(row?.status).toBe('warn');
+ expect(row?.details?.code).toBe('harness_hook_unowned');
+ expect(row?.details?.events).toEqual(['SessionEnd']);
+ expect(row?.fix_unavailable_reason).toBe('operator_judgement');
+
+ writeFileSync(settings, '{ "hooks": ');
+ const [broken] = rows(await offlineRun(parent));
+ expect(broken?.status).toBe('warn');
+ expect(broken?.message).toContain(settings);
+ expect(broken?.details?.reason).toBe('harness_hook_carrier_unparseable');
+ }, T);
+
+ test('one marked entry per event → no carrier row', async () => {
+ const { parent, home } = makeHome();
+ const settings = join(parent, 'settings.json');
+ writeFileSync(settings, JSON.stringify({ hooks: hookGroups(['SessionStart', 'Stop', 'SessionEnd'], true) }));
+ writeHookReceipt(home, settings);
+ expect(rows(await offlineRun(parent))).toEqual([]);
+ }, T);
+});
+
// ── 1. hook heartbeat failure rate [B3] ─────────────────────────────────────
describe('bootstrap_hooks_heartbeat thresholds', () => {
diff --git a/test/bootstrap-harness-hook-ownership.test.ts b/test/bootstrap-harness-hook-ownership.test.ts
new file mode 100644
index 0000000000..55a013c7c9
--- /dev/null
+++ b/test/bootstrap-harness-hook-ownership.test.ts
@@ -0,0 +1,290 @@
+/**
+ * Harness hook entries that lost their `_gbrain` marker (#6092, #6171).
+ * Claude Code can drop unknown keys when it rewrites settings.json, so the
+ * harness lane recognizes its own unmarked entries by an anchored parse of
+ * exactly the command buildClaudeHookCommand writes, scoped per event and
+ * bound to this install's launcher/source/seat (receipt-backed). Anything else
+ * that merely looks like a harness hook is unowned and never deleted.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ buildClaudeHookCommand,
+ classifyHarnessHook,
+ groupsCarryGbrainHook,
+ harnessHookIdentity,
+ parseClaudeHookCommand,
+ removeClaudeHooksAt,
+ scanHarnessHookCarrier,
+ writeClaudeHooksAt,
+ type ClaudeHookEnv,
+ type HarnessHookIdentity,
+} from '../src/core/bootstrap/hooks.ts';
+import {
+ CLAUDE_HOOK_EVENTS,
+ CLAUDE_HOOK_SUBCOMMAND,
+ GBRAIN_HARNESS_MARKER_VALUE,
+ GBRAIN_HOOK_MARKER_KEY,
+ type ClaudeHookEvent,
+} from '../src/core/bootstrap/host-specs.ts';
+
+const BIN = '/opt/fake/gbrain';
+const OLD_BIN = '/home/alice-example/gbrain-clone/bin/gbrain';
+const ME: HarnessHookIdentity = { launchers: [BIN], sources: ['default'] };
+const HARNESS_ENV: ClaudeHookEnv = { GBRAIN_SOURCE: 'default', GBRAIN_HOOK_LANE: 'harness' };
+
+function tmpFile(): string {
+ return join(mkdtempSync(join(tmpdir(), 'gb-hook-own-')), 'settings.json');
+}
+
+function readJson(path: string): Record<string, unknown> {
+ return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;
+}
+
+function entry(command: string, extra: Record<string, unknown> = {}): Record<string, unknown> {
+ return { type: 'command', command, timeout: 5, ...extra };
+}
+
+/** Our five harness entries with the marker stripped, as the host leaves them. */
+function strippedHarnessHooks(bin = BIN, env: ClaudeHookEnv = HARNESS_ENV): Record<string, unknown[]> {
+ return Object.fromEntries(CLAUDE_HOOK_EVENTS.map((e) => [e, [{ hooks: [entry(buildClaudeHookCommand(bin, e, env))] }]]));
+}
+
+function flat(settings: Record<string, unknown>, event: string): Array<Record<string, unknown>> {
+ const groups = ((settings.hooks ?? {}) as Record<string, unknown[]>)[event] ?? [];
+ return groups.flatMap((g) => ((g as { hooks?: unknown[] }).hooks ?? []) as Array<Record<string, unknown>>);
+}
+
+describe('parseClaudeHookCommand (inverse of buildClaudeHookCommand)', () => {
+ test('round-trips every event, env combination and quoted launcher', () => {
+ const bins = [BIN, '/Users/alice example/.bun/bin/gbrain', "/tmp/it's here/gbrain", '/opt/a@b:c/gbrain'];
+ const envs: ClaudeHookEnv[] = [];
+ for (const source of [undefined, '', 'default', 'acme-notes']) {
+ for (const home of [undefined, '/srv/brain home']) {
+ for (const lane of [undefined, 'harness']) {
+ for (const seat of [undefined, 'alice-desk']) {
+ envs.push({
+ ...(source !== undefined ? { GBRAIN_SOURCE: source } : {}),
+ ...(home ? { GBRAIN_HOME: home } : {}),
+ ...(lane ? { GBRAIN_HOOK_LANE: lane } : {}),
+ ...(seat ? { GBRAIN_SEAT: seat } : {}),
+ });
+ }
+ }
+ }
+ }
+ let n = 0;
+ for (const bin of bins) {
+ for (const env of envs) {
+ for (const event of CLAUDE_HOOK_EVENTS) {
+ const command = buildClaudeHookCommand(bin, event, env);
+ const parsed = parseClaudeHookCommand(command);
+ expect(parsed).toEqual({ gbrainBin: bin, subcommand: CLAUDE_HOOK_SUBCOMMAND[event], env });
+ n++;
+ }
+ }
+ }
+ expect(n).toBe(bins.length * envs.length * CLAUDE_HOOK_EVENTS.length);
+ });
+
+ test('rejects anything the builder would not write', () => {
+ const good = buildClaudeHookCommand(BIN, 'Stop', HARNESS_ENV);
+ expect(parseClaudeHookCommand(good)).not.toBeNull();
+ for (const bad of [
+ `${good} | tee /tmp/log`,
+ `${good} --debug`,
+ `${good} `,
+ ` ${good}`,
+ good.replace('env ', 'env '),
+ `env GBRAIN_SOURCE=default GBRAIN_SOURCE=other GBRAIN_HOOK_LANE=harness ${BIN} hook stop`,
+ `env GBRAIN_HOOK_LANE=harness GBRAIN_SOURCE=default ${BIN} hook stop`,
+ `env FOO=1 GBRAIN_HOOK_LANE=harness ${BIN} hook stop`,
+ `env 'GBRAIN_SOURCE=default' GBRAIN_HOOK_LANE=harness ${BIN} hook stop`,
+ `env GBRAIN_HOOK_LANE=harness gbrain hook stop`,
+ `env GBRAIN_HOOK_LANE=harness ${BIN} hook stop extra`,
+ `env GBRAIN_HOOK_LANE=harness ${BIN} hook not-an-event`,
+ `GBRAIN_HOOK_LANE=harness ${BIN} hook stop`,
+ `env GBRAIN_HOME= GBRAIN_HOOK_LANE=harness ${BIN} hook stop`,
+ ]) {
+ expect(parseClaudeHookCommand(bad)).toBeNull();
+ }
+ });
+});
+
+describe('classifyHarnessHook: grammar is not ownership', () => {
+ const stop = (bin = BIN, env: ClaudeHookEnv = HARNESS_ENV) => entry(buildClaudeHookCommand(bin, 'Stop', env));
+
+ test('marked, owned command, and identity-free shape match', () => {
+ expect(classifyHarnessHook({ ...stop(), [GBRAIN_HOOK_MARKER_KEY]: GBRAIN_HARNESS_MARKER_VALUE }, 'Stop', ME)?.ownership).toBe('marked');
+ const owned = classifyHarnessHook(stop(), 'Stop', ME);
+ expect(owned?.ownership).toBe('command');
+ expect(owned?.why).not.toContain(BIN);
+ expect(classifyHarnessHook(stop(OLD_BIN), 'Stop', 'any')?.ownership).toBe('command');
+ });
+
+ test('differing launchers, homes, sources and seats are unowned', () => {
+ expect(classifyHarnessHook(stop(OLD_BIN), 'Stop', ME)?.ownership).toBe('unowned');
+ expect(classifyHarnessHook(stop('/custom/tool'), 'Stop', ME)?.ownership).toBe('unowned');
+ expect(classifyHarnessHook(stop(BIN, { ...HARNESS_ENV, GBRAIN_HOME: '/srv/other' }), 'Stop', ME)?.ownership).toBe('unowned');
+ expect(classifyHarnessHook(stop(BIN, { GBRAIN_SOURCE: 'acme-notes', GBRAIN_HOOK_LANE: 'harness' }), 'Stop', ME)?.ownership).toBe('unowned');
+ const seated = stop(BIN, { ...HARNESS_ENV, GBRAIN_SEAT: 'alice-desk' });
+ expect(classifyHarnessHook(seated, 'Stop', { ...ME, seats: [''] })?.ownership).toBe('unowned');
+ expect(classifyHarnessHook(seated, 'Stop', { ...ME, seats: ['alice-desk'] })?.ownership).toBe('command');
+ expect(classifyHarnessHook(seated, 'Stop', ME)?.ownership).toBe('command');
+ });
+
+ test('event scoping, edits, other markers and foreign hooks', () => {
+ expect(classifyHarnessHook(stop(), 'SubagentStop', ME)).toBeNull();
+ expect(classifyHarnessHook(stop(), 'SessionStart', ME)?.ownership).toBe('unowned');
+ expect(classifyHarnessHook(entry(`${buildClaudeHookCommand(BIN, 'Stop', HARNESS_ENV)} | tee log`), 'Stop', ME)?.ownership).toBe('unowned');
+ expect(classifyHarnessHook({ ...stop(), [GBRAIN_HOOK_MARKER_KEY]: 'bootstrap-v1' }, 'Stop', ME)).toBeNull();
+ expect(classifyHarnessHook(entry(buildClaudeHookCommand(BIN, 'Stop', { GBRAIN_SOURCE: 'ws' })), 'Stop', ME)).toBeNull();
+ expect(classifyHarnessHook(entry('echo hi'), 'Stop', ME)).toBeNull();
+ });
+});
+
+describe('harnessHookIdentity', () => {
+ test('merges the current install with the receipt-recorded launcher, source and seat', () => {
+ const receipt = { source_id: 'default' };
+ expect(harnessHookIdentity(receipt, { launcher: OLD_BIN, seat: 'alice-desk' }, { launcher: BIN, source: 'acme-notes', seat: 'desk-2' }))
+ .toEqual({ launchers: [BIN, OLD_BIN], sources: ['acme-notes', 'default'], seats: ['alice-desk', 'desk-2'] });
+ });
+
+ test('a legacy receipt (no launcher or seat recorded) leaves seats open; an unpinned receipt claims no-source hooks', () => {
+ expect(harnessHookIdentity({ source_id: 'default', source_pinned: false }, {}, { launcher: null }))
+ .toEqual({ launchers: [], sources: [null] });
+ });
+});
+
+describe('writeClaudeHooksAt converges over marker-stripped entries (#6171)', () => {
+ test('re-run leaves exactly one marked entry per event; the rest of the file is unchanged', () => {
+ const path = tmpFile();
+ const userStop = { matcher: '', hooks: [entry('/usr/local/bin/notify-done')] };
+ const original = {
+ model: 'opus',
+ permissions: { allow: ['Bash(ls:*)', 'mcp__gbrain'] },
+ enabledPlugins: { 'other@market': true },
+ hooks: { Stop: [userStop], SubagentStop: [{ hooks: [entry(buildClaudeHookCommand(BIN, 'Stop', HARNESS_ENV))] }] } as Record<string, unknown[]>,
+ };
+ for (const [event, groups] of Object.entries(strippedHarnessHooks())) {
+ original.hooks[event] = [...(original.hooks[event] ?? []), ...groups];
+ }
+ writeFileSync(path, JSON.stringify(original, null, 2));
+
+ const r = writeClaudeHooksAt(path, { gbrainBin: BIN, env: HARNESS_ENV, marker: GBRAIN_HARNESS_MARKER_VALUE, identity: ME });
+ expect(r.removedPrior).toBe(CLAUDE_HOOK_EVENTS.length);
+ const after = readJson(path);
+ for (const event of CLAUDE_HOOK_EVENTS) {
+ const ours = flat(after, event).filter((e) => typeof e.command === 'string' && (e.command as string).includes('GBRAIN_HOOK_LANE=harness'));
+ expect(ours).toHaveLength(1);
+ expect(ours[0]![GBRAIN_HOOK_MARKER_KEY]).toBe(GBRAIN_HARNESS_MARKER_VALUE);
+ }
+ const { hooks, ...rest } = after;
+ const { hooks: originalHooks, ...originalRest } = original;
+ expect(JSON.stringify(rest)).toBe(JSON.stringify(originalRest));
+ const afterHooks = hooks as Record<string, unknown[]>;
+ expect(afterHooks.Stop![0]).toEqual(userStop);
+ expect(afterHooks.SubagentStop).toEqual(originalHooks.SubagentStop);
+ });
+
+ test('another launcher, home or source survives the install, and the note names the code', () => {
+ const path = tmpFile();
+ const hooks = strippedHarnessHooks(OLD_BIN);
+ hooks.SessionStart = [{ hooks: [entry(buildClaudeHookCommand(BIN, 'SessionStart', { ...HARNESS_ENV, GBRAIN_HOME: '/srv/other' }))] }];
+ hooks.UserPromptSubmit = [{ hooks: [entry(buildClaudeHookCommand(BIN, 'UserPromptSubmit', { GBRAIN_SOURCE: 'acme-notes', GBRAIN_HOOK_LANE: 'harness' }))] }];
+ writeFileSync(path, JSON.stringify({ hooks }));
+ const r = writeClaudeHooksAt(path, { gbrainBin: BIN, env: HARNESS_ENV, marker: GBRAIN_HARNESS_MARKER_VALUE, identity: ME });
+ expect(r.removedPrior).toBe(0);
+ expect(r.notes.filter((n) => n.includes('harness_hook_unowned'))).toHaveLength(CLAUDE_HOOK_EVENTS.length);
+ for (const event of CLAUDE_HOOK_EVENTS) expect(flat(readJson(path), event)).toHaveLength(2);
+ });
+
+ test('a launcher the receipt recorded is claimed (bun-global install replaced by a clone)', () => {
+ const path = tmpFile();
+ writeFileSync(path, JSON.stringify({ hooks: strippedHarnessHooks(OLD_BIN) }));
+ const identity = harnessHookIdentity({ source_id: 'default' }, { launcher: OLD_BIN }, { launcher: BIN, source: 'default' });
+ const r = writeClaudeHooksAt(path, { gbrainBin: BIN, env: HARNESS_ENV, marker: GBRAIN_HARNESS_MARKER_VALUE, identity });
+ expect(r.removedPrior).toBe(CLAUDE_HOOK_EVENTS.length);
+ for (const event of CLAUDE_HOOK_EVENTS) expect(flat(readJson(path), event).map((e) => e.command)).toEqual([buildClaudeHookCommand(BIN, event, HARNESS_ENV)]);
+ });
+
+ test('the seat an unmarked entry carried is kept on re-run', () => {
+ const path = tmpFile();
+ writeFileSync(path, JSON.stringify({ hooks: strippedHarnessHooks(BIN, { ...HARNESS_ENV, GBRAIN_SEAT: 'alice-desk' }) }));
+ const r = writeClaudeHooksAt(path, { gbrainBin: BIN, env: HARNESS_ENV, marker: GBRAIN_HARNESS_MARKER_VALUE, identity: ME });
+ expect(r.seat).toBe('alice-desk');
+ expect(r.installed.every((i) => i.command.includes('GBRAIN_SEAT=alice-desk'))).toBe(true);
+ });
+});
+
+describe('removeClaudeHooksAt removes unmarked-but-ours entries (#6092)', () => {
+ function fixture(): { path: string; before: string } {
+ const path = tmpFile();
+ const hooks = strippedHarnessHooks();
+ hooks.Stop!.push({ hooks: [entry(`${buildClaudeHookCommand(BIN, 'Stop', HARNESS_ENV)} | tee /tmp/log`)] });
+ hooks.SubagentStop = [{ hooks: [entry(buildClaudeHookCommand(BIN, 'Stop', HARNESS_ENV))] }];
+ hooks.SessionStart!.push({ hooks: [entry('echo mine')] });
+ const before = JSON.stringify({ model: 'opus', hooks }, null, 2);
+ writeFileSync(path, before);
+ return { path, before };
+ }
+
+ test('removes ours, lists each by event without command text, keeps and reports the near-miss', () => {
+ const { path } = fixture();
+ const r = removeClaudeHooksAt(path, GBRAIN_HARNESS_MARKER_VALUE, { identity: ME });
+ expect(r.removed).toBe(CLAUDE_HOOK_EVENTS.length);
+ expect(r.unmarked.map((u) => u.event).sort()).toEqual([...CLAUDE_HOOK_EVENTS].sort());
+ for (const u of r.unmarked) {
+ expect(u.why).not.toContain(BIN);
+ expect(u.why).not.toContain('GBRAIN_HOOK_LANE');
+ }
+ expect(r.unowned).toEqual(['Stop']);
+ const after = readJson(path);
+ expect(flat(after, 'Stop').map((e) => e.command)).toEqual([`${buildClaudeHookCommand(BIN, 'Stop', HARNESS_ENV)} | tee /tmp/log`]);
+ expect(flat(after, 'SubagentStop')).toHaveLength(1);
+ expect(flat(after, 'SessionStart').map((e) => e.command)).toEqual(['echo mine']);
+ expect(after.model).toBe('opus');
+ });
+
+ test('dryRun reports the same list and writes nothing', () => {
+ const { path, before } = fixture();
+ const r = removeClaudeHooksAt(path, GBRAIN_HARNESS_MARKER_VALUE, { identity: ME, dryRun: true });
+ expect(r.removed).toBe(CLAUDE_HOOK_EVENTS.length);
+ expect(r.unmarked).toHaveLength(CLAUDE_HOOK_EVENTS.length);
+ expect(r.unowned).toEqual(['Stop']);
+ expect(r.backupPath).toBeNull();
+ expect(readFileSync(path, 'utf8')).toBe(before);
+ });
+
+ test('without an identity removal stays marker-only (workspace lane unchanged)', () => {
+ const { path, before } = fixture();
+ expect(removeClaudeHooksAt(path, GBRAIN_HARNESS_MARKER_VALUE).removed).toBe(0);
+ expect(readFileSync(path, 'utf8')).toBe(before);
+ });
+});
+
+describe('scanHarnessHookCarrier and groupsCarryGbrainHook (read-only probes)', () => {
+ test('counts marked, owned and unowned per event; an unparseable file says so', () => {
+ const path = tmpFile();
+ const hooks = strippedHarnessHooks();
+ hooks.Stop!.push({ hooks: [entry(buildClaudeHookCommand(BIN, 'Stop', HARNESS_ENV), { [GBRAIN_HOOK_MARKER_KEY]: GBRAIN_HARNESS_MARKER_VALUE })] });
+ hooks.PreCompact!.push({ hooks: [entry(buildClaudeHookCommand(OLD_BIN, 'PreCompact', HARNESS_ENV))] });
+ writeFileSync(path, JSON.stringify({ hooks }));
+ const scan = scanHarnessHookCarrier(path, ME);
+ expect(scan.state).toBe('ok');
+ expect(scan.events.Stop).toEqual({ marked: 1, command: 1, unowned: 0 });
+ expect(scan.events.PreCompact).toEqual({ marked: 0, command: 1, unowned: 1 });
+ expect(scanHarnessHookCarrier(path, 'any').events.PreCompact).toEqual({ marked: 0, command: 2, unowned: 0 });
+ writeFileSync(path, '{ not json');
+ expect(scanHarnessHookCarrier(path, ME).state).toBe('unparseable');
+ });
+
+ test('an unmarked harness command counts as a gbrain hook for carrier overlap', () => {
+ const event: ClaudeHookEvent = 'SessionStart';
+ expect(groupsCarryGbrainHook([{ hooks: [entry(buildClaudeHookCommand(BIN, event, HARNESS_ENV))] }], event)).toBe(true);
+ expect(groupsCarryGbrainHook([{ hooks: [entry('echo hi')] }], event)).toBe(false);
+ expect(groupsCarryGbrainHook([{ hooks: [entry('x', { [GBRAIN_HOOK_MARKER_KEY]: 'bootstrap-v1' })] }], event)).toBe(true);
+ });
+});
diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.ts
index c8ad2de803..d45b0522bc 100644
--- a/test/bootstrap-harness.serial.test.ts
+++ b/test/bootstrap-harness.serial.test.ts
@@ -52,6 +52,7 @@ import {
} from '../src/core/bootstrap/host-specs.ts';
import { AMBIENT_WRITEBACK_BLOCK_BEGIN } from '../src/core/bootstrap/instructions-block.ts';
import type { ExecRunner } from '../src/core/bootstrap/repo.ts';
+import { buildClaudeHookCommand } from '../src/core/bootstrap/hooks.ts';
import type { ConnectProbeResult } from '../src/core/connect-probe.ts';
import type { GBrainConfig } from '../src/core/config.ts';
import { VERSION } from '../src/version.ts';
@@ -1590,3 +1591,181 @@ describe('ambient-writeback instruction blocks (kind: instructions, WP3)', () =>
expect(instrTargets(f.home).map((t) => t.host)).toEqual(['claude-code']);
});
});
+
+// ── #6092 / #6171: hook entries the host stripped of their _gbrain marker ──
+
+/** Drop the `_gbrain` key from every hook entry, as a Claude Code settings rewrite can. */
+function stripMarkers(path: string): void {
+ const s = readJson(path);
+ for (const groups of Object.values((s.hooks ?? {}) as Record<string, Array<{ hooks?: Array<Record<string, unknown>> }>>)) {
+ for (const g of groups) for (const e of g.hooks ?? []) delete e._gbrain;
+ }
+ writeFileSync(path, JSON.stringify(s, null, 2));
+}
+
+function hookEntries(path: string, event: string): Array<Record<string, unknown>> {
+ const groups = ((readJson(path).hooks ?? {}) as Record<string, Array<{ hooks?: Array<Record<string, unknown>> }>>)[event] ?? [];
+ return groups.flatMap((g) => g.hooks ?? []);
+}
+
+function harnessReceipt(home: string): HarnessReceipt {
+ const state = readHarnessReceiptState(home);
+ if (state.state !== 'ok') throw new Error(`receipt ${state.state}`);
+ return state.receipt;
+}
+
+describe('harness hooks without their marker (#6092, #6171)', () => {
+ const CLAUDE = ['--harness', 'claude-code'];
+
+ test('apply → host strips markers → --remove exits 0, removes all five, lists them, consumes the receipt', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags(CLAUDE), f.deps)).toBe(0);
+ const s = readJson(f.userSettings);
+ (s.hooks as Record<string, unknown[]>).SessionStart.push({ hooks: [{ type: 'command', command: 'echo mine' }] });
+ s.model = 'opus';
+ writeFileSync(f.userSettings, JSON.stringify(s, null, 2));
+ stripMarkers(f.userSettings);
+
+ expect(await removeHarness(parseHarnessArgs(['--remove', '--yes']), f.deps)).toBe(0);
+ const after = readJson(f.userSettings);
+ expect(after.hooks).toEqual({ SessionStart: [{ hooks: [{ type: 'command', command: 'echo mine' }] }] });
+ expect(after.model).toBe('opus');
+ expect(readHarnessReceiptState(f.home)).toEqual({ state: 'absent' });
+ const out = f.out.join('\n');
+ for (const event of CLAUDE_HOOK_EVENTS) expect(out).toContain(`removed unmarked hooks.${event} entry`);
+ expect(out).not.toContain('/opt/fake/gbrain hook');
+ expect(out).toMatch(/fully removed/);
+ });
+
+ test('apply → strip → re-apply converges to exactly one marked entry per event', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags(CLAUDE), f.deps)).toBe(0);
+ stripMarkers(f.userSettings);
+ expect(await applyHarness(flags(CLAUDE), f.deps)).toBe(0);
+ for (const event of CLAUDE_HOOK_EVENTS) {
+ const entries = hookEntries(f.userSettings, event);
+ expect(entries).toHaveLength(1);
+ expect(entries[0]!._gbrain).toBe(GBRAIN_HARNESS_MARKER_VALUE);
+ }
+ const hooks = harnessReceipt(f.home).targets.find((t) => t.kind === 'hooks');
+ expect(hooks?.launcher).toBe('/opt/fake/gbrain');
+ expect(hooks?.seat).toBe('');
+ });
+
+ test('a launcher recorded on the receipt is claimed after an upgrade moves the binary', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags(CLAUDE), f.deps)).toBe(0);
+ stripMarkers(f.userSettings);
+ expect(await applyHarness(flags([...CLAUDE, '--gbrain-bin', '/opt/new/gbrain']), f.deps)).toBe(0);
+ for (const event of CLAUDE_HOOK_EVENTS) {
+ const entries = hookEntries(f.userSettings, event);
+ expect(entries).toHaveLength(1);
+ expect(String(entries[0]!.command)).toContain('/opt/new/gbrain hook');
+ }
+ });
+
+ test('another install\'s unmarked hooks (different launcher, not on the receipt) survive install and remove', async () => {
+ const f = makeFake();
+ const other = buildClaudeHookCommand('/opt/other-install/gbrain', 'Stop', { GBRAIN_SOURCE: 'default', GBRAIN_HOOK_LANE: 'harness' });
+ writeFileSync(f.userSettings, JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: other }] }] } }));
+ expect(await applyHarness(flags(CLAUDE), f.deps)).toBe(0);
+ expect(f.err.join('\n')).toContain('harness_hook_unowned');
+ expect(hookEntries(f.userSettings, 'Stop').map((e) => e.command)).toContain(other);
+ expect(await removeHarness(parseHarnessArgs(['--remove', '--yes']), f.deps)).toBe(1);
+ expect(hookEntries(f.userSettings, 'Stop').map((e) => e.command)).toEqual([other]);
+ });
+
+ test('an edited lookalike keeps the hooks target failed (exit 1, harness_hook_unowned); a retry after the hand edit exits 0', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags(CLAUDE), f.deps)).toBe(0);
+ const s = readJson(f.userSettings);
+ const stop = (s.hooks as Record<string, Array<{ hooks: Array<Record<string, unknown>> }>>).Stop[0]!.hooks[0]!;
+ delete stop._gbrain;
+ stop.command = `${String(stop.command)} | tee /tmp/stop.log`;
+ writeFileSync(f.userSettings, JSON.stringify(s, null, 2));
+
+ expect(await removeHarness(parseHarnessArgs(['--remove', '--yes']), f.deps)).toBe(1);
+ expect(hookEntries(f.userSettings, 'Stop')).toHaveLength(1);
+ for (const event of CLAUDE_HOOK_EVENTS.filter((e) => e !== 'Stop')) expect(hookEntries(f.userSettings, event)).toHaveLength(0);
+ const hooks = harnessReceipt(f.home).targets.find((t) => t.kind === 'hooks');
+ expect(hooks?.state).toBe('failed');
+ expect(hooks?.error).toContain('harness_hook_unowned');
+ const err = f.err.join('\n');
+ expect(err).toContain('[gbrain notice harness_hook_unowned kind=safety]');
+ expect(err).toContain('next: tell_user_to_run');
+ expect(err).toContain('fix: gbrain bootstrap harness --remove');
+ expect(err).toContain('verify: gbrain bootstrap harness --status');
+ expect(f.out.join('\n')).not.toMatch(/fully removed/);
+
+ const fixed = readJson(f.userSettings);
+ delete (fixed.hooks as Record<string, unknown>).Stop;
+ writeFileSync(f.userSettings, JSON.stringify(fixed, null, 2));
+ expect(await removeHarness(parseHarnessArgs(['--remove', '--yes']), f.deps)).toBe(0);
+ expect(readHarnessReceiptState(f.home)).toEqual({ state: 'absent' });
+ });
+
+ test('--remove --dry-run lists what would go and writes nothing', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags(CLAUDE), f.deps)).toBe(0);
+ stripMarkers(f.userSettings);
+ const settingsBefore = readFileSync(f.userSettings, 'utf8');
+ const receiptBefore = readFileSync(harnessReceiptPath(f.home), 'utf8');
+ const callsBefore = f.calls.length;
+ expect(await removeHarness(parseHarnessArgs(['--remove', '--dry-run', '--yes']), f.deps)).toBe(0);
+ expect(readFileSync(f.userSettings, 'utf8')).toBe(settingsBefore);
+ expect(readFileSync(harnessReceiptPath(f.home), 'utf8')).toBe(receiptBefore);
+ expect(f.calls.length).toBe(callsBefore);
+ expect(f.revoked).toEqual([]);
+ const out = f.out.join('\n');
+ for (const event of CLAUDE_HOOK_EVENTS) expect(out).toContain(`would remove unmarked hooks.${event} entry`);
+ expect(out).toContain('would remove 5 harness hook entries');
+ expect(parseHarnessArgs(['--dry-run']).error).toMatch(/--remove --dry-run/);
+ });
+
+ test('apply → re-apply → --remove drops our mcp__gbrain; a pre-existing entry still survives', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags([...CLAUDE, '--no-hooks']), f.deps)).toBe(0);
+ expect(await applyHarness(flags([...CLAUDE, '--no-hooks']), f.deps)).toBe(0);
+ expect(harnessReceipt(f.home).targets.find((t) => t.kind === 'permission')?.mechanism).toBe('added');
+ expect(f.out.join('\n')).not.toMatch(/pre-existing/);
+ expect(await removeHarness(parseHarnessArgs(['--remove', '--yes']), f.deps)).toBe(0);
+ expect(JSON.stringify(readJson(f.userSettings))).not.toContain('mcp__gbrain');
+
+ const g = makeFake();
+ writeFileSync(g.userSettings, JSON.stringify({ permissions: { allow: ['mcp__gbrain'] } }));
+ expect(await applyHarness(flags([...CLAUDE, '--no-hooks']), g.deps)).toBe(0);
+ expect(await applyHarness(flags([...CLAUDE, '--no-hooks']), g.deps)).toBe(0);
+ expect(harnessReceipt(g.home).targets.find((t) => t.kind === 'permission')?.mechanism).toBe('pre-existing');
+ expect(await removeHarness(parseHarnessArgs(['--remove', '--yes']), g.deps)).toBe(0);
+ expect((readJson(g.userSettings).permissions as { allow: string[] }).allow).toEqual(['mcp__gbrain']);
+ });
+
+ test('a failed smoke on a re-run keeps the restored registration\'s pre-approval', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags([...CLAUDE, '--no-hooks']), f.deps)).toBe(0);
+ const deps: HarnessDeps = { ...f.deps, probeIdentity: async () => ({ ok: false, reason: 'auth', message: 'HTTP 401' }) };
+ expect(await applyHarness(flags([...CLAUDE, '--no-hooks']), deps)).toBe(1);
+ expect((readJson(f.userSettings).permissions as { allow: string[] }).allow).toEqual(['mcp__gbrain']);
+ });
+
+ test('cross-HOME guard: another install\'s UNMARKED user-scope hooks block --project wiring', async () => {
+ const f = makeFake();
+ const hooks = Object.fromEntries(CLAUDE_HOOK_EVENTS.map((e) => [e, [{ hooks: [{
+ type: 'command', command: buildClaudeHookCommand('/opt/other-home/gbrain', e, { GBRAIN_SOURCE: 'default', GBRAIN_HOOK_LANE: 'harness' }),
+ }] }]]));
+ writeFileSync(f.userSettings, JSON.stringify({ hooks }));
+ const project = mkdtempSync(join(tmpdir(), 'gb-harness-proj-'));
+ expect(await applyHarness(flags([...CLAUDE, '--project', project]), f.deps)).toBe(2);
+ expect(f.err.join('\n')).toMatch(/user-scope harness hooks already exist/);
+ expect(existsSync(join(project, '.claude', 'settings.local.json'))).toBe(false);
+ });
+
+ test('--status reports each hook carrier, counting unmarked entries as ours', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags(CLAUDE), f.deps)).toBe(0);
+ stripMarkers(f.userSettings);
+ f.out.length = 0;
+ await statusHarness(parseHarnessArgs(['--status']), f.deps);
+ expect(f.out.join('\n')).toContain(`hook entries in ${f.userSettings}: 5 gbrain (5 without the _gbrain marker)`);
+ });
+});
diff --git a/test/bootstrap-verify-hook-carrier-overlap.test.ts b/test/bootstrap-verify-hook-carrier-overlap.test.ts
index 241e545cf5..44dca55626 100644
--- a/test/bootstrap-verify-hook-carrier-overlap.test.ts
+++ b/test/bootstrap-verify-hook-carrier-overlap.test.ts
@@ -105,6 +105,17 @@ describe('checkHookCarrierOverlap (#4585)', () => {
expect(check.detail).not.toContain('WARN');
});
+ test('#6092: user-scope harness hooks the host stripped of their marker still count as a carrier', () => {
+ mkdirSync(dirname(userSettings), { recursive: true });
+ writeFileSync(userSettings, JSON.stringify({
+ hooks: { SessionStart: [{ hooks: [{ type: 'command', command: 'env GBRAIN_SOURCE=default GBRAIN_HOOK_LANE=harness /opt/fake/gbrain hook session-start' }] }] },
+ }));
+ writeCarrier(join(ws, '.claude', 'settings.local.json'), ['SessionStart']);
+ const check = checkHookCarrierOverlap(ws, userSettings);
+ expect(check.detail).toContain('WARN');
+ expect(check.detail).toContain('SessionStart (user-scope settings.json + .claude/settings.local.json)');
+ });
+
test('a malformed carrier fails soft (treated as carrying nothing)', () => {
writeCarrier(join(ws, '.claude', 'settings.local.json'), ['SessionStart']);
mkdirSync(dirname(userSettings), { recursive: true });