Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(bootstrap): LIVE_SERVE refusal prints a pre-mint with the full harness grant (#6661)
time-attack0b4ed53b2ce6
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex cf6f60f6cf..735ba198cb 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -29,7 +29,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; it removes hook entries that lost their marker when their command is this install's (`harness-hooks.ts`), keeps the hooks target failed on an unowned lookalike, and `--remove --dry-run` previews without a lock or any write. Hooks targets record `launcher` and `seat` on the receipt (the ownership identity for later runs); the permission target carries `mechanism: 'added'` forward from a prior confirmed receipt target so a re-run never relabels its own `mcp__<name>` as pre-existing, and the failed-smoke rollback removes only an entry added this run. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`. The production mint (`mintHarnessToken`, exported) rotates each host's token from the token it replaces via `carryLegacyGrant`. `--refresh-skills` (`src/core/bootstrap/harness-skills.ts`, `refreshHarnessSkills`) re-joins each live shared-skills entry under its recorded credential so the receipt and native router adopt the server's current enrollment epoch, with no token rotation; `localEnrollment` reads the adapter receipt epoch for `--status`, and `supersededEnrollments` is doctor's read-only comparison against `shared_skill_members` (`bootstrap_harness_health` warn, code `shared_skills_epoch_superseded`). Pinned by `test/harness-skills-epoch.test.ts`. The Codex SessionEnd capture hook obeys the same recorded consent as the Claude lane (`wireCodexCapture`: hooks on, capture accepted, never registrar mode) and is a numbered consent item when wired.+- `src/core/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 `LIVE_SERVE` when no token was supplied, printing (and in `details.steps`) stop / `auth create` + `auth rescope --operations` with the harness grant / restart / `--token` (#6661) and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve; it removes hook entries that lost their marker when their command is this install's (`harness-hooks.ts`), keeps the hooks target failed on an unowned lookalike, and `--remove --dry-run` previews without a lock or any write. Hooks targets record `launcher` and `seat` on the receipt (the ownership identity for later runs); the permission target carries `mechanism: 'added'` forward from a prior confirmed receipt target so a re-run never relabels its own `mcp__<name>` as pre-existing, and the failed-smoke rollback removes only an entry added this run. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`. The production mint (`mintHarnessToken`, exported) rotates each host's token from the token it replaces via `carryLegacyGrant`. `--refresh-skills` (`src/core/bootstrap/harness-skills.ts`, `refreshHarnessSkills`) re-joins each live shared-skills entry under its recorded credential so the receipt and native router adopt the server's current enrollment epoch, with no token rotation; `localEnrollment` reads the adapter receipt epoch for `--status`, and `supersededEnrollments` is doctor's read-only comparison against `shared_skill_members` (`bootstrap_harness_health` warn, code `shared_skills_epoch_superseded`). Pinned by `test/harness-skills-epoch.test.ts`. The Codex SessionEnd capture hook obeys the same recorded consent as the Claude lane (`wireCodexCapture`: hooks on, capture accepted, never registrar mode) and is a numbered consent item when wired.- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor, `[]` stored as the explicit no-source grant; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). `carryLegacyGrant` + `readActiveTokenPermissions` are the harness rotation carry-over: takes holders and the source grant carry as stored (explicit empty lists included; an explicit `--source` wins), a stored operation snapshot narrows to the run's snapshot plus only skills-policy-added operations, and newer operations are reported as withheld (pinned by `test/harness-rotation-grants.test.ts`). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`. `insertUnifiedToken` (shared with `auth create`) births every token on the unified grant columns at revision 1 plus the `permissions` mirror; a brain whose schema predates the columns refuses with `migrations_pending` (fix: `gbrain apply-migrations --yes`) and nothing is written; `carryLegacyGrant` parses the prior grant from its JSONB through `tokenGrantFromPermissions`, so a drifted prior carries its JSON edit (the `--adopt-permissions` resolution).- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). session-start's context pack goes through `src/core/context/session-start-pack.ts`: when `sessionStartAwaitsServe` holds (source `startup`/`resume`, harness claude-code, `claudeCodeSpawnsServe(cwd)`), the hook's deadline widens from `SESSION_START_DEADLINE_MS` (1.5s) to `SESSION_START_SERVE_WAIT_DEADLINE_MS` (4s, under the 5s harness timeout) and `requestSessionStartPack` retries every 100ms, re-resolving socket and secret, until the serve Claude Code spawned alongside SessionStart answers (Cat 41 first push: Claude Code 2.1.285 starts MCP servers in parallel with SessionStart and a fresh serve binds ~2s later); a wait that runs out records heartbeat `degraded`/`serve_not_ready`. Pinned by `test/hook-session-start-serve-wait.serial.test.ts`. When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune via `gcCorpusTurnFiles`: an extracted `.txt` goes at `corpus_retention_days`, one with no `.ingested` sidecar only at `CORPUS_UNINGESTED_RETENTION_FACTOR` (3) times that, E-N1, pinned by `test/corpus-retention-uningested.serial.test.ts`; an assistant-only whole-file parse heartbeats `degraded`/`no_user_turns`, E-N4; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`. Seat identity (#4618): session-end (before any corpus write of the session), compact (before `bankCompactSegment`) and the stop hook's writeback bank (before `bankWritebackTurn`) record `<sessionId>.seat.json` through `context/seat.ts` — `GBRAIN_SEAT` when valid, else the hashed harness-home seat; `seat_label_invalid`, `seat_conflict` (first seat kept) and `seat_write_failed` are heartbeat reasons with a fixed `hint` (session-end applies them last, like the deferred reasons). `gcCorpusArtifacts` reaps a seat sidecar once no `.txt` of its session remains, after a 10-minute grace. Pinned by `test/session-seat-capture.serial.test.ts`. `HOOK_EVENTS` is the router inventory from `src/cli/subcommands.ts`; `hook <event> --help` prints usage and never runs the event. `user-prompt` confines and parses `transcript_path` through `captureSpecFor(io.harness)`, so `--harness codex` reads the rollout under `CODEX_HOME/sessions` (the Claude projects root otherwise), and skips the Claude-only pressure notice for codex.- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). Both the hook-tail and full-session parsers skip root `isSidechain`, `isMeta`, or `isCompactSummary` exactly `true`; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string root `origin.kind` other than `'human'` is excluded; missing, empty, or unstructured origins stay compatible, without guessing from message text. Assistant text and non-text placeholders remain eligible, while skipped metadata entries also contribute no collected tool calls. `test/claude-code-jsonl-origin.test.ts` uses synthetic fixtures, not new live-harness validation. `genuineUserTurnIndexes` separately records accepted user-role turns containing real text blocks (harness tags and paste blocks removed first), because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.diff --git a/docs/guides/bootstrap.md b/docs/guides/bootstrap.mdindex 9e493ce72a..5c7419d235 100644--- a/docs/guides/bootstrap.md+++ b/docs/guides/bootstrap.md@@ -300,9 +300,21 @@ mode wires them in one command, with no `agent.json` and no interview:`--yes`. Close active Claude Code sessions for the cleanest user-scopesettings writes (the host also writes that file).-PGLite note: minting needs the single-writer lock, so on a PGLite brain-either pre-mint (`gbrain auth create bootstrap-harness --scopes read,write`-while the serve is stopped) and pass `--token`, or stop/re-run/restart.+PGLite note: minting needs the single-writer lock, and the health check+needs the serve running, so on a PGLite brain the harness can't mint its own+token. Pre-mint it with the harness grant while the serve is stopped, then+pass `--token` (#6661). The `LIVE_SERVE` refusal prints these steps with the+exact operation list:++1. Stop the serve.+2. `gbrain auth create bootstrap-harness --scopes read,write,skills_member_self`+ (`--scopes read,write` under `--skills memory-only`; `skills_member_self`+ is what lets the harness join shared skills).+3. `gbrain auth rescope --token bootstrap-harness --operations <the printed list>`+ (plus `--sources <id>` when you pass `--source`).+4. Start `gbrain serve --http` again.+5. Re-run `gbrain bootstrap harness` with `--token <value>`.+Postgres brains mint fine while the serve runs. A token you supply is neverrevoked by `--remove` or rotation (it is not the harness's to revoke) —retire it yourself with `gbrain auth revoke` when you're done with it.diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.tsindex 3a1363114c..6c4c923709 100644--- a/src/core/bootstrap/harness.ts+++ b/src/core/bootstrap/harness.ts@@ -781,15 +781,16 @@ async function cleanupStalePriorTargets(}}-/** A live `gbrain serve` holds this PGLite brain: the two documented escape hatches. */-function liveServeRefusal(): BootstrapError {- return new BootstrapError(- 'LIVE_SERVE',- 'a live `gbrain serve` holds this PGLite brain, so the harness cannot mint a token — either ' +- 'pre-mint one while the serve is stopped (`gbrain auth create bootstrap-harness --scopes read,write`) ' +- 'and re-run with --token <value>, or stop the serve, re-run this command, and restart it. ' +- '(Postgres brains mint fine while the serve runs.)',- );+/** #6661 (D25): a live serve holds this PGLite brain (no mint) and a stopped one fails the health probe: pre-mint with the harness grant, then --token. */+async function liveServeRefusal(opts: { tokenName: string; follow: boolean; source?: string }): Promise<BootstrapError> {+ const scopes = opts.follow ? ['read', 'write', 'skills_member_self'] : ['read', 'write'];+ const operations = await harnessOperationSnapshot(opts.follow);+ const steps = ['stop the serve that holds this brain', `gbrain auth create ${opts.tokenName} --scopes ${scopes.join(',')}`,+ `gbrain auth rescope --token ${opts.tokenName} --operations ${operations.join(',')}${opts.source ? ` --sources ${opts.source}` : ''}`,+ 'start `gbrain serve --http` again', 're-run this `gbrain bootstrap harness` command with --token <the token step 2 printed>'];+ return new BootstrapError('LIVE_SERVE', 'a live `gbrain serve` holds this PGLite brain, so the harness cannot mint a token, and with the serve ' ++ `stopped its health check fails. Pre-mint the token with the harness grant (scopes ${scopes.join(',')} and its operation list), then use ` ++ `--token:\n${steps.map((step, i) => ` ${i + 1}. ${step}`).join('\n')}\n(Postgres brains mint fine while the serve runs.)`, { details: { steps, scopes, operations } });}/** The engine could not open because a live serve holds the PGLite brain (vs any other failure). */@@ -1086,7 +1087,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P// A live PGLite serve holds the brain. Without a token the mint below// would refuse anyway — refuse HERE with the same two escape hatches, so// the operator never sees a source-resolution error for a lock problem.- if (flags.token === undefined) throw liveServeRefusal();+ if (flags.token === undefined) throw await liveServeRefusal({ tokenName: flags.tokenName, follow: skillsPolicy === 'follow' });// --token lane (the documented PGLite path): nothing is minted, so the// grant is the operator's own token. Leave the hooks UNPINNED — a hook// request that names no source resolves through the live serve's own@@ -1265,7 +1266,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P});} catch (e) {const msg = e instanceof Error ? e.message : String(e);- if (isLiveServeFailure(msg, d)) throw liveServeRefusal();+ if (isLiveServeFailure(msg, d)) throw await liveServeRefusal({ tokenName: flags.tokenName, follow: skillsPolicy === 'follow', ...(flags.source ? { source: flags.source } : {}) });throw e;}tokens.set(host, minted.token);diff --git a/test/bootstrap-harness-lifecycle.serial.test.ts b/test/bootstrap-harness-lifecycle.serial.test.tsindex f9cf9f17f7..19bc299402 100644--- a/test/bootstrap-harness-lifecycle.serial.test.ts+++ b/test/bootstrap-harness-lifecycle.serial.test.ts@@ -125,6 +125,36 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {GBRAIN_DATABASE_URL: undefined,});+ // #6661: started once in beforeAll and again by the pre-mint sequence test (which stops it first).+ async function startServe(env: Record<string, string | undefined>): Promise<void> {+ serverReady = false;+ server = spawn('bun', [+ 'run', 'src/cli.ts', 'serve', '--http',+ '--bind', '127.0.0.1', '--port', String(PORT),+ '--public-url', BASE,+ ], { cwd: process.cwd(), env, stdio: ['ignore', 'pipe', 'pipe'] });+ let serr = '';+ server.stderr?.on('data', (d: Buffer) => { serr += d.toString(); });+ for (let i = 0; i < 60; i++) {+ try {+ const res = await fetch(`${BASE}/health`);+ if (res.ok) { serverReady = true; break; }+ } catch { /* not up yet */ }+ await new Promise((r) => setTimeout(r, 500));+ }+ if (!serverReady) throw new Error(`serve --http did not become ready:\n${serr}`);+ }++ async function stopServe(): Promise<void> {+ const proc = server;+ server = null;+ serverReady = false;+ if (!proc || proc.exitCode !== null) return;+ const exited = new Promise<void>((r) => proc.once('exit', () => r()));+ proc.kill('SIGTERM');+ await exited;+ }+beforeAll(async () => {parent = mkdtempSync(join(tmpdir(), 'gb-harness-e2e-'));sandboxHome = mkdtempSync(join(tmpdir(), 'gb-harness-home-'));@@ -154,21 +184,7 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {if (!token) throw new Error(`auth create did not yield a token:\n${authOut}`);expect(authOut).toContain('scopes=["read","write"]');- server = spawn('bun', [- 'run', 'src/cli.ts', 'serve', '--http',- '--bind', '127.0.0.1', '--port', String(PORT),- '--public-url', BASE,- ], { cwd: process.cwd(), env, stdio: ['ignore', 'pipe', 'pipe'] });- let serr = '';- server.stderr?.on('data', (d: Buffer) => { serr += d.toString(); });- for (let i = 0; i < 60; i++) {- try {- const res = await fetch(`${BASE}/health`);- if (res.ok) { serverReady = true; break; }- } catch { /* not up yet */ }- await new Promise((r) => setTimeout(r, 500));- }- if (!serverReady) throw new Error(`serve --http did not become ready:\n${serr}`);+ await startServe(env);}, 90_000);afterAll(() => {@@ -191,6 +207,48 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {expect(err).toMatch(/stop the serve/);}, 60_000);+ // #6661 (D25): the refusal's printed sequence, run for real: stop the serve, pre-mint with the harness grant, restart.+ test('the refusal\'s stop/mint/rescope/start sequence yields a token with the harness grant', async () => {+ expect(serverReady).toBe(true);+ const { runner } = makeClaudeRunner();+ const { result, err } = await withEnv(envFor(), () =>+ capture(() => runBootstrap(['harness', '--yes', '--port', String(PORT), '--harness', 'codex', '--token-name', 'harness-e2e'], { runner, harnessDetect: HARNESS_DETECT })),+ );+ expect(result).toBe(1);+ const steps = [...err.matchAll(/^\s+\d\. (.*)$/gm)].map((m) => m[1]!);+ expect(steps).toHaveLength(5);+ expect(steps[0]).toMatch(/stop the serve/);+ expect(steps[1]).toBe('gbrain auth create harness-e2e --scopes read,write,skills_member_self');+ expect(steps[2]).toMatch(/^gbrain auth rescope --token harness-e2e --operations \S*join_brain\S*$/);+ expect(steps[3]).toMatch(/gbrain serve --http/);+ expect(steps[4]).toMatch(/--token/);++ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: parent };+ delete env.DATABASE_URL;+ delete env.GBRAIN_DATABASE_URL;+ const gbrain = (argv: string[]) => execFileSync('bun', ['run', 'src/cli.ts', ...argv], { cwd: process.cwd(), env, encoding: 'utf8' });+ await stopServe();+ const created = gbrain(steps[1]!.split(' ').slice(1));+ const premint = (created.match(/gbrain_[a-f0-9]{64}/) ?? [''])[0];+ expect(premint).not.toBe('');+ gbrain(steps[2]!.split(' ').slice(1));+ const grants = gbrain(['auth', 'rescope', '--token', 'harness-e2e']);+ const stored = (grants.match(/^\s+Operations: (.*)$/m) ?? ['', ''])[1]!.split(', ');+ expect(stored).toEqual(steps[2]!.split(' ')[6]!.split(','));+ await startServe(env);+ const joinBrain = async (bearer: string) => (await fetch(`${BASE}/mcp`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${bearer}` },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'join_brain', arguments: {} } }),+ })).text();+ // The printed grant reaches join_brain (refused only for its missing argument); the bare read,write pre-mint the+ // old refusal suggested is refused for scope, which is what the reporter hit.+ const viaPremint = await joinBrain(premint);+ expect(viaPremint).toContain('Missing required parameter: adapter');+ expect(viaPremint).not.toContain('insufficient_scope');+ expect(await joinBrain(token)).toContain('insufficient_scope');+ }, 120_000);+test('apply with --token: real health + real bearer smoke; both harnesses wired; receipt + install log', async () => {expect(serverReady).toBe(true);const { runner, calls } = makeClaudeRunner();diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.tsindex 07fa3a0bab..9f9cd90c1d 100644--- a/test/bootstrap-harness.serial.test.ts+++ b/test/bootstrap-harness.serial.test.ts@@ -746,6 +746,41 @@ describe('outside-voice hardening (X-batch)', () => {expect(readHarnessReceiptState(f.home)).toEqual({ state: 'absent' });});+ // #6661 (D25): the refusal's pre-mint carries the harness grant; a bare `--scopes read,write` token got join_brain refused.+ test('LIVE_SERVE refusal prints the stop/mint/rescope/start/--token sequence with the full harness grant', async () => {+ const f = makeFake({+ pgliteLive: true,+ hookSourceError: new Error("GBrain's local database is already open through `gbrain serve` (MCP, PID 4242)."),+ });+ const err = await applyHarness(flags(['--harness', 'codex']), f.deps).then(() => null, (e: unknown) => e as { code: string; message: string; details: { steps: string[]; scopes: string[]; operations: string[] } });+ expect(err?.code).toBe('LIVE_SERVE');+ const { steps, scopes, operations } = err!.details;+ expect(scopes).toEqual(['read', 'write', 'skills_member_self']);+ expect(operations).toEqual(expect.arrayContaining(['join_brain', 'sync_brain_skills', 'leave_brain', 'put_page', 'query']));+ const { operations: all } = await import('../src/core/operations.ts');+ const byName = new Map(all.map(op => [op.name, op]));+ expect(operations.filter(name => byName.get(name)?.localOnly || !['read', 'write'].includes(byName.get(name)?.scope ?? ''))).toEqual([]);+ expect(steps).toEqual([+ 'stop the serve that holds this brain',+ 'gbrain auth create bootstrap-harness --scopes read,write,skills_member_self',+ `gbrain auth rescope --token bootstrap-harness --operations ${operations.join(',')}`,+ 'start `gbrain serve --http` again',+ 're-run this `gbrain bootstrap harness` command with --token <the token step 2 printed>',+ ]);+ for (const step of steps) expect(err!.message).toContain(step);+ expect(f.mintCalls).toHaveLength(0);+ });++ test('LIVE_SERVE refusal on a memory-only re-run with --source carries the memory-only grant and the source floor', async () => {+ const f = makeFake({ pgliteLive: true, mintQueue: [] });+ const err = await applyHarness(flags(['--harness', 'codex', '--skills', 'memory-only', '--source', 'wiki', '--token-name', 'hx']), f.deps)+ .then(() => null, (e: unknown) => e as { code: string; details: { steps: string[]; operations: string[] } });+ expect(err?.code).toBe('LIVE_SERVE');+ expect(err!.details.steps[1]).toBe('gbrain auth create hx --scopes read,write');+ expect(err!.details.steps[2]).toMatch(/^gbrain auth rescope --token hx --operations \S+ --sources wiki$/);+ expect(err!.details.operations).not.toContain('join_brain');+ });+test('live PGLite serve + --token + no --source: wires unpinned with a warning (the documented PGLite lane)', async () => {const f = makeFake({pgliteLive: true,