Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(bootstrap): converge shared-skills cleanup after a cleanup token is revoked (#6743)
garrytan5b144d7e45d6
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex 5b89cc610d..34ad7cc872 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -30,6 +30,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `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: `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/bootstrap/harness-cleanup.ts` — #6743 shared-skills cleanup convergence for the harness apply (step 10), `--status` and doctor's `bootstrap_harness_health`. `convergeHarnessCleanup` leaves stale enrollments (a working prior enrollment stays until the current one is ready; one whose credential is already revoked always leaves) and then revokes each carried `previous_ids` entry that no not-yet-left enrollment holds, one id at a time. `leaveRevokedEnrollment` runs the adapter's local leave with a caller that never contacts the host and records the entry left with reason `credential_revoked`: a revoked principal cannot authenticate `leave_brain`, so its membership is inert. `harnessCleanupItems` reports what stays pending per id (`revoke_pending`, `leave_pending`, `enrollment_retained`, `credential_unreadable`, with the token-row state from the read-only `tokenStatesWith` lookup); the apply and `--status` exit `bootstrap_cleanup_pending` (14) with a `fix` that re-runs the same command when every id converges and otherwise names the owner's revoke or restore step. Pinned by `test/bootstrap-harness-cleanup-6743.test.ts`.- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor, `[]` stored as the explicit no-source grant; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). `carryLegacyGrant` + `readActiveTokenPermissions` are the harness rotation carry-over: takes holders and the source grant carry as stored (explicit empty lists included; an explicit `--source` wins), a stored operation snapshot narrows to the run's snapshot plus only skills-policy-added operations, and newer operations are reported as withheld (pinned by `test/harness-rotation-grants.test.ts`). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`. `insertUnifiedToken` (shared with `auth create`) births every token on the unified grant columns at revision 1 plus the `permissions` mirror; a brain whose schema predates the columns refuses with `migrations_pending` (fix: `gbrain apply-migrations --yes`) and nothing is written; `carryLegacyGrant` parses the prior grant from its JSONB through `tokenGrantFromPermissions`, so a drifted prior carries its JSON edit (the `--adopt-permissions` resolution).- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). 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/docs/guides/bootstrap.md b/docs/guides/bootstrap.mdindex 5a0a648011..b88f553255 100644--- a/docs/guides/bootstrap.md+++ b/docs/guides/bootstrap.md@@ -330,6 +330,30 @@ doesn't answer at the URL you gave (a wrong `--url` or `--port`), anythingelse answering there, a run without `--token`, and a Postgres brain all stillfail the health check with exit 1.+<a id="cleanup-pending"></a>Each rotation leaves the old shared-skills+enrollment with that enrollment's own credential, then revokes the+credential: leave before revoke, because `leave_brain` is principal-owned and+a revoked token can never leave. Each carried token id is revoked and cleared+on its own, so one stuck enrollment no longer holds every other id on the+receipt. An enrollment whose credential is already revoked (for example,+revoked by hand before its leave finished) is inert: the run still removes it+locally (adapter receipt, native router, unchanged owned files; edited files+are retained) and records it as left with reason `credential_revoked`.++While anything is still pending, the run exits `bootstrap_cleanup_pending`+(exit 14, `"status": "cleanup_pending"` under `--json`) instead of 0. The+JSON `cleanup` array lists each id with its token state (`active`,+`revoked`, `missing`, `unknown`), its cleanup state (`revoke_pending`,+`leave_pending`, `enrollment_retained`, `credential_unreadable`) and whether+a re-run can finish it. When every id can, the `fix` re-runs the same command+(`next: run`). When one cannot, the `fix` is the owner's step+(`next: tell_user_to_run`): for a lost cleanup credential, restore it or+revoke that token by id, after which the next re-run finishes the local+cleanup; for an old enrollment kept because the current one is not ready,+resolve the current enrollment first. `--status` exits 14 with the same list,+and doctor's `bootstrap_harness_health` names each id as revoked (cleanup+pending) or active.+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/docs/guides/shared-brain-skills.md b/docs/guides/shared-brain-skills.mdindex 9ea326dce8..6dbe9a2d0c 100644--- a/docs/guides/shared-brain-skills.md+++ b/docs/guides/shared-brain-skills.md@@ -584,7 +584,11 @@ erasure of source material, history, or backups.Managed removal disables local following and attempts owned-file cleanup evenwhen offline or already revoked. `remote_membership_pending: true` means the-host has not acknowledged leave; retry remote cleanup when possible. Do not+host has not acknowledged leave; retry remote cleanup when possible. A+bootstrap-managed enrollment whose credential is already revoked cannot leave+remotely; `gbrain bootstrap harness` finishes its local cleanup and records it+as left with reason `credential_revoked`, because a revoked principal's+membership is inert ([cleanup pending](bootstrap.md#cleanup-pending)). Do notclaim a server-side departure from successful local deletion, or delete editedfiles to make the status look complete.diff --git a/src/commands/doctor/bootstrap-checks.ts b/src/commands/doctor/bootstrap-checks.tsindex 71f7bb160a..3200517e4e 100644--- a/src/commands/doctor/bootstrap-checks.ts+++ b/src/commands/doctor/bootstrap-checks.ts@@ -172,6 +172,8 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise// --status`'s job; doctor stays offline-cheap.if (harnessState.state === 'ok') {const hr = harnessState.receipt;+ const { cleanupDoctorMessage, harnessCleanupReport, tokenStatesWith } = await import('../../core/bootstrap/harness-cleanup.ts');+ let cleanup: Awaited<ReturnType<typeof harnessCleanupReport>> = [];const failed = hr.targets.filter((t) => t.state === 'failed');const pending = hr.targets.filter((t) => t.state === 'pending');if (failed.length > 0 || pending.length > 0) {@@ -182,11 +184,13 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise`harness wiring incomplete: ${failed.length} failed / ${pending.length} pending target(s)` +` — re-run \`gbrain bootstrap harness\` to converge (details: gbrain bootstrap harness --status).`,});- } else if (hr.token.previous_ids && hr.token.previous_ids.length > 0) {+ } else if ((cleanup = await harnessCleanupReport(hr, ids => engine ? tokenStatesWith(engine, ids) : Promise.resolve({}))).length > 0) {+ // #6743: per id, a revoked credential awaiting enrollment cleanup reads apart from an active one (leave before revoke).checks.push({name: 'bootstrap_harness_health',status: 'fail',- message: `${hr.token.previous_ids.length} previous harness token(s) were never revoked (ids ${hr.token.previous_ids.join(', ')}) — re-run \`gbrain bootstrap harness\`, or run \`gbrain auth revoke\` with the id flag per id.`,+ message: cleanupDoctorMessage(cleanup),+ details: { code: 'bootstrap_cleanup_pending', cleanup },});} else if (hr.targets.length === 0 && hr.token.minted && hr.token.id !== undefined) {// Half-removed state: a remove under a live PGLite serve strips everydiff --git a/src/core/bootstrap/harness-cleanup.ts b/src/core/bootstrap/harness-cleanup.tsnew file mode 100644index 0000000000..f474db1469--- /dev/null+++ b/src/core/bootstrap/harness-cleanup.ts@@ -0,0 +1,283 @@+/**+ * #6743: shared-skills cleanup convergence for `gbrain bootstrap harness`.+ *+ * A rotation leaves each old shared-skills enrollment with that enrollment's+ * own credential, then revokes the credential (leave before revoke:+ * `leave_brain` is principal-owned, so a revoked token can never leave). Two+ * rules keep a re-run converging:+ *+ * - An enrollment whose credential is already revoked is inert remotely: its+ * leave still runs locally (adapter receipt deactivation, native-router+ * removal, owned-file cleanup that keeps edited files) and the entry is+ * recorded as left with reason `credential_revoked`.+ * - Each carried token id is revoked and cleared on its own. Only an id that a+ * not-yet-left enrollment still holds stays on the receipt.+ *+ * Whatever is still pending is reported per id: the apply exits+ * `bootstrap_cleanup_pending` (14) instead of 0, with a fix that re-runs the+ * command when every id can converge and names the owner's step when one+ * cannot. `--status` and doctor read the same items.+ */+import { existsSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';+import { loadConfig, toEngineConfig } from '../config.ts';+import type { BrainEngine } from '../engine.ts';+import { createEngine } from '../engine-factory.ts';+import { TOKEN_ID_RE } from '../token-mint.ts';+import type { HarnessReceipt } from './format.ts';+import { probeLivePgliteHolder } from './uninstall.ts';+import type { resolveHarnessDeps } from './harness.ts';++type SkillsEntry = NonNullable<HarnessReceipt['shared_skills']>[number];+type Deps = ReturnType<typeof resolveHarnessDeps>;++export type TokenState = 'active' | 'revoked' | 'missing' | 'unknown';+export type TokenStateLookup = (ids: string[]) => Promise<Record<string, TokenState>>;++export const BOOTSTRAP_CLEANUP_PENDING = 'bootstrap_cleanup_pending';+export const HARNESS_CLEANUP_DOCS = 'docs/guides/bootstrap.md#cleanup-pending';++export interface CleanupItem {+ /** The carried token id; null for an enrollment that used a supplied credential. */+ token_id: string | null;+ host: string | null;+ token: TokenState;+ state: 'revoke_pending' | 'leave_pending' | 'enrollment_retained' | 'credential_unreadable';+ /** True when a plain re-run of the bootstrap command can finish this id. */+ converges: boolean;+ /** The owner's step when a re-run cannot finish it. */+ user_message?: string;+}++/** Read-only: each id's row state in access_tokens. */+export async function tokenStatesWith(engine: Pick<BrainEngine, 'executeRaw'>, ids: string[]): Promise<Record<string, TokenState>> {+ const valid = ids.filter(id => TOKEN_ID_RE.test(id));+ const rows = valid.length === 0 ? [] : await engine.executeRaw<{ id: string; revoked: boolean }>(+ 'SELECT id::text AS id, revoked_at IS NOT NULL AS revoked FROM access_tokens WHERE id::text = ANY($1::text[])', [valid]);+ return Object.fromEntries(ids.map(id => {+ const row = rows.find(r => r.id.toLowerCase() === id.toLowerCase());+ return [id, !row ? 'missing' : row.revoked ? 'revoked' : 'active'];+ }));+}++export async function defaultTokenStates(ids: string[]): Promise<Record<string, TokenState>> {+ const cfg = loadConfig();+ if (!cfg) throw new Error('no brain configured');+ // A live serve holds the PGLite single-writer lock (the normal state for --status): the states read unknown.+ if (cfg.database_path && probeLivePgliteHolder(cfg.database_path) !== null) throw new Error('a live gbrain serve holds this PGLite brain');+ const engineConfig = toEngineConfig(cfg);+ const engine = await createEngine(engineConfig);+ await engine.connect(engineConfig);+ try {+ return await tokenStatesWith(engine, ids);+ } finally {+ await engine.disconnect();+ }+}++/** A lookup that cannot reach the brain reads every id as unknown, never as revoked. */+async function lookupStates(lookup: TokenStateLookup, ids: string[]): Promise<Record<string, TokenState>> {+ if (ids.length === 0) return {};+ const states = await lookup(ids).catch(() => ({} as Record<string, TokenState>));+ return Object.fromEntries(ids.map(id => [id, states[id] ?? 'unknown']));+}++export async function credentialRevoked(entry: SkillsEntry, d: Pick<Deps, 'tokenStates'>): Promise<boolean> {+ if (!entry.token_id) return false;+ return (await lookupStates(d.tokenStates, [entry.token_id]))[entry.token_id] === 'revoked';+}++/**+ * Leave an enrollment whose credential is already revoked. The local leave+ * runs with a caller that never contacts the host (a revoked bearer cannot+ * authenticate `leave_brain`), and the remote membership counts as inert.+ */+export async function leaveRevokedEnrollment(entry: SkillsEntry, d: Pick<Deps, 'installSharedSkills' | 'log' | 'logError'>): Promise<boolean> {+ const result = await d.installSharedSkills(+ { version: 1, mcp_url: entry.url, issuer_url: entry.url.replace(/\/mcp$/, ''), client_id: entry.token_id ?? `revoked-${entry.host}` },+ { harness: entry.host, root: entry.root, name: entry.name, remove: true,+ toolCaller: async () => { throw new Error('credential_revoked: the cleanup credential is revoked'); } },+ ).catch(() => ({ status: 'pending', retained_files: undefined }));+ if (result.status !== 'left' && result.status !== 'left_with_retained_files') {+ entry.status = 'pending';+ entry.reason = 'cleanup_unavailable';+ d.logError(`shared skills (${entry.host}): local cleanup of the enrollment for revoked token ${entry.token_id} did not finish; a re-run retries it.`);+ return false;+ }+ entry.status = result.status;+ entry.reason = 'credential_revoked';+ entry.retained_files = result.retained_files;+ rmSync(join(entry.root, 'credentials.json'), { force: true });+ d.log(`shared skills (${entry.host}): token ${entry.token_id} is already revoked, so its enrollment cannot leave remotely and is inert; ` ++ `local cleanup finished${result.retained_files?.length ? ` (edited files retained: ${result.retained_files.join(', ')})` : ''}.`);+ return true;+}++const isCurrentEntry = (receipt: HarnessReceipt, entry: SkillsEntry) =>+ entry.token_id === undefined || entry.token_id === receipt.harness_tokens?.[entry.host]?.id;++/** Not-yet-left enrollments other than this run's current ones (without a run: the receipt's harness tokens). */+function staleEntries(receipt: HarnessReceipt, current?: ReadonlySet<SkillsEntry>): SkillsEntry[] {+ return (receipt.shared_skills ?? []).filter(entry => !entry.status.startsWith('left') &&+ !(current ? current.has(entry) : isCurrentEntry(receipt, entry)));+}++const heldIds = (receipt: HarnessReceipt) =>+ new Set((receipt.shared_skills ?? []).filter(e => !e.status.startsWith('left')).flatMap(e => e.token_id ? [e.token_id] : []));++function idsToClassify(receipt: HarnessReceipt, current?: ReadonlySet<SkillsEntry>): string[] {+ return [...new Set([...(receipt.token.previous_ids ?? []), ...staleEntries(receipt, current).flatMap(e => e.token_id ? [e.token_id] : [])])];+}++/** The pending cleanup, one item per stale enrollment and per carried id no enrollment holds. */+export function harnessCleanupItems(receipt: HarnessReceipt, states: Record<string, TokenState>, current?: ReadonlySet<SkillsEntry>): CleanupItem[] {+ const items: CleanupItem[] = staleEntries(receipt, current).map(entry => {+ const token = entry.token_id ? states[entry.token_id] ?? 'unknown' : 'unknown';+ const base = { token_id: entry.token_id ?? null, host: entry.host, token };+ const id = entry.token_id ?? '(supplied)';+ if (entry.reason === 'cleanup_unavailable' && token !== 'revoked') {+ return { ...base, state: 'credential_unreadable', converges: false,+ user_message: `The cleanup credential of the old ${entry.host} enrollment (${join(entry.root, 'credentials.json')}) is unreadable, so it cannot leave. ` ++ `Restore that file, or revoke token ${id} by id (\`gbrain auth revoke\`): an enrollment whose credential is revoked counts as inert ` ++ 'and the next re-run finishes its local cleanup.' };+ }+ if (entry.reason === 'remote_membership_pending' || entry.reason === 'cleanup_unavailable') {+ if (token !== 'missing') return { ...base, state: 'leave_pending', converges: true };+ return { ...base, state: 'leave_pending', converges: false,+ user_message: `Token ${id} is not in this brain's token table, so its ${entry.host} enrollment cannot leave. ` ++ 'Check that this machine\'s brain config names the brain the harness serves (`gbrain auth list` shows its tokens).' };+ }+ return { ...base, state: 'enrollment_retained', converges: false,+ user_message: `The old ${entry.host} enrollment (token ${id}) is kept working because the current shared-skills enrollment is not ready ` ++ '(`gbrain bootstrap harness --status` shows why). Resolve that; the next re-run leaves the old enrollment, then revokes its token.' };+ });+ const held = heldIds(receipt);+ for (const id of receipt.token.previous_ids ?? []) {+ if (!held.has(id)) items.push({ token_id: id, host: null, token: states[id] ?? 'unknown', state: 'revoke_pending', converges: true });+ }+ return items;+}++/** Read-only report for `--status` and doctor. */+export async function harnessCleanupReport(receipt: HarnessReceipt, lookup: TokenStateLookup): Promise<CleanupItem[]> {+ return harnessCleanupItems(receipt, await lookupStates(lookup, idsToClassify(receipt)));+}++/**+ * Apply step 10: leave stale enrollments, then revoke each carried id that no+ * remaining enrollment holds. Returns what is still pending.+ */+export async function convergeHarnessCleanup(o: {+ receipt: HarnessReceipt;+ prior: HarnessReceipt | null | undefined;+ current: ReadonlySet<SkillsEntry>;+ wired: boolean;+ skillsReady: boolean;+ memoryOnly: boolean;+ leave: (entry: SkillsEntry, d: Deps) => Promise<boolean>;+ save: () => void;+}, d: Deps): Promise<CleanupItem[]> {+ const { receipt } = o;+ const states = await lookupStates(d.tokenStates, idsToClassify(receipt, o.current));+ const cached: Deps = { ...d, tokenStates: async ids => Object.fromEntries(ids.map(id => [id, states[id] ?? 'unknown'])) };+ // A working prior enrollment stays until the current one is ready (the follow-approval boundary);+ // one whose credential is revoked is already dead, so it always leaves.+ const priorEnrollment = (o.prior?.shared_skills ?? []).some(entry => !entry.status.startsWith('left') &&+ existsSync(join(entry.root, 'shared-skills', 'receipt.json')));+ const leaveAll = (o.wired && (o.skillsReady || !priorEnrollment)) || o.memoryOnly;+ for (const entry of staleEntries(receipt, o.current)) {+ if (!leaveAll && states[entry.token_id ?? ''] !== 'revoked') continue;+ await o.leave(entry, cached);+ o.save();+ }+ receipt.shared_skills = receipt.shared_skills?.filter(entry => entry.status !== 'left');+ o.save();+ if (o.wired && receipt.token.previous_ids?.length) {+ const held = heldIds(receipt);+ const remaining: string[] = [];+ for (const id of receipt.token.previous_ids) {+ if (held.has(id)) { remaining.push(id); continue; }+ try {+ const revoked = await d.revokeById(id);+ d.log(revoked ? `previous harness token revoked (id ${id}).` : `previous harness token was already revoked (id ${id}).`);+ } catch (e) {+ remaining.push(id);+ d.logError(`could not revoke a previous harness token (${e instanceof Error ? e.message : String(e)}); kept on the receipt (id ${id}) for the next re-run.`);+ }+ }+ if (remaining.length > 0) receipt.token.previous_ids = remaining;+ else delete receipt.token.previous_ids;+ o.save();+ }+ const items = harnessCleanupItems(receipt, states, o.current);+ if (items.length > 0) d.logError(`cleanup pending (${BOOTSTRAP_CLEANUP_PENDING}):\n${cleanupLines(items).join('\n')}`);+ return items;+}++const TOKEN_WORDS: Record<TokenState, string> = {+ active: 'active', revoked: 'revoked', missing: "not in this brain's token table", unknown: 'status unknown',+};++function describeItem(item: CleanupItem): string {+ const who = item.token_id ?? `${item.host} (supplied credential)`;+ const what = item.state === 'revoke_pending'+ ? item.token === 'revoked' ? 'no enrollment holds it; a re-run clears it from the receipt' : 'no enrollment holds it; a re-run revokes it (or `gbrain auth revoke` by id)'+ : item.state === 'leave_pending'+ ? item.token === 'revoked' ? 'enrollment cleanup pending; a re-run finishes it locally' : 'enrollment leave pending'+ : item.state === 'credential_unreadable' ? 'its cleanup credential is unreadable' : 'kept for the previous enrollment until the current one is ready';+ return `${who}: ${TOKEN_WORDS[item.token]}; ${what}`;+}++export function cleanupLines(items: CleanupItem[]): string[] {+ return items.map(item => ` pending: ${describeItem(item)}${item.user_message ? ` — ${item.user_message}` : ''}`);+}++/** Doctor's wording: per id, a revoked credential awaiting cleanup reads apart from an active one. */+export function cleanupDoctorMessage(items: CleanupItem[]): string {+ return `shared-skills cleanup pending for ${items.length} previous harness credential(s): ${items.map(describeItem).join('; ')}. ` ++ 'Leave before revoke: re-run `gbrain bootstrap harness`, which leaves each old enrollment and then revokes its token. ' ++ 'Revoke a token by hand only after its enrollment has left, or when its cleanup credential is lost.';+}++/** The apply's re-run argv: this run's flags, the token value masked, `--yes` added. */+function rerunArgv(raw: readonly string[]): { argv: string[]; token: boolean } {+ const argv = ['gbrain', 'bootstrap', 'harness'];+ let token = false;+ for (let i = 0; i < raw.length; i++) {+ if (raw[i] === '--json') continue;+ if (raw[i] === '--token') { i++; token = true; argv.push('--token', '<TOKEN>'); continue; }+ argv.push(raw[i]!);+ }+ if (!argv.includes('--yes')) argv.push('--yes');+ return { argv, token };+}++export function harnessCleanupFix(items: CleanupItem[], raw: readonly string[]): Action {+ const rerun = rerunArgv(raw);+ const verify = { argv: ['gbrain', 'bootstrap', 'harness', '--status', '--json'] };+ const inputs = rerun.token ? [{ name: 'TOKEN', how: 'The same token this run was given with --token.' }] : undefined;+ const blocked = items.filter(item => !item.converges);+ if (blocked.length === 0) {+ return { argv: rerun.argv, ...(inputs ? { inputs } : {}), consent: [], actor: 'agent', verify, docs: HARNESS_CLEANUP_DOCS, requires_exclusive: false,+ why: 'The same approved command leaves each old shared-skills enrollment, then revokes its token; a leave that was offline is retried.' };+ }+ const first = blocked[0]!;+ const revokeStep = first.state === 'credential_unreadable' && first.token_id !== null;+ return {+ argv: revokeStep ? ['gbrain', 'auth', 'revoke', '--id', first.token_id!] : rerun.argv,+ ...(!revokeStep && inputs ? { inputs } : {}),+ consent: [], actor: 'user', verify, docs: HARNESS_CLEANUP_DOCS, requires_exclusive: false,+ why: 'A re-run alone cannot finish this cleanup; the owner of the old credential acts first.',+ user_message: `${blocked.map(item => item.user_message).join(' ')} Then re-run: ${rerun.argv.join(' ')}`,+ };+}++/** The apply/status `--json` fields: per-id items always; status, code and fix only when the run otherwise succeeded. */+export function cleanupOutcomeFields(items: CleanupItem[], ok: boolean, raw: readonly string[] | null):+ { cleanup?: CleanupItem[]; status?: string; code?: string; fix?: RenderedAction } {+ if (items.length === 0) return {};+ if (!ok) return { cleanup: items };+ return { status: 'cleanup_pending', code: BOOTSTRAP_CLEANUP_PENDING, cleanup: items,+ ...(raw ? { fix: renderAction(harnessCleanupFix(items, raw), cliRenderContext()) } : {}) };+}diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.tsindex b559c6d772..28d5bac39d 100644--- a/src/core/bootstrap/harness.ts+++ b/src/core/bootstrap/harness.ts@@ -42,7 +42,8 @@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 { CONFIRMATION_REQUIRED_EXIT_CODE, HARNESS_CLEANUP_PENDING_EXIT_CODE, HARNESS_PENDING_VERIFY_EXIT_CODE } from '../exit-codes.ts';+import { cleanupLines, cleanupOutcomeFields, convergeHarnessCleanup, credentialRevoked, defaultTokenStates, harnessCleanupReport, leaveRevokedEnrollment, type TokenStateLookup } from './harness-cleanup.ts';import { finishPendingVerify, harnessOutcomeFields, harnessVerifyPending, pendingVerifyStatusLine } from './harness-pending-verify.ts';import { dirname, join, resolve } from 'node:path';import { randomUUID } from 'node:crypto';@@ -338,6 +339,7 @@ export interface HarnessDeps {}>;nativeSkillsDir?: (host: HarnessTarget['host']) => string | undefined;revokeById?: (id: string) => Promise<boolean>;+ tokenStates?: TokenStateLookup; // #6743: read-only token-row states for the cleanup lane; tests inject a fake./** Resolve the source the hooks + token bind to, through the SAME resolver* the serve's resolve-IPC binding uses (resolveSourceWithTier: env →* dotfile → local_path → sources.default → sole non-default → seed@@ -389,6 +391,7 @@ export function resolveHarnessDeps(deps: HarnessDeps): Required<Omit<HarnessDepsreturn config ? join(dirname(config), 'skills') : nativeSharedSkillsDirectory(host) ?? undefined;}),revokeById: deps.revokeById ?? defaultRevokeById,+ tokenStates: deps.tokenStates ?? defaultTokenStates,resolveHookSource: deps.resolveHookSource ?? defaultResolveHookSource,pgliteLiveServe: deps.pgliteLiveServe ?? defaultPgliteLiveServe,// #4325: config-dir fallback mirrors detectCodex/detectOpencode below —@@ -828,6 +831,7 @@ async function leaveHarnessSkills(rmSync(join(entry.root, 'credentials.json'), { force: true });return true;}+ if (await credentialRevoked(entry, d)) return leaveRevokedEnrollment(entry, d);const credentials = readCredentials(join(entry.root, 'credentials.json'));if (credentials.mcp_url !== entry.url) throw new Error('credential endpoint mismatch');const result = await d.installSharedSkills(credentials, { harness: entry.host, root: entry.root, name: entry.name, remove: true });@@ -1964,40 +1968,9 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Psave();}}- const priorEnrollment = (prior?.shared_skills ?? []).some(entry => !entry.status.startsWith('left') &&- existsSync(join(entry.root, 'shared-skills', 'receipt.json')));- let skillsCleanupComplete = skillsReady || !priorEnrollment;- if ((allConfirmed && smokeOk && skillsCleanupComplete) || skillsPolicy === 'memory-only') {- for (const entry of receipt.shared_skills ?? []) {- if (!currentSkills.has(entry) && !(await leaveHarnessSkills(entry, d))) skillsCleanupComplete = false;- save();- }- receipt.shared_skills = receipt.shared_skills?.filter(entry => entry.status !== 'left');- save();- }- if (allConfirmed && smokeOk && skillsCleanupComplete && receipt.token.previous_ids?.length) {- const remaining: string[] = [];- for (const id of receipt.token.previous_ids) {- try {- const revoked = await d.revokeById(id);- d.log(revoked ? `previous harness token revoked (id ${id}).` : `previous harness token was already revoked (id ${id}).`);- } catch (e) {- remaining.push(id);- d.logError(- `could not revoke a previous harness token (${e instanceof Error ? e.message : String(e)}) — ` +- `revoke it manually: gbrain auth revoke with the id flag (${id}); kept on the receipt.`,- );- }- }- if (remaining.length > 0) receipt.token.previous_ids = remaining;- else delete receipt.token.previous_ids;- save();- } else if (receipt.token.previous_ids?.length) {- d.logError(- `${receipt.token.previous_ids.length} previous harness token(s) NOT revoked (wiring incomplete or smoke failed) — ` +- 'old clients keep working; re-run `gbrain bootstrap harness` to converge.',- );- }+ // #6743: per-id leave-then-revoke; a revoked credential's enrollment is inert (logic in harness-cleanup.ts).+ const cleanup = await convergeHarnessCleanup({ receipt, prior, current: currentSkills, wired: allConfirmed && smokeOk, skillsReady,+ memoryOnly: skillsPolicy === 'memory-only', leave: leaveHarnessSkills, save }, d);// 11. Degradation + skew honesty.if (health.engine === 'postgres') {@@ -2021,6 +1994,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): PJSON.stringify({schema_version: 1, ...harnessOutcomeFields(pendingFix, allConfirmed && smokeOk),+ ...cleanupOutcomeFields(cleanup, !pendingFix && allConfirmed && smokeOk, flags.raw),url,engine: health.engine ?? null,serve_version: health.version ?? null,@@ -2038,7 +2012,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P),);}- return pendingFix ? HARNESS_PENDING_VERIFY_EXIT_CODE : allConfirmed && smokeOk ? 0 : 1;+ return pendingFix ? HARNESS_PENDING_VERIFY_EXIT_CODE : allConfirmed && smokeOk ? (cleanup.length ? HARNESS_CLEANUP_PENDING_EXIT_CODE : 0) : 1;}// ── Remove [C9/F2/C8] ───────────────────────────────────────────────────────@@ -2491,6 +2465,21 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):});const instructionsOk = instructionsProbes.every((p) => p.probe === 'installed');const hookCarriers = harnessHookCarrierStatus(receipt, d);+ // Cron contract: 0 means ALL-VERIFIED (or honest degrades only) — a+ // crashed apply's pending/failed targets are NOT success just because+ // /health answers (ship-review P2); an unconverged rotation or shared-skills+ // cleanup exits bootstrap_cleanup_pending (#6743). The+ // token-unrecoverable honest degrade stays 0 per the documented contract.+ const allTargetsConfirmed = liveTargets.every((t) => t.state === 'confirmed');+ // Half-removed state (red-team CRITICAL): --remove under a live PGLite+ // serve strips every host target but defers the revoke, leaving a+ // zero-target receipt whose minted token is STILL ACTIVE. Vacuous+ // every() would read that as green forever.+ const removalPending = receipt.targets.length === 0 && ((receipt.token.minted && receipt.token.id !== undefined) ||+ Object.values(receipt.harness_tokens ?? {}).some(t => t.minted && t.id) ||+ (receipt.shared_skills ?? []).some(entry => !entry.status.startsWith('left')));+ const statusOk = health.ok && tokenVerified !== false && allTargetsConfirmed && !removalPending && instructionsOk && !receipt.verify_pending;+ const cleanup = await harnessCleanupReport(receipt, d.tokenStates);if (flags.json) {d.log(@@ -2514,6 +2503,7 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):...(hookCarriers.length > 0 ? { hook_carriers: hookCarriers } : {}),pending_previous_tokens: receipt.token.previous_ids ?? [],...(receipt.verify_pending ? { status: 'partial', verify_pending: receipt.verify_pending } : {}),+ ...cleanupOutcomeFields(cleanup, statusOk, null),receipt_path: harnessReceiptPath(d.gbrainHome),},null,@@ -2543,37 +2533,20 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):d.log(` hook entries in ${c.path}: ${c.state === 'ok' ? `${c.ours} gbrain (${c.unmarked} without the _gbrain marker)` : c.state}` +`${c.duplicates.length ? `; duplicated: ${c.duplicates.join(', ')}` : ''}${c.unowned.length ? `; not this install's (left in place): ${c.unowned.join(', ')}` : ''}`);}- if (receipt.token.previous_ids?.length) {- d.log(` pending: ${receipt.token.previous_ids.length} previous token(s) await revocation (re-run to converge): ${receipt.token.previous_ids.join(', ')}`);- }+ for (const line of cleanupLines(cleanup)) d.log(line);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).');}if (skew) d.log(`note: ${skew}`);}- // Cron contract: 0 means ALL-VERIFIED (or honest degrades only) — a- // crashed apply's pending/failed targets and an unconverged rotation are- // NOT success just because /health answers (ship-review P2). The- // token-unrecoverable honest degrade stays 0 per the documented contract.- const allTargetsConfirmed = liveTargets.every((t) => t.state === 'confirmed');- const rotationConverged = (receipt.token.previous_ids?.length ?? 0) === 0;- // Half-removed state (red-team CRITICAL): --remove under a live PGLite- // serve strips every host target but defers the revoke, leaving a- // zero-target receipt whose minted token is STILL ACTIVE. Vacuous- // every() would read that as green forever.- const removalPending = receipt.targets.length === 0 && ((receipt.token.minted && receipt.token.id !== undefined) ||- Object.values(receipt.harness_tokens ?? {}).some(t => t.minted && t.id) ||- (receipt.shared_skills ?? []).some(entry => !entry.status.startsWith('left')));if (removalPending) {d.logError(`removal pending: host wiring is gone but token revocation or shared-skills cleanup is unfinished — ` +'stop the serve and re-run `gbrain bootstrap harness --remove`, or revoke it with `gbrain auth revoke` and the id flag.',);}- return health.ok && tokenVerified !== false && allTargetsConfirmed && rotationConverged && !removalPending && instructionsOk && !receipt.verify_pending- ? 0- : 1;+ return statusOk ? (cleanup.length ? HARNESS_CLEANUP_PENDING_EXIT_CODE : 0) : 1;}// ── Home preflight ──────────────────────────────────────────────────────────diff --git a/src/core/exit-codes.ts b/src/core/exit-codes.tsindex 09b0da0ef1..3be802a65d 100644--- a/src/core/exit-codes.ts+++ b/src/core/exit-codes.ts@@ -6,6 +6,7 @@* 0 ok · 1 failed (class/retryable in JSON) · 2 usage / invalid input ·* 3 confirmation_required (its ONLY meaning) · 10 write pending ·* 11 resumable budget stop · 13 harness wired, verification pending ·+ * 14 harness wired, shared-skills/token cleanup pending ·* 69 serve exited unhealthy · 75 migration* lock held · 124 timeout · 130 interrupted. `test/exit-codes.test.ts` enumerates every literal* exit 3 in src/ so a new one cannot reuse it.@@ -53,6 +54,15 @@ export const BUDGET_STOP_EXIT_CODE = 11;*/export const HARNESS_PENDING_VERIFY_EXIT_CODE = 13;+/**+ * #6743: `gbrain bootstrap harness` wired and verified the harness, but the+ * cleanup of earlier shared-skills enrollments or carried token ids is still+ * pending (`bootstrap_cleanup_pending`). The JSON lists each id's state; its+ * `fix` re-runs the command when every id can converge, or names the owner's+ * revoke or leave step when one cannot.+ */+export const HARNESS_CLEANUP_PENDING_EXIT_CODE = 14;+/*** #6543: `gbrain serve` exited on its own because its persistence consumer* reported `restart_required` continuously for `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS`diff --git a/test/bootstrap-doctor-checks.test.ts b/test/bootstrap-doctor-checks.test.tsindex add649ff68..98b06012ca 100644--- a/test/bootstrap-doctor-checks.test.ts+++ b/test/bootstrap-doctor-checks.test.ts@@ -244,7 +244,8 @@ describe('bootstrap_harness_health (#4043)', () => {const checks = await run(parent);const c = byName(checks, 'bootstrap_harness_health');expect(c?.status).toBe('fail');- expect(c?.message).toMatch(/never revoked/);+ // #6743: per-id wording (this id has no enrollment to leave, so revoking it is safe).+ expect(c?.message).toContain('44444444-4444-4444-4444-444444444444: status unknown; no enrollment holds it; a re-run revokes it (or `gbrain auth revoke` by id)');}, T);test('healthy receipt + unreachable serve → WARN (normal transient), never fail', async () => {diff --git a/test/bootstrap-harness-cleanup-6743.test.ts b/test/bootstrap-harness-cleanup-6743.test.tsnew file mode 100644index 0000000000..6db19548de--- /dev/null+++ b/test/bootstrap-harness-cleanup-6743.test.ts@@ -0,0 +1,218 @@+/**+ * #6743: bootstrap's shared-skills cleanup converges after a cleanup+ * credential was revoked before its enrollment left.+ *+ * Real adapter files: each enrollment installs its owned router and native+ * router through installSharedSkillsConnection; the host is a synthetic tool+ * caller that refuses a revoked bearer the way the HTTP serve does (an auth+ * failure, not an OperationError). No paid model calls, no database.+ */+import { afterEach, expect, test } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { randomUUID } from 'node:crypto';+import { applyHarness, parseHarnessArgs, statusHarness, type HarnessDeps } from '../src/core/bootstrap/harness.ts';+import { readHarnessReceiptState, type HarnessReceipt } from '../src/core/bootstrap/format.ts';+import { installSharedSkillsConnection } from '../src/core/harness/shared-skills.ts';+import type { SharedSkillsToolCaller } from '../src/core/shared-skills/adapter.ts';+import * as exitCodes from '../src/core/exit-codes.ts';+import { bootstrapDoctorChecks } from '../src/commands/doctor.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { withEnv } from './helpers/with-env.ts';++const roots: string[] = [];+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });+const HARNESS_CLEANUP_PENDING_EXIT_CODE = (exitCodes as Record<string, number>).HARNESS_CLEANUP_PENDING_EXIT_CODE;+const flags = (...args: string[]) => parseHarnessArgs(['--yes', '--no-hooks', '--harness', 'codex', ...args]);++function fixture() {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-cleanup-6743-'));+ roots.push(root);+ const home = join(root, '.gbrain');+ const brain = randomUUID();+ const tokens = new Map<string, { token: string; revoked: boolean }>();+ const mints: Array<{ id: string; token: string }> = [];+ const events: string[] = [];+ const output: string[] = [];+ const memberships = new Map<string, { id: string; active: boolean }>();+ let leaveOutage = false;+ const live = (token: string | undefined) => [...tokens.values()].some(t => t.token === token && !t.revoked);+ const states = (ids: string[]) => Object.fromEntries(ids.map(id => [id, !tokens.has(id) ? 'missing' : tokens.get(id)!.revoked ? 'revoked' : 'active'] as const));+ let codex: string | null = null;+ const deps: HarnessDeps = {+ gbrainHome: home, isTTY: false, gbrainBin: '/synthetic/gbrain',+ userSettingsPath: join(root, 'claude', 'settings.json'), codexConfig: join(root, 'codex', 'config.toml'),+ opencodeConfig: join(root, 'opencode', 'opencode.json'), loadFileConfig: () => null,+ nativeSkillsDir: host => join(root, host, 'skills'),+ detectClaude: () => true, detectCodex: () => true, detectOpencode: () => true,+ resolveHookSource: async explicit => ({ source_id: explicit ?? 'workspace', grant: explicit ? [explicit] : ['workspace'] }),+ fetchFn: (async () => new Response(JSON.stringify({ status: 'ok', engine: 'postgres', version: '0.51.7.0' }))) as unknown as typeof fetch,+ probeIdentity: async (_url, token) => live(token) ? { ok: true, identity: 'fixture brain' } : { ok: false, reason: 'auth', message: 'denied' },+ mint: async options => {+ const result = { ...options, id: randomUUID(), token: `gbrain_${randomUUID().replaceAll('-', '').repeat(2)}` };+ tokens.set(result.id, { token: result.token, revoked: false });+ mints.push(result);+ events.push(`mint:${result.id}`);+ return result;+ },+ revokeById: async id => {+ events.push(`revoke:${id}`);+ const row = tokens.get(id);+ if (!row || row.revoked) return false;+ row.revoked = true;+ return true;+ },+ tokenStates: async ids => states(ids),+ pgliteLiveServe: () => false,+ runner: async () => ({ code: 0, stdout: codex ?? '', stderr: '' }),+ installSharedSkills: async (credentials, options) => {+ const principal = credentials.access_token;+ const call: SharedSkillsToolCaller = async <T>(name: string): Promise<T> => {+ if (!live(principal)) throw new Error('401 unauthorized: invalid or revoked token');+ if (name === 'leave_brain' && leaveOutage) throw new Error('synthetic leave outage');+ if (!memberships.has(principal!)) memberships.set(principal!, { id: randomUUID(), active: false });+ const member = memberships.get(principal!)!;+ if (name === 'leave_brain') { member.active = false; events.push(`leave:${principal}`); return { status: 'left' } as T; }+ if (name === 'join_brain') member.active = true;+ if (!member.active) throw new Error('membership_inactive');+ return { schema_version: 2, complete: true, status: 'catalog_visible', brain_id: brain, installation_id: member.id,+ enrollment_epoch: 1, view_token: 'fixture-view', batch_token: 'fixture-batch', sequence: 1, skills: [], blocked_skills: [],+ delivery: { native: 'unverified', freshness: 'session_refresh' } } as T;+ };+ return installSharedSkillsConnection(credentials, { ...options, toolCaller: options.toolCaller ?? call });+ },+ log: text => output.push(text), logError: text => output.push(text),+ };+ const receipt = (): HarnessReceipt => {+ const state = readHarnessReceiptState(home);+ if (state.state !== 'ok') throw new Error('missing fixture receipt');+ return state.receipt;+ };+ return {+ root, home, deps, mints, events, output, tokens, receipt, states,+ leaveOutage: (value = true) => { leaveOutage = value; },+ revokeByHand: (id: string) => { tokens.get(id)!.revoked = true; },+ lastJson: () => JSON.parse(output.at(-1)!),+ };+}++const adapterReceipt = (entryRoot: string) => JSON.parse(readFileSync(join(entryRoot, 'shared-skills', 'receipt.json'), 'utf8'));++/** Two old enrollments stuck on a leave outage, the first with a user edit to its owned router. */+async function twoPendingEnrollments(f: ReturnType<typeof fixture>) {+ expect(await applyHarness(flags(), f.deps)).toBe(0);+ const a = f.receipt().shared_skills![0];+ const ownedRouter = join(a.root, 'shared-skills', 'router', 'SKILL.md');+ expect(existsSync(ownedRouter)).toBe(true);+ writeFileSync(ownedRouter, '# User edited router');+ const nativeRouter = adapterReceipt(a.root).native_router_path as string;+ expect(existsSync(nativeRouter)).toBe(true);+ f.leaveOutage();+ expect(await applyHarness(flags(), f.deps)).toBe(HARNESS_CLEANUP_PENDING_EXIT_CODE);+ expect(await applyHarness(flags('--json'), f.deps)).toBe(HARNESS_CLEANUP_PENDING_EXIT_CODE);+ return { a, ownedRouter, nativeRouter };+}++test('exit code 14 is bootstrap_cleanup_pending', () => {+ expect(HARNESS_CLEANUP_PENDING_EXIT_CODE).toBe(14);+});++test('a two-entry receipt (one credential revoked, one valid) converges on a rerun and keeps the user edit', async () => {+ const f = fixture();+ const { a, ownedRouter, nativeRouter } = await twoPendingEnrollments(f);+ const pending = f.lastJson();+ expect(pending.status).toBe('cleanup_pending');+ expect(pending.code).toBe('bootstrap_cleanup_pending');+ expect(pending.cleanup.map((i: { token_id: string; state: string; token: string; converges: boolean }) => [i.token_id, i.state, i.token, i.converges]))+ .toEqual([[f.mints[0].id, 'leave_pending', 'active', true], [f.mints[1].id, 'leave_pending', 'active', true]]);+ expect(pending.fix.next).toBe('run');+ expect(f.receipt().token.previous_ids).toEqual([f.mints[0].id, f.mints[1].id]);++ // The old doctor advice: revoke first. Its enrollment can no longer leave remotely.+ f.revokeByHand(f.mints[0].id);+ f.leaveOutage(false);++ // Fixture run of the rendered fix: the argv, then its verify.+ expect(pending.fix.argv.slice(0, 3)).toEqual(['gbrain', 'bootstrap', 'harness']);+ expect(pending.fix.argv).not.toContain('--json');+ expect(await applyHarness(parseHarnessArgs([...pending.fix.argv.slice(3), '--json']), f.deps)).toBe(0);+ const done = f.lastJson();+ expect(done.status).toBe('ok');+ expect(done.cleanup).toBeUndefined();+ const r = f.receipt();+ expect(r.token.previous_ids).toBeUndefined();+ const revokedEntry = r.shared_skills!.find(e => e.token_id === f.mints[0].id)!;+ expect(revokedEntry.status).toBe('left_with_retained_files');+ expect(revokedEntry.reason).toBe('credential_revoked');+ expect(r.shared_skills!.filter(e => !e.status.startsWith('left')).map(e => e.token_id)).toEqual([f.mints[3].id]);+ // Local cleanup still ran for the revoked enrollment: receipt deactivated, native router removed, credential dropped, edit kept.+ expect(adapterReceipt(a.root).status).toBe('left_with_retained_files');+ expect(existsSync(nativeRouter)).toBe(false);+ expect(readFileSync(ownedRouter, 'utf8')).toBe('# User edited router');+ expect(existsSync(join(a.root, 'credentials.json'))).toBe(false);+ // The valid ones left before their tokens were revoked; the revoked one was only cleared.+ for (const m of [f.mints[1], f.mints[2]]) expect(f.events.indexOf(`leave:${m.token}`)).toBeLessThan(f.events.indexOf(`revoke:${m.id}`));+ expect(f.events).not.toContain(`leave:${f.mints[0].token}`);+ expect(f.states([f.mints[0].id, f.mints[1].id, f.mints[2].id, f.mints[3].id]))+ .toEqual({ [f.mints[0].id]: 'revoked', [f.mints[1].id]: 'revoked', [f.mints[2].id]: 'revoked', [f.mints[3].id]: 'active' });++ expect(await statusHarness(parseHarnessArgs(pending.fix.verify.argv.slice(3)), f.deps)).toBe(0);+ const status = f.lastJson();+ expect(status.pending_previous_tokens).toEqual([]);+ expect(status.cleanup).toBeUndefined();+});++test('status and doctor tell a revoked credential awaiting cleanup apart from an active one', async () => {+ const f = fixture();+ await twoPendingEnrollments(f);+ f.revokeByHand(f.mints[0].id);+ expect(await statusHarness(flags('--status', '--json'), f.deps)).toBe(HARNESS_CLEANUP_PENDING_EXIT_CODE);+ const status = f.lastJson();+ expect(status.status).toBe('cleanup_pending');+ expect(status.code).toBe('bootstrap_cleanup_pending');+ expect(status.cleanup.map((i: { token_id: string; token: string }) => [i.token_id, i.token]))+ .toEqual([[f.mints[0].id, 'revoked'], [f.mints[1].id, 'active']]);++ const engine = {+ executeRaw: async (sql: string, params: unknown[] = []) => sql.includes('access_tokens')+ ? (params[0] as string[]).filter(id => f.tokens.has(id)).map(id => ({ id, revoked: f.tokens.get(id)!.revoked }))+ : [],+ getConfig: async () => null,+ } as unknown as BrainEngine;+ const checks = await withEnv({ GBRAIN_HOME: f.root }, () => bootstrapDoctorChecks(engine));+ const health = checks.find(c => c.name === 'bootstrap_harness_health')!;+ expect(health.status).toBe('fail');+ expect(health.message).toContain(`${f.mints[0].id}: revoked; enrollment cleanup pending`);+ expect(health.message).toContain(`${f.mints[1].id}: active; enrollment leave pending`);+ expect(health.message).toContain('Leave before revoke');+ expect(health.message).not.toContain('never revoked');+});++test('a cleanup no rerun can finish names the owner revoke step and carries no new ids', async () => {+ const f = fixture();+ expect(await applyHarness(flags(), f.deps)).toBe(0);+ const a = f.receipt().shared_skills![0];+ f.leaveOutage();+ expect(await applyHarness(flags(), f.deps)).toBe(HARNESS_CLEANUP_PENDING_EXIT_CODE);+ f.leaveOutage(false);+ rmSync(join(a.root, 'credentials.json'));+ expect(await applyHarness(flags('--json'), f.deps)).toBe(HARNESS_CLEANUP_PENDING_EXIT_CODE);+ const stuck = f.lastJson();+ expect(stuck.cleanup).toEqual([expect.objectContaining({ token_id: f.mints[0].id, state: 'credential_unreadable', token: 'active', converges: false })]);+ expect(stuck.fix.next).toBe('tell_user_to_run');+ expect(stuck.fix.argv).toEqual(['gbrain', 'auth', 'revoke', '--id', f.mints[0].id]);+ expect(stuck.fix.user_message).toContain('credentials.json');+ // The enrollment rotated out by that run left and its token was revoked: the list does not grow.+ expect(f.receipt().token.previous_ids).toEqual([f.mints[0].id]);+ expect(await applyHarness(flags(), f.deps)).toBe(HARNESS_CLEANUP_PENDING_EXIT_CODE);+ expect(f.receipt().token.previous_ids).toEqual([f.mints[0].id]);++ // The owner runs the step (gbrain auth revoke by id), then the re-run converges.+ expect(await f.deps.revokeById!(stuck.fix.argv[4])).toBe(true);+ expect(await applyHarness(flags(), f.deps)).toBe(0);+ expect(f.receipt().token.previous_ids).toBeUndefined();+ expect(f.receipt().shared_skills!.some(e => e.token_id === f.mints[0].id)).toBe(false);+ expect(f.output.join('\n')).toContain(`token ${f.mints[0].id} is already revoked, so its enrollment cannot leave remotely and is inert`);+ expect(await statusHarness(parseHarnessArgs(stuck.fix.verify.argv.slice(3)), f.deps)).toBe(0);+});diff --git a/test/bootstrap-shared-skills.test.ts b/test/bootstrap-shared-skills.test.tsindex 43b12fd11b..0e0adff9b2 100644--- a/test/bootstrap-shared-skills.test.ts+++ b/test/bootstrap-shared-skills.test.ts@@ -8,6 +8,7 @@ import { readHarnessReceiptState, writeHarnessReceipt, type HarnessReceipt } froimport { installSharedSkillsConnection } from '../src/core/harness/shared-skills.ts';import type { SharedSkillsToolCaller } from '../src/core/shared-skills/adapter.ts';import { operations } from '../src/core/operations.ts';+import { HARNESS_CLEANUP_PENDING_EXIT_CODE } from '../src/core/exit-codes.ts';const roots: string[] = [];afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });@@ -175,7 +176,8 @@ test('follow failure stays pending without breaking memory or revoking the priorconst f = fixture();expect(await applyHarness(flags(), f.deps)).toBe(0);f.failJoin();- expect(await applyHarness(flags(), f.deps)).toBe(0);+ // #6743: the retained prior enrollment is pending cleanup, so the run no longer reports plain success.+ expect(await applyHarness(flags(), f.deps)).toBe(HARNESS_CLEANUP_PENDING_EXIT_CODE);expect(f.receipt().shared_skills?.at(-1)?.status).toBe('pending');expect(f.memberships.get(f.mints[0].token)?.active).toBe(true);expect(f.revoked).toEqual([]);