Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(bootstrap): move pending_verify into harness-pending-verify.ts (#6661)
garrytan6418f4775f55
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex 96ba96815c..5b89cc610d 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 `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. #6661 option B: on a PGLite brain a `--token` run whose `/health` probe gets no response (`ServeHealth.unreachable`) while no serve holds the brain wires every target, skips the canary and smoke without rolling back, writes `verify_pending` on the receipt and exits `HARNESS_PENDING_VERIFY_EXIT_CODE` (13, JSON `status: pending_verify`, `code: pending_verify`) with the same-command `--token <TOKEN>` re-run as `fix` (`harnessPendingVerifyFix`); `--status` reports `status: partial` and exits 1 while the marker stands, and the next passing run's fresh receipt clears it. A live holder (wrong `--url`/`--port`), an HTTP answer, no `--token` or Postgres still fail.+- `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. #6661 option B: `harness-pending-verify.ts` (a `--token` run on PGLite with no serve answering ends `pending_verify`, exit 13, re-run as `fix`; `--status` partial until it passes).- `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 or session source record once no `.txt` of its session remains, after a 10-minute grace; session-end counts live sessions across the spool and the legacy top level (#6611). 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. #5941: the pack and user-prompt arms ask for `contextSourceId` (session-start-pack.ts): `GBRAIN_SOURCE`, else the session's frozen source record, else the cwd's `.gbrain-source` walk; a serve bound elsewhere answers `source_mismatch` (the heartbeat reason).- `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/src/core/bootstrap/harness-pending-verify.ts b/src/core/bootstrap/harness-pending-verify.tsnew file mode 100644index 0000000000..4029d21c7c--- /dev/null+++ b/src/core/bootstrap/harness-pending-verify.ts@@ -0,0 +1,83 @@+/**+ * #6661 option B: `gbrain bootstrap harness --token` on a PGLite brain while no serve answers.+ *+ * The serve holds the PGLite single-writer lock, so a stopped serve is the normal state for wiring. When+ * `/health` gets no response at all and no serve holds the brain, the run wires every target and ends+ * `pending_verify` (exit 13) instead of failing before any write. A serve that holds the brain but does not+ * answer at this url (a wrong --url/--port), anything answering with a non-ok reply, a run without --token,+ * registrar mode and Postgres brains still fail the health check.+ *+ * The completion step is the same --token run once the serve is up: it needs no PGLite lock (nothing is+ * minted, and source resolution falls back while a serve holds the brain), verifies over HTTP and enrolls+ * shared skills. `--status` stays partial while the receipt carries `verify_pending`; each run writes a+ * fresh receipt, so the next run that passes its smoke clears it.+ */+import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';+import type { GBrainConfig } from '../config.ts';+import type { HarnessReceipt } from './format.ts';+import type { ServeHealth } from './serve-health.ts';++interface PendingVerifyDeps {+ loadFileConfig: () => GBrainConfig | null;+ pgliteLiveServe: () => boolean;+ logError: (line: string) => void;+}++/**+ * The step-2 health verdict: true when the run proceeds as pending_verify. Logs the hard-stop line when+ * the caller must return 1 (`!health.ok` and not pending), or the pending note.+ */+export function harnessVerifyPending(health: ServeHealth, flags: { token?: string }, registrarMode: boolean, url: string, d: PendingVerifyDeps): boolean {+ if (health.ok) return false;+ const pending = health.unreachable === true && flags.token !== undefined && !registrarMode &&+ d.loadFileConfig()?.engine === 'pglite' && !d.pgliteLiveServe();+ d.logError(pending+ ? `no gbrain serve answers at ${url} and none holds this PGLite brain: wiring with the supplied --token now; verification waits for the serve (pending_verify).`+ : `no healthy gbrain serve at ${url} (${health.detail ?? 'unreachable'}) — start \`gbrain serve --http\` on this box first (or pass --url/--port).`);+ return pending;+}++/** The fix: this run's argv with the token shown as `<TOKEN>`, the resolved source pinned, and --yes. */+export function harnessPendingVerifyFix(raw: readonly string[], url: string, resolvedSource: string | null): Action {+ const argv = ['gbrain', 'bootstrap', 'harness'];+ for (let i = 0; i < raw.length; i++) {+ if (raw[i] === '--json') continue;+ if (raw[i] === '--token') { i++; argv.push('--token', '<TOKEN>'); continue; }+ argv.push(raw[i]!);+ }+ if (resolvedSource) argv.push('--source', resolvedSource);+ if (!argv.includes('--yes')) argv.push('--yes');+ return {+ argv,+ inputs: [{ name: 'TOKEN', how: 'The same token this run was given with --token.' }],+ consent: [],+ actor: 'user',+ why: 'The smoke test needs a running serve; the re-run verifies the wiring over HTTP while the serve holds the PGLite brain.',+ user_message: `Start \`gbrain serve --http\` for this brain (it must answer at ${url}), then re-run this command with the same --token. ` ++ '`gbrain bootstrap harness --status` reports partial until that run passes its smoke test.',+ verify: { argv: ['gbrain', 'bootstrap', 'harness', '--status', '--json'] },+ docs: 'docs/guides/bootstrap.md#pending-verify',+ requires_exclusive: false,+ };+}++/** Records the marker on the receipt, logs the outcome and returns the fix. */+export function finishPendingVerify(receipt: HarnessReceipt, save: () => void, raw: readonly string[], url: string,+ resolvedSource: string | null, d: Pick<PendingVerifyDeps, 'logError'>): Action {+ const fix = harnessPendingVerifyFix(raw, url, resolvedSource);+ receipt.verify_pending = { since: new Date().toISOString(), reason: 'serve_unreachable' };+ save();+ d.logError(`pending_verify: the harness is wired but not verified. ${fix.user_message}`);+ return fix;+}++/** The apply `--json` outcome fields: `status`, and `code` + rendered `fix` when pending. */+export function harnessOutcomeFields(pendingFix: Action | null, ok: boolean): { status: string; code?: string; fix?: RenderedAction } {+ if (!pendingFix) return { status: ok ? 'ok' : 'failed' };+ return { status: 'pending_verify', code: 'pending_verify', fix: renderAction(pendingFix, cliRenderContext()) };+}++export function pendingVerifyStatusLine(pending: NonNullable<HarnessReceipt['verify_pending']>): string {+ return ` partial: wired ${pending.since} while no serve answered (pending_verify) — with \`gbrain serve --http\` running, ` ++ 're-run the same `gbrain bootstrap harness --token <TOKEN>` command to verify and finish.';+}diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.tsindex cd69510a59..b559c6d772 100644--- a/src/core/bootstrap/harness.ts+++ b/src/core/bootstrap/harness.ts@@ -43,7 +43,7 @@import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';import { askHarnessConsent } from './harness-consent.ts';import { CONFIRMATION_REQUIRED_EXIT_CODE, HARNESS_PENDING_VERIFY_EXIT_CODE } from '../exit-codes.ts';-import { cliRenderContext, renderAction, type Action } from '../agent-output.ts';+import { finishPendingVerify, harnessOutcomeFields, harnessVerifyPending, pendingVerifyStatusLine } from './harness-pending-verify.ts';import { dirname, join, resolve } from 'node:path';import { randomUUID } from 'node:crypto';@@ -947,22 +947,8 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Pd.log('registrar mode (non-loopback url): hooks are NOT wired — they would talk to the LOCAL brain, not the registered remote serve. MCP registration only.');}const health = await probeServeHealth(url, d.fetchFn);- // #6661: on PGLite a stopped serve is the normal state for wiring with --token (the serve holds the- // single-writer lock), so nothing answering is pending verification, not a failure. A serve that holds- // the brain but does not answer at this url (a wrong --url/--port), or anything else answering, still fails.- const verifyPending = !health.ok && health.unreachable === true && flags.token !== undefined && !registrarMode &&- d.loadFileConfig()?.engine === 'pglite' && !d.pgliteLiveServe();- if (!health.ok && !verifyPending) {- d.logError(- `no healthy gbrain serve at ${url} (${health.detail ?? 'unreachable'}) — ` +- 'start `gbrain serve --http` on this box first (or pass --url/--port).',- );- return 1;- }- if (verifyPending) {- d.logError(`no gbrain serve answers at ${url} and none holds this PGLite brain: wiring with the supplied --token now; ` +- 'verification waits for the serve (pending_verify).');- }+ const verifyPending = harnessVerifyPending(health, flags, registrarMode, url, d); // #6661: logs the verdict+ if (!health.ok && !verifyPending) return 1;// 2b. Ambient-writeback gate (WP3): resolved from the FILE plane only —// this lane is engine-free by design (the DB plane stays authoritative for@@ -1663,11 +1649,9 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P// format, both unknown to it), so it either rejects both (smoke fails,// nothing revoked, rollback fires) or accepts the canary and is caught// here. Either way the fresh mint is revoked below, never left live.- const canary = verifyPending ? null : await d.probeIdentity(url, generateToken('gbrain_'));+ const canary = await d.probeIdentity(url, generateToken('gbrain_'));let smoke: ConnectProbeResult;- if (canary === null) {- smoke = { ok: false, reason: 'unreachable', message: `no gbrain serve answered at ${url} when this run started` };- } else if (canary.ok || canary.reason === 'tool_error') {+ if (canary.ok || canary.reason === 'tool_error') {smoke = {ok: false,reason: 'auth',@@ -1691,9 +1675,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P'smoke test: token authenticated (initialize + tool dispatch reached); get_brain_identity ' +'unavailable — the serve likely runs a narrowed --surface (e.g. verbs). Counted as verified.',);- } else if (verifyPending) {- d.log('smoke test: pending — start `gbrain serve --http`, then re-run this command (the wiring stays in place).');- } else {+ } else if (!verifyPending || !['unreachable', 'timeout'].includes(smoke.reason)) { // #6661: nothing answered, nothing to roll backd.logError(redactToken(`smoke test FAILED (${smoke.reason}): ${smoke.message}` +@@ -2033,22 +2015,12 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P);}- // #6661: everything wired, only the serve-side check is outstanding.- const pendingVerify = verifyPending && allConfirmed;- const pendingFix = pendingVerify ? harnessPendingVerifyFix(flags, url, unpinnedHooks || flags.source ? null : hookSource ?? null) : null;- if (pendingVerify) {- receipt.verify_pending = { since: new Date().toISOString(), reason: 'serve_unreachable' };- save();- d.logError(`pending_verify: the harness is wired but not verified. ${pendingFix!.user_message}`);- }-+ const pendingFix = verifyPending && allConfirmed && !smokeOk ? finishPendingVerify(receipt, save, flags.raw, url, unpinnedHooks || flags.source ? null : hookSource, d) : null;if (flags.json) {emitJson(JSON.stringify({- schema_version: 1,- status: pendingVerify ? 'pending_verify' : allConfirmed && smokeOk ? 'ok' : 'failed',- ...(pendingFix ? { code: 'pending_verify', fix: renderAction(pendingFix, cliRenderContext()) } : {}),+ schema_version: 1, ...harnessOutcomeFields(pendingFix, allConfirmed && smokeOk),url,engine: health.engine ?? null,serve_version: health.version ?? null,@@ -2066,38 +2038,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P),);}- if (pendingVerify) return HARNESS_PENDING_VERIFY_EXIT_CODE;- return allConfirmed && smokeOk ? 0 : 1;-}--/**- * #6661: the completion step for `pending_verify` is this same --token run once the serve is up: it needs no- * PGLite lock (nothing is minted, and source resolution falls back while a serve holds the brain), verifies- * over HTTP, and enrolls shared skills. The token value is never repeated; the source this run resolved is- * pinned so the re-run wires the hooks the same way.- */-function harnessPendingVerifyFix(flags: HarnessFlags, url: string, resolvedSource: string | null): Action {- const argv = ['gbrain', 'bootstrap', 'harness'];- for (let i = 0; i < flags.raw.length; i++) {- const a = flags.raw[i]!;- if (a === '--json') continue;- if (a === '--token') { i++; argv.push('--token', '<TOKEN>'); continue; }- argv.push(a);- }- if (resolvedSource) argv.push('--source', resolvedSource);- if (!argv.includes('--yes')) argv.push('--yes');- return {- argv,- inputs: [{ name: 'TOKEN', how: 'The same token this run was given with --token.' }],- consent: [],- actor: 'user',- why: 'The smoke test needs a running serve; the re-run verifies the wiring over HTTP while the serve holds the PGLite brain.',- user_message: `Start \`gbrain serve --http\` for this brain (it must answer at ${url}), then re-run this command with the same --token. ` +- '`gbrain bootstrap harness --status` reports partial until that run passes its smoke test.',- verify: { argv: ['gbrain', 'bootstrap', 'harness', '--status', '--json'] },- docs: 'docs/guides/bootstrap.md#pending-verify',- requires_exclusive: false,- };+ return pendingFix ? HARNESS_PENDING_VERIFY_EXIT_CODE : allConfirmed && smokeOk ? 0 : 1;}// ── Remove [C9/F2/C8] ───────────────────────────────────────────────────────@@ -2605,10 +2546,7 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):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(', ')}`);}- if (receipt.verify_pending) {- d.log(` partial: wired ${receipt.verify_pending.since} while no serve answered (pending_verify) — with \`gbrain serve --http\` running, ` +- 're-run the same `gbrain bootstrap harness --token <TOKEN>` command to verify and finish.');- }+ if (receipt.verify_pending) d.log(pendingVerifyStatusLine(receipt.verify_pending));if (degraded) {d.log('per-turn injection: needs a running gbrain serve on Postgres (MCP tools are the active seam).');}diff --git a/test/backup-preflight-6649.test.ts b/test/backup-preflight-6649.serial.test.tssimilarity index 100%rename from test/backup-preflight-6649.test.tsrename to test/backup-preflight-6649.serial.test.tsdiff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.tsindex 7ae1cbfcff..34f5238d64 100644--- a/test/bootstrap-harness.serial.test.ts+++ b/test/bootstrap-harness.serial.test.ts@@ -149,6 +149,7 @@ function makeFake(opts: {});}) as unknown as typeof fetch,probeIdentity: async (_url: string, probeToken: string): Promise<ConnectProbeResult> => {+ if (!health.ok) return { ok: false, reason: 'unreachable', message: 'fetch failed: ECONNREFUSED' };// Token-aware like a REAL serve: only tokens this fixture knows about// authenticate — the apply-time canary (a random same-format token)// must fail with reason 'auth' or every apply trips the impostor guard.diff --git a/test/fixtures/guards/check-windows-hide.ts/bad-stale-migration/src/core/tailscale.ts b/test/fixtures/guards/check-windows-hide.ts/bad-stale-migration/src/core/persistence/topology-filesystem.tssimilarity index 100%rename from test/fixtures/guards/check-windows-hide.ts/bad-stale-migration/src/core/tailscale.tsrename to test/fixtures/guards/check-windows-hide.ts/bad-stale-migration/src/core/persistence/topology-filesystem.tsdiff --git a/test/fixtures/guards/check-windows-hide.ts/good/src/core/tailscale.ts b/test/fixtures/guards/check-windows-hide.ts/good/src/core/persistence/topology-filesystem.tssimilarity index 100%rename from test/fixtures/guards/check-windows-hide.ts/good/src/core/tailscale.tsrename to test/fixtures/guards/check-windows-hide.ts/good/src/core/persistence/topology-filesystem.tsdiff --git a/test/windows-ipc-long-path-6573.test.ts b/test/windows-ipc-long-path-6573.serial.test.tssimilarity index 100%rename from test/windows-ipc-long-path-6573.test.tsrename to test/windows-ipc-long-path-6573.serial.test.ts