Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(repair): gbrain repair stuck-recovery resolves a write recovery blocked on unexpected file bytes (#6650)

garrytan5d7cf7f0bce5
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index 5e445ebea8..9da21dea00 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `take-supersession` (#5886 relinks takes supersession chains from journal, stored-pointer or forced fence-structure evidence; ambiguous pages are reported with the manual edit, never rewritten; `src/core/repair/take-supersession.ts`), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `gbrain repair fences [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff] [--no-llm] [--max-usd <n>] [--apply [--expect <hash>]]` repairs malformed facts and takes fences (#6188, `src/core/repair/fences.ts`). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs; flags a kind does not take name the kinds that do (`--only`/`--skip`/`--diff`: frontmatter, fences; `--slug`: fences; `--yes`: frontmatter); `--expect` is accepted for explicit-only and preview-bound kinds, `--include-ambiguous` for explicit-only kinds; `--max-usd <n>` and `--no-llm` only for `spends: 'llm'` kinds (a non-negative USD amount that only lowers the kind's cap), and on any other kind `--max-usd` names the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>` (hash from `doctor --remediation-plan --json`), as `--max-cost` always does. Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. An apply with a report hook prints `repaired N; still waiting: <reason>=<count>` (never a repair count it did not make) and a partial scan; a stop prints its `fix` command and the consent it asks for. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost (plus, for a `spends: 'llm'` kind, the paid-model estimate or spend and what is left under today's cap) and capacity, and the apply command; `--json` has the same fields. The dry run lists the kinds that may queue paid embeddings and, when a result carries `cost.llm_usd`, `Kinds that may call a paid model` with the summed estimate and the cap left. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`. An item whose apply refuses `invalid_params` or `source_changed` (`REPAIR_ITEM_FAILURE_CODES` in `src/core/repair/core.ts`) is a per-item verdict: `runRepair` records it in `result.failed[]` (`item`, `source_id`, `slug`, `reason`, redacted `message`, `retry: 'next_full_scan'`) plus a `failed` outcome, writes no cursor for it and continues; a later success moves the cursor past it, so a resumed run skips it and the next full scan retries it (the `revision_conflict` rule). The command prints `failed N`, each `FAILED <item> (<reason>)` line and the full-scan command, and `repairExitVerdict` exits 1 on any failure or stop. Consumers never read failures as an all-clear: `runRepairSteps` (`RepairStepResult.failed`, status `failed`), the content lane (`ContentLaneResult.failed[]`, exit 1), and the `fence_repair` / `content_repair` phases (`warn`). Test: `test/repair-apply-continue-6459.test.ts`.
+- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `take-supersession` (#5886 relinks takes supersession chains from journal, stored-pointer or forced fence-structure evidence; ambiguous pages are reported with the manual edit, never rewritten; `src/core/repair/take-supersession.ts`), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `gbrain repair fences [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff] [--no-llm] [--max-usd <n>] [--apply [--expect <hash>]]` repairs malformed facts and takes fences (#6188, `src/core/repair/fences.ts`). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs; flags a kind does not take name the kinds that do (`--only`/`--skip`/`--diff`: frontmatter, fences; `--slug`: fences; `--yes`: frontmatter); `--expect` is accepted for explicit-only and preview-bound kinds, `--include-ambiguous` for explicit-only kinds; `--max-usd <n>` and `--no-llm` only for `spends: 'llm'` kinds (a non-negative USD amount that only lowers the kind's cap), and on any other kind `--max-usd` names the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>` (hash from `doctor --remediation-plan --json`), as `--max-cost` always does. Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. An apply with a report hook prints `repaired N; still waiting: <reason>=<count>` (never a repair count it did not make) and a partial scan; a stop prints its `fix` command and the consent it asks for. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost (plus, for a `spends: 'llm'` kind, the paid-model estimate or spend and what is left under today's cap) and capacity, and the apply command; `--json` has the same fields. The dry run lists the kinds that may queue paid embeddings and, when a result carries `cost.llm_usd`, `Kinds that may call a paid model` with the summed estimate and the cap left. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`. An item whose apply refuses `invalid_params` or `source_changed` (`REPAIR_ITEM_FAILURE_CODES` in `src/core/repair/core.ts`) is a per-item verdict: `runRepair` records it in `result.failed[]` (`item`, `source_id`, `slug`, `reason`, redacted `message`, `retry: 'next_full_scan'`) plus a `failed` outcome, writes no cursor for it and continues; a later success moves the cursor past it, so a resumed run skips it and the next full scan retries it (the `revision_conflict` rule). The command prints `failed N`, each `FAILED <item> (<reason>)` line and the full-scan command, and `repairExitVerdict` exits 1 on any failure or stop. Consumers never read failures as an all-clear: `runRepairSteps` (`RepairStepResult.failed`, status `failed`), the content lane (`ContentLaneResult.failed[]`, exit 1), and the `fence_repair` / `content_repair` phases (`warn`). Test: `test/repair-apply-continue-6459.test.ts`. `gbrain repair stuck-recovery` takes `--request-id <uuid>` and, with `--apply --expect <hash> --yes`, `--keep prior|disk` (both refused for other kinds); the consent argv carries them.
- `src/commands/repair-content.ts` — `gbrain repair content [--source <id>] [--only <path>]... [--skip <path>]... [--no-llm] [--max-usd <n>] [--diff] [--apply [--expect <h1>[,<h2>]]] [--json]` (#6377): the content-repair lane as one command. `content` is parsed by `repair.ts`'s strict flag grammar like a kind (`CONTENT_LANE`; `--only`/`--skip`/`--diff`, `--no-llm`, `--max-usd` and `--expect` are accepted for it, `--slug`, `--yes`, `--include-ambiguous` and `--all` refuse) and dispatched before the kind check; it is a lane, not a `RepairKind`: no registry entry, no cursor of its own, listed under "Lanes:" in `REPAIR_HELP`. `runRepairContentCommand` resolves the scope, runs `runContentLane` and prints each kind's result through `renderRepairResult` plus a lane line (spend, allowance left, each kind's hash, every stop, the apply command); `--json` prints `{ lane, scope, mode, kinds, results[] (with `paid`), preview_hashes, cost, stopped, paid_kinds, apply_command }`. A kind's stop sets exit verdict 1; a wrong `--expect` count is `invalid_params` with the preview as its fix. Test: `test/repair-content.test.ts`.
- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--yes] [--max-usd USD] [--repo PATH]`. W4.5: re-embedding is paid, so `runReindex(engine, args, { authorized?, interactive? })` calls `requireReindexConsent` (`src/core/reindex-consent.ts`) after the dry-run return and before the managed dispatch for every caller unless `--no-embed` or `authorized` (the upgrade path's TTY yes, the job handler's stored spend record); `src/cli/commands/reindex.ts` renders the exit-3 consent refusal and `cost_cap_exceeded`. The approved finite cap runs the inline pass (and the managed dispatch) under a `BudgetTracker` via `withBudgetTracker`; once it is exhausted (an import swallows the refused embedding) the loop stops at the next page and `reportBudgetStop` exits 1 with `budget_exhausted` in `--json`. `countPending` is exported for `jobs submit reindex` and the mode-switch prompt. The writer pool is sized once from the run's page target (pending, capped by `--limit`) through `resolveWorkersWithClamp`, so Postgres runs over 100 pages default to `DEFAULT_PARALLEL_WORKERS` while PGLite stays at one; `--workers` overrides and the used count is reported as `workers` in the result and JSON (pinned by `test/e2e/reindex-auto-workers-5181.test.ts`). Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`. #5377: on a managed brain (`managedPersistenceEnabled`) the `--markdown` sweep delegates to the projection repairs through `runRepair` (`safe-chunks`, then `contextual-mode` unless `--no-embed`), so it never takes the legacy writer and changes no page revision, journal request or canonical file; `--type` is refused there with the repair commands, and pages the repairs cannot rebuild are reported as `unsupported_pages`. The doctor, upgrade and post-upgrade hints that name `gbrain reindex --markdown` therefore work on both brain modes (C-NEW-5).
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index 33a343f356..354c5f9e67 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -1,8 +1,9 @@
-# Key files: Core Persistence (request indexes and fault seams)
+# Key files: Core Persistence (request indexes, fault seams, stuck recovery)
[Subsystem index](../KEY_FILES.md) · [Core Persistence](core-persistence.md) · [continued](core-persistence-continued.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-The online-built request-table indexes (the managed sync checkpoint pair, the page purge's slug index), the checkpoint validation they serve, and the named fault seams the persistence gate and the purge tests inject at.
+The online-built request-table indexes (the managed sync checkpoint pair, the page purge's slug index), the checkpoint validation they serve, the named fault seams the persistence gate and the purge tests inject at, and the stuck-recovery resolution (`gbrain repair stuck-recovery`) that uses them.
- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.
-- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`) `consumer:prepared` (between preparing a claimed request and publishing it) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts` and the #6511 tests.
+- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`) `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts` and the #6511 tests.
+- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk --yes`, a non-interactive apply without `--yes` exits 3). `scanStuckRecoveries` (owner host only, else `owner_unavailable` for a named source) reads the source's queued head blocker (`readHeadBlockers`; its `request_recovery` ids select the records) and every non-terminal recovery record on the worktree blocked on `unexpected_file_bytes` or whose file matches neither recorded version; a v2 shared-skill bundle record refuses `recovery_bundle_unsupported` (catalogue entry, `docs/guides/repair.md#recovery-bundle-unsupported`), a withdrawal-mirror effect recovery on the worktree is listed in `refused` (residual `effect_recovery`; named with `--request-id` it refuses `recovery_effect_unsupported`), a blocked terminal request is listed in `refused` (residual `terminal_refused`; named with `--request-id` it refuses `recovery_choice_refused`, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior, disk and unified-diff files 0600 under `~/.gbrain/backups/stuck-recovery/<request>/<digest>/` (a private directory outside every checkout) and prints the `diff -u` command. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page's `knowledge_revision`. `resolveStuckRecovery` runs under `acquireWorktree` with a bounded wait (10 s, then `writer_lock_unavailable`; so the resident recovery pass returns unchanged), re-verifies the digest (`preview_changed`) and journals in `op_checkpoints` op `stuck-recovery-resolution` keyed `<request row id>:<preview hash>` (exempt from the checkpoint purge; the finished row is the audit entry): `backed_up` (disk and prior bytes durable, always), then `written` (`--keep prior`: `upgradeRecoveryStaging` reserves an older record's restoration stage within the recovery budget, `queue_capacity` otherwise, then the prior bytes are published through `publishPersistenceFile` at that stage after `cleanupRecoveryStaging`, an absent prior unlinked) or `abandoned` (`--keep disk`, #6640's drop: `completeWrite` ends the live request `conflict` `source_changed`, or `finishUnpublishedFailure` with its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path's `clearResolvedRecovery`), then `recoverPublication(…, alreadyLocked)` finishes by its unchanged rule and the journal records `done` with the result. A step refuses `unexpected_file_bytes` when the file changed again; a different `--keep` for the same hash refuses `idempotency_conflict`; an identical apply after `done` replays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reports `finished_by: another_pass`. `--keep prior` on a request with no recorded failure requeues it (the accepted write publishes again). `--keep disk` hands off to `gbrain sources reconcile <source> <slug> --brain host --preview` and never reports the page repaired. Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`.
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 0df90dd329..cd249121b8 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `RemoteMcpError`, `extractResponseMeta` and `ignoredRemoteParams` live in `src/core/remote-mcp-error.ts` (re-exported here) so local CLI paths can name them without loading the MCP SDK; the CLI imports this module only on a routed call. `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser. A status-only host's 503 `serve_status_only` envelope from OAuth discovery or `/token` (`status_only` on the `remote-mcp-probe.ts` failure, with `retry_after_s`) becomes `RemoteMcpError` detail (`code`, `reason`, `why`, `fix`), which the CLI renders through the agent envelope and the thin-client doctor reports on its check (`test/remote-mcp-status-only.test.ts`).
-- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests, `sync-import-provenance` rows, the blocked-cursor conversion log, the #6188 fence census (`fence-candidate`, `fence-scan`) and paid fence-repair attempt claims and memos (`fence-repair-attempt`) of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests never expire.
+- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests, `sync-import-provenance` rows, the blocked-cursor conversion log, the #6188 fence census (`fence-candidate`, `fence-scan`) and paid fence-repair attempt claims and memos (`fence-repair-attempt`) of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests and `stuck-recovery-resolution` audit entries (`gbrain repair stuck-recovery`) never expire.
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms`, `repair extractor-facts` and the other preview-bound repair kinds such as `repair ontology-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`). #6351: `loadApprovedSet` takes an optional lazy `emptyHash` (the hash a preview of the same selection prints when it finds nothing, from current state including source incarnations); with no saved row and a matching hash it returns an empty set, so the apply command an empty preview prints succeeds while a changed incarnation still refuses `preview_changed`. The eight preview-bound repair kinds without a local `emptyPlanHash` (stale-atoms, captured-facts, conversation-labels, extractor-facts, failed-writes, frontmatter, loop-facts, ontology-facts) pass it. Pinned by `test/repair-empty-preview-apply.test.ts`.
- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `abortOnCleanupPass(name)` wraps that for child work: it returns `{ signal, release }`, the signal aborts when the cleanup pass runs (sync's `git pull` uses it), and `release` deregisters it. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/process-cleanup.test.ts` and `test/e2e/supervisor-stop-drain-5062.test.ts`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 9097f22910..7909314250 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -9,7 +9,7 @@ fixes those and the other kinds listed in
[What each kind fixes](#what-each-kind-fixes). Every run is a preview unless
you pass `--apply`.
The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `extractor-facts`,
-`captured-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter` and `managed-sync-orphans`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
+`captured-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans` and `stuck-recovery`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and
`gbrain doctor --remediate --yes --include-repairs --expect <plan_hash>` runs them under a budget
(see [Run repairs through doctor](#run-repairs-through-doctor)).
@@ -134,6 +134,7 @@ work behind exits 0, so scripts should also check `results[].complete`.
| `connector-checkpoints` | `connector_checkpoints` | Deletes managed connector checkpoint rows and retry pointers that no registered connector source can load and that are older than 7 days. They accumulate after a content setting such as `g_history_days` changes, or when a connector host older than v0.60.11.0 runs during an upgrade. Cleanup only: it never copies or re-keys a checkpoint, takes no journal admission and runs brain-wide (`--source` does not narrow it). | Rows a queued or running connector write, or a connector's recorded pending set, still references. |
| `orphan-bindings` | `orphan_persistence_bindings` | Deletes persistence source bindings whose source was removed, or that belong to an earlier incarnation of a source re-added under the same id. `gbrain sources remove` and `gbrain sources purge` delete the binding; one an older gbrain left behind makes the re-added source read as claimed, so every `gbrain sync --source <id>` fails with `writer_coordinator_required`. Bookkeeping only: no journal admission, no page or file changes, and it runs brain-wide (`--source` does not narrow it). See [orphan bindings](#orphan-bindings). | A binding that a queued, running or recovering write request of the same source incarnation still references. |
| `managed-sync-orphans` | `sync_failures` | Explicit-only, preview-bound. Retires managed sync bookkeeping nothing current can resume or clear: a `managed-sync-failure` row whose cursor key has no cursor, and an unfinished `managed-sync` cursor recorded by a principal that is no longer an active local writer (or a pre-options cursor a later run superseded) whose pending request is terminal. `op_checkpoints` rows only; no journal admission, no page or file changes. The preview prints a hash; `--apply --expect <hash>` retires exactly that set. See [managed sync orphans](#managed-sync-orphans). | An unfinished cursor whose pending request is still queued, running or recovering, or one the live writer can resume with its recorded options (doctor prints that sync command). |
+| `stuck-recovery` | none (`gbrain sources writer status` shows the request `recovering` with `unexpected_file_bytes`) | Explicit-only, preview-bound, destructive consent. Resolves a live page publication recovery whose file matches neither its recorded prior nor its published bytes, which stops every write on its worktree. The preview lists each blocked file with both fingerprints and writes a private diff; `--apply --expect <hash> --keep prior\|disk --yes` backs up both versions, then restores the prior (the write publishes again) or keeps the edit and abandons the write. See [stuck recovery](#stuck-recovery). | A terminal request with its recovery still set (listed as refused, `recovery_choice_refused`), a withdrawal-mirror effect recovery (listed as refused, `recovery_effect_unsupported`), a shared-skill bundle recovery (`recovery_bundle_unsupported`), a recovery blocked on staging bytes, and a recovery whose file already matches a recorded version (the resident writer finishes those). |
| `frontmatter-keys` | `stale_frontmatter_keys` | Explicit-only, preview-bound. Strips the parser's reserved top-level keys (`type`, `title`, `tags`, `slug`) that an older import stored inside `pages.frontmatter`. Since v0.60.176.0 those keys are not file/database drift and never render (#6454), so this is hygiene: database rows only, in source-scoped coordinated batches of up to 1,000 pages, no file, body or embedding change. Each swept page advances its `knowledge_revision` once, so a client holding an older revision of a swept page gets one `revision_conflict` and re-reads. See [frontmatter keys](#frontmatter-keys). | A page whose keys were cleared by a write between preview and apply (`already_clean`). |
| `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). |
| `attribution-backfill` | none | Fills write attribution (who wrote it) on pages, page versions and facts written before attribution was recorded, only where exactly one committed request in the write journal proves the writer: the page write whose recorded result is the row's revision, or the `remember` that inserted the fact. Fills NULLs only, in committed batches of 1,000 that resume after an interruption; no content, revision, page file or request ID changes. See [write attribution](../mcp/ADMIN.md#write-attribution). | `unrecorded_pages`, `unrecorded_page_versions`, `unrecorded_facts`: rows the journal cannot prove. They stay `unrecorded`; nothing is inferred. |
@@ -434,6 +435,82 @@ failure row and its manifest (when no other cursor shares the run) in one
transaction, so a cursor the writer picked up meanwhile is left alone. Do not
delete `op_checkpoints` rows by hand.
+### Stuck recovery
+
+<a id="stuck-recovery"></a>
+
+**Say to your agent:** *"Every write to my notes source has been pending for an
+hour and writer status says a request is recovering with unexpected_file_bytes.
+Show me what changed and let me pick which version to keep."*
+
+A page write records its file's prior bytes before it publishes. If the
+process dies mid-publication, the owner's recovery pass restores the prior
+bytes or finishes the write. When the file matches neither the recorded prior
+nor the published bytes (usually a hand edit made while the write was
+publishing), recovery refuses to overwrite it: the request stays `recovering`
+with `unexpected_file_bytes`, no write on that worktree is claimed, and the
+resident writer re-checks it every 30 seconds without progress. Do not delete
+the file to unblock it.
+
+`gbrain repair stuck-recovery` is the sanctioned exit. Run it on the host that
+owns the source.
+
+```bash
+gbrain repair stuck-recovery --source notes # preview: each blocked file, its diff, the choices
+gbrain repair stuck-recovery --source notes --request-id <uuid> # only one request
+gbrain repair stuck-recovery --source notes --keep prior --apply --expect <hash> --yes
+gbrain repair stuck-recovery --source notes --keep disk --apply --expect <hash> --yes
+```
+
+The preview starts from the blocker of the source's queued head and lists
+every recovery record on the worktree. For each file it prints the prior
+(hash, size, mode, or `absent: prior was a create`), the bytes on disk (or
+`deleted on disk`), what recovery sees, and a private diff written under
+`~/.gbrain/backups/stuck-recovery/<request>/` with the exact `diff -u`
+command that reproduces it. It prints only the choices available for every
+listed record. The hash binds each record's identity, each file's disk bytes
+and the page's database revision, so an edit or a page write after the
+preview refuses the apply with `preview_changed`.
+
+The choice is the user's: there is no default `--keep`, the kind never runs
+from `--all`, `gbrain doctor --remediate` or a remediation step, and a
+non-interactive apply without `--yes` exits 3 with the consent payload and
+changes nothing. The backups never authorize an apply by themselves.
+
+What a choice does depends on the request's state:
+
+| Request state | `--keep prior` | `--keep disk` (#6640's `drop`) |
+|---|---|---|
+| Live (`recovering`), no recorded failure: the publication was interrupted and its database transaction never committed | Backs up both versions, writes the recorded prior bytes back through the writer's own durable, confined publication (staged at the record's reserved restoration path; an absent prior unlinks the file); recovery then requeues the request and the accepted write publishes again on the next pass. | Backs up both versions and ends the request `conflict` with `source_changed` instead of requeueing a write that would conflict again; recovery then only cleans its staging and clears the record, releasing the recovery bytes it reserved. The record itself is never rewritten. |
+| Live with a recorded failure (`publication_failed`) | Prior bytes back; the request ends `failed` or `conflict` with that failure. | Disk bytes kept; the request ends with that failure. |
+| Terminal (`committed`, `failed`, `conflict`, `cancelled`) with its recovery record still set | Refused (`recovery_choice_refused`): recovery never restores a terminal request's file, so this would roll back committed bytes. | Refused (`recovery_choice_refused`): a terminal outcome is immutable and there is no publication to abandon. |
+
+The preview lists a terminal request as `refused` with the reason and offers
+no choice for it. After `--keep disk` the database page still holds the
+content from before the write, so the page shows as file/database drift until
+you reconcile it: `gbrain sources reconcile <source> <slug> --brain host
+--preview`. The command never reports the page as repaired.
+
+The apply runs under the worktree lock, so the resident recovery pass cannot
+interleave. Each step is journaled (`op_checkpoints`, op
+`stuck-recovery-resolution`): a run killed at any point resumes with the same
+command, and a resident writer of any version can finish a resolution this
+command started, because the recovery rule it uses is unchanged. Running the
+same apply again after it finished replays the recorded result; the same hash
+with the other `--keep` refuses `idempotency_conflict`. The finished journal
+row is the resolution's audit entry and does not expire; the request's own
+receipt is never rewritten by this command (`--keep disk` completes the live
+request; it never changes a terminal one). A shared-skill bundle recovery is
+refused with [`recovery_bundle_unsupported`](#recovery-bundle-unsupported), and
+a withdrawal-mirror effect recovery on the worktree is listed as refused with
+[`recovery_effect_unsupported`](#recovery-effect-unsupported). The apply waits
+at most 10 seconds for the worktree lock, then refuses `writer_lock_unavailable`
+with nothing changed; `--keep prior` on a record that predates reserved staging
+first reserves it and refuses `queue_capacity` when the recovery budget is full,
+also with nothing changed.
+#6640's `drop` (abandon the blocked publication and keep the disk bytes) is
+`--keep disk` on a live request; there is no separate flag.
+
### Frontmatter keys
<a id="frontmatter-keys"></a>
@@ -1879,6 +1956,41 @@ applies to `gbrain jobs authorize-legacy --select`, `gbrain jobs cancel
--select`, `gbrain repair stale-atoms`, `gbrain repair extractor-facts`,
`gbrain repair captured-facts` and `gbrain repair loop-facts`.
+### Recovery bundle unsupported
+
+`recovery_bundle_unsupported`: `gbrain repair stuck-recovery` found a
+shared-skill bundle recovery record (several skill files published together)
+among the selected requests. It resolves page recoveries only, so nothing was
+changed. Inspect the request read-only with `gbrain sources writer status
+--source <id> --json`, ask the user which version of each skill file to keep,
+put those bytes in place by hand, and let the resident writer finish the
+recovery. Pass `--request-id` to resolve the page recoveries on the same
+source.
+
+### Recovery choice refused
+
+`recovery_choice_refused`: `gbrain repair stuck-recovery` will not apply that
+`--keep` choice to that request, and nothing was changed. Either the request is
+terminal while its recovery record is still set (its outcome is immutable,
+recovery never restores its file, and `--keep prior` would roll back committed
+bytes; the record only waits for staging cleanup, see `gbrain sources writer
+status --source <id> --json`), or the record cannot support the choice
+(`--keep prior` without stored prior bytes, or a blocked path that is not a
+regular file). The preview lists only the choices it can make safe.
+
+### Recovery effect unsupported
+
+`recovery_effect_unsupported`: a withdrawal-mirror effect recovery blocks the
+source's worktree, and `gbrain repair stuck-recovery` does not resolve it.
+That recovery only finishes forward (it never restores the bytes from before a
+withdrawal), so either `--keep` choice could put withdrawn content back on
+disk. Nothing was changed. Inspect the effect read-only with `gbrain sources
+writer status --source <id> --json` and ask the user whether the edited file
+may be replaced by its withdrawn version; the resident writer finishes the
+effect once the file matches one of its recorded versions. The preview lists
+the effect as `refused`; naming its request with `--request-id` refuses with
+this code.
+
### Legacy job authority
`permission_denied` with this anchor means a queued job row has SQL NULL
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 0055588806..e0ca7ab677 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -29,6 +29,7 @@
| [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` |
| [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` |
| A managed catch-up on a live checkout keeps dying (`revision_conflict`, `pinned_git_worktree_conflict`, `page_identity_changed`, `write ECONNABORTED`), or you want an agent to drive the recovery | `gbrain sync status --source <id> --json` (cursor, `committed_last_10m`, each hold and the last error with `class` / `safe_actions` / `needs_human`); when nothing moved and `needs_human` is false, `gbrain sync unblock --source <id> --apply`, then the sync it prints ([runbook](sync-unblock-runbook.md)) | agent; a person only when `needs_human` names a slug | none | `gbrain sync status --source <id> --json` |
+| [Every write on a source stays pending; writer status shows a request `recovering` with `unexpected_file_bytes`](repair.md#stuck-recovery) | preview `gbrain repair stuck-recovery --source <id>` on the owner host, show the user the diff it prints, then run the choice they pick: `--keep prior` or `--keep disk` with `--apply --expect <hash> --yes`; never delete the file to unblock it | agent; the apply after the user picks a version | `destructive` (both versions are backed up first) | `gbrain sources writer status --source <id> --json` shows no recovering request |
| [Sync held a file with `worktree_dirty`](#worktree-dirty-hold) | commit (or restore) the file, then `gbrain sync unblock --source <id> --apply` and the sync it prints | agent; whoever edits the file commits it | none | `gbrain sources status <id> --json` |
| A managed sync of a source far behind HEAD prints `staged catch-up: synced to <commit>, short of HEAD`, or `sliced catch-up: committed the <phase> slice of <commit> through <path>` | Staging is automatic: `gbrain sync --source <id> --no-pull` takes stage after stage (each the furthest first-parent commit whose delta fits 100,000 entries and 16 MiB) until it reaches HEAD, and a stop resumes at the stored cursor; a scheduled sync takes one stage per run. A first sync, a `--full` sync or one commit that alone exceeds the bound is cut into path slices instead (#6349): every import slice, then bounded deletion slices, pinned at one target; `last_commit` moves only when the last slice settles, and the same command resumes an unfinished target at its stored slice. Only one file whose manifest entry alone exceeds the byte bound still refuses `request_too_large`, naming it; exclude it (`--exclude`, or `gbrain config set sync.exclude`) and rerun | agent | none | `gbrain sync status --source <id> --json` (cursor target reaches HEAD) |
| A write, sync, connector run or activation refuses `storage_error` with `requires exactly one known boolean persistence state` (`detail: persistence_mode_unknown`) | The `persistence_brain` singleton is missing, duplicated or malformed, so gbrain cannot tell whether the brain is managed and refuses instead of writing around the owner (#6482). Run `gbrain sources writer status --probe --json` on the brain host (it reports `mode: unknown` and the problem instead of refusing), restore the one row (`gbrain doctor --json` names the repair), then rerun the command | host operator | none | `gbrain doctor --json` |
diff --git a/llms-full.txt b/llms-full.txt
index 1baebba029..477fe389cc 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10148,6 +10148,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` |
| [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` |
| A managed catch-up on a live checkout keeps dying (`revision_conflict`, `pinned_git_worktree_conflict`, `page_identity_changed`, `write ECONNABORTED`), or you want an agent to drive the recovery | `gbrain sync status --source <id> --json` (cursor, `committed_last_10m`, each hold and the last error with `class` / `safe_actions` / `needs_human`); when nothing moved and `needs_human` is false, `gbrain sync unblock --source <id> --apply`, then the sync it prints ([runbook](sync-unblock-runbook.md)) | agent; a person only when `needs_human` names a slug | none | `gbrain sync status --source <id> --json` |
+| [Every write on a source stays pending; writer status shows a request `recovering` with `unexpected_file_bytes`](repair.md#stuck-recovery) | preview `gbrain repair stuck-recovery --source <id>` on the owner host, show the user the diff it prints, then run the choice they pick: `--keep prior` or `--keep disk` with `--apply --expect <hash> --yes`; never delete the file to unblock it | agent; the apply after the user picks a version | `destructive` (both versions are backed up first) | `gbrain sources writer status --source <id> --json` shows no recovering request |
| [Sync held a file with `worktree_dirty`](#worktree-dirty-hold) | commit (or restore) the file, then `gbrain sync unblock --source <id> --apply` and the sync it prints | agent; whoever edits the file commits it | none | `gbrain sources status <id> --json` |
| A managed sync of a source far behind HEAD prints `staged catch-up: synced to <commit>, short of HEAD`, or `sliced catch-up: committed the <phase> slice of <commit> through <path>` | Staging is automatic: `gbrain sync --source <id> --no-pull` takes stage after stage (each the furthest first-parent commit whose delta fits 100,000 entries and 16 MiB) until it reaches HEAD, and a stop resumes at the stored cursor; a scheduled sync takes one stage per run. A first sync, a `--full` sync or one commit that alone exceeds the bound is cut into path slices instead (#6349): every import slice, then bounded deletion slices, pinned at one target; `last_commit` moves only when the last slice settles, and the same command resumes an unfinished target at its stored slice. Only one file whose manifest entry alone exceeds the byte bound still refuses `request_too_large`, naming it; exclude it (`--exclude`, or `gbrain config set sync.exclude`) and rerun | agent | none | `gbrain sync status --source <id> --json` (cursor target reaches HEAD) |
| A write, sync, connector run or activation refuses `storage_error` with `requires exactly one known boolean persistence state` (`detail: persistence_mode_unknown`) | The `persistence_brain` singleton is missing, duplicated or malformed, so gbrain cannot tell whether the brain is managed and refuses instead of writing around the owner (#6482). Run `gbrain sources writer status --probe --json` on the brain host (it reports `mode: unknown` and the problem instead of refusing), restore the one row (`gbrain doctor --json` names the repair), then rerun the command | host operator | none | `gbrain doctor --json` |
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index eb2616abe7..d89487a786 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -63,6 +63,8 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i
[--apply --expect <preview-hash> --yes] [--json]
gbrain repair fences [--source <id>] [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff]
[--no-llm] [--max-usd <n>] [--apply [--expect <preview-hash>]] [--limit <n>] [--json]
+ gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]
+ [--keep prior|disk --apply --expect <preview-hash> --yes] [--json]
${REPAIR_CONTENT_HELP}
Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.
@@ -94,7 +96,11 @@ Options:
model-tier items stay held with llm_disabled.
--max-usd <n> Kinds that may call a paid model (${llmKinds}) and the content lane: spend at most n USD on the
model in this run. It only lowers the cap (the daily fences.repair cap still applies); never raises it.
- --yes frontmatter, conversation-labels --apply: the user agreed to the previewed changes (destructive
+ --keep prior|disk
+ stuck-recovery --apply: the version of each blocked file to keep (the user's choice from the preview).
+ --request-id <uuid>
+ stuck-recovery: resolve only this request's recovery (default: every blocked record of the source).
+ --yes frontmatter, conversation-labels, stuck-recovery --apply: the user agreed to the previewed changes (destructive
consent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).
--json Machine-readable output with a stable shape (frontmatter: every per-file diff).
@@ -103,23 +109,25 @@ paid embedding work, preview gbrain doctor --remediation-plan --json and, after
run gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>.
With no kind, previews every kind. Run it on the brain host.
Held files (the content lane, then the two-pass frontmatter repair): docs/guides/repair.md#held-files.
-Malformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.`;
+Malformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.
+A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-recovery.`;
const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm']);
-const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd']);
+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--keep', '--request-id']);
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
- '--only': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels'],
- '--slug': ['fences'],
+ '--only': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery'],
+ '--slug': ['fences'], '--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
};
const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md',
- '--slug': 'notes/a', '--max-usd': '0.50' };
+ '--slug': 'notes/a', '--max-usd': '0.50', '--keep': 'prior', '--request-id': '123e4567-e89b-42d3-a456-426614174000' };
/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */
const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,
{ fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });
interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;
- noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[] }
+ noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];
+ keep?: 'prior' | 'disk'; requestId?: string }
/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */
function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | undefined): OperationError {
@@ -168,6 +176,15 @@ export function parseRepairArgs(args: string[]): RepairArgs {
else if (flag === '--skip') parsed.skip.push(value);
else if (flag === '--slug') parsed.slugs.push(value);
else if (flag === '--max-usd') { maxUsdText = value; maxUsdFlag = flag; }
+ else if (flag === '--keep') {
+ if (value !== 'prior' && value !== 'disk') throw invalid(`--keep must be prior or disk (got "${value}").`,
+ 'Pass --keep prior to write the recorded prior bytes back, or --keep disk to keep the bytes on disk; the preview lists which are available.', ['gbrain', 'repair', 'stuck-recovery', '--json']);
+ parsed.keep = value;
+ } else if (flag === '--request-id') {
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw invalid(`--request-id must be a request UUID (got "${value}").`,
+ 'Pass the request_id the stuck-recovery preview (or gbrain sources writer status --json) lists, e.g. --request-id 123e4567-e89b-42d3-a456-426614174000.', ['gbrain', 'repair', 'stuck-recovery', '--json']);
+ parsed.requestId = value.toLowerCase();
+ }
else parsed.limit = value;
}
if (positional.length > 1) throw new OperationError('invalid_params', `Unexpected argument '${positional[1]}'; gbrain repair takes at most one kind.`,
@@ -245,7 +262,7 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }
export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }
- const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText } = parseRepairArgs(args);
+ const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, keep, requestId, limit: limitText } = parseRepairArgs(args);
const limit = limitText === undefined ? undefined : Number(limitText);
if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');
if (kind === CONTENT_LANE) {
@@ -266,15 +283,15 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
const scope = await resolveRepairScope(engine, source);
if (apply && kind && expect && repairSpec(kind as RepairKind).consent === 'destructive') {
const preview = ['gbrain', 'repair', kind, ...(source ? ['--source', source] : []), ...only.flatMap(path => ['--only', path]), ...skip.flatMap(path => ['--skip', path]),
- ...(includeAmbiguous ? ['--include-ambiguous'] : [])];
+ ...(includeAmbiguous ? ['--include-ambiguous'] : []), ...(requestId ? ['--request-id', requestId] : [])];
const custom = repairSpec(kind as RepairKind).consentText;
- const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)})` } : {
+ const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)}${keep ? `, keep ${keep}` : ''})` } : {
what: `Rewrite the previewed ${kind} changes on disk and import them`,
why: `The preview ${expect} listed each file change; applying it rewrites those files in place and publishes them.`,
risk: 'Only the previewed lines change; a file that changed since the preview is skipped. Managed sources commit through the Git effect (undo with git revert); legacy sources keep a backup under ~/.gbrain/backups/frontmatter/.',
user_message: `Apply the previewed ${kind} repair (preview ${expect.slice(0, 12)})? Each listed file is rewritten on disk exactly as the preview showed and imported again.` };
const auth = await consentGate({ command: `repair ${kind}`, effects: ['destructive'], actor: 'agent', ...text,
- argv: [...preview, '--apply', '--expect', expect, ...(json ? ['--json'] : [])], preview_argv: [...preview, '--json'], plan_hash: expect, args }, { json, env: engineConsentEnv(engine) });
+ argv: [...preview, ...(keep ? ['--keep', keep] : []), '--apply', '--expect', expect, ...(json ? ['--json'] : [])], preview_argv: [...preview, '--json'], plan_hash: expect, args }, { json, env: engineConsentEnv(engine) });
if (!auth) return;
}
const runner = await repairRunner(engine, { apply, noEmbed });
@@ -282,7 +299,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
for (const k of kinds) {
const result = await runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous,
...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),
- ...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}) });
+ ...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),
+ ...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}) });
results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });
if (result.stopped) break;
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index af6a92d5ff..954e1d4f0e 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -541,6 +541,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// #6574 (publication round trips). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.209.0', text: 'Publishing a page now writes its timeline rows, fact rows, fact field refreshes and take resolutions in a few set-based statements (one per 500 rows) instead of one statement per row, and `insertFacts` inserts in multi-row chunks for every caller. A large page no longer needs thousands of round trips, so it publishes inside `persistence.publication_ceiling_ms` behind a transaction-mode pooler with pipelining off. A projection that takes 30 s or more logs `[persistence] phase=publication reason=slow_projection` with its row counts and per-step milliseconds.' },
{ since: '0.60.209.0', text: 'Before a publish opens its transaction, the consumer now commits one claim renewal that stamps the request `publishing` and leases it for the publication ceiling plus its grace, and stops renewing until the publish ends. A long publish no longer reads as a lapsed claim, so `gbrain sync` no longer stops `drain_stalled` with `owner_missing` while the publish is still working; a publish past the ceiling still reports `publication_overdue`. An owner that crashes mid-publish now holds its head until that lease runs out (the ceiling plus about 70 s) rather than 30 s.' },
+ // #6650 §1.10 (GBRA L2). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.213.0', text: 'A page write whose recovery is blocked on `unexpected_file_bytes` (its file matches neither the recorded prior nor the published bytes, so every write on that source stays pending) now has a sanctioned exit: `gbrain repair stuck-recovery --source <id>` previews each blocked file with a private diff under ~/.gbrain/backups/stuck-recovery/, and `--keep prior` (restore the prior bytes; the write publishes again) or `--keep disk` (keep your edit; the write ends conflict) with `--apply --expect <hash> --yes` backs up both versions first. A terminal request is never changed. It runs only when named; nothing changes until you apply it, and each resolution is kept as an audit entry that does not expire.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 357bcedf71..540ac806f7 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -73,7 +73,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
@@ -101,13 +101,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],
'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--apply', '--background', '--brain', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--include-ambiguous', '--json', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--path', '--plan', '--progress-interval', '--progress-json', '--quiet', '--repo', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--apply', '--background', '--brain', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--path', '--plan', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request-id', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--scopes', '--source', '--timeout'],
- 'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--only', '--probe', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--yes'],
+ 'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--only', '--probe', '--remediate', '--remediation-plan', '--request-id', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--yes'],
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
index f85ff8daa0..3bdb65f48d 100644
--- a/src/core/error-catalogue.ts
+++ b/src/core/error-catalogue.ts
@@ -45,6 +45,12 @@ export const ERROR_CATALOGUE = {
page_projection_conflict: { code: 'page_projection_conflict', docs: 'docs/guides/repair.md#page-projection-conflict' },
explicit_kind_required: { code: 'explicit_kind_required', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' },
repair_kind_unavailable: { code: 'unavailable', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' },
+ // #6650: gbrain repair stuck-recovery resolves page recovery records only; a shared-skill bundle record is refused.
+ recovery_bundle_unsupported: { code: 'recovery_bundle_unsupported', docs: 'docs/guides/repair.md#recovery-bundle-unsupported' },
+ // #6650: a (request state, --keep) pair stuck-recovery cannot make safe: a terminal request, or a choice the record cannot support.
+ recovery_choice_refused: { code: 'recovery_choice_refused', docs: 'docs/guides/repair.md#recovery-choice-refused' },
+ // #6650: a withdrawal-mirror effect recovery only finishes forward, so stuck-recovery lists it as refused.
+ recovery_effect_unsupported: { code: 'recovery_effect_unsupported', docs: 'docs/guides/repair.md#recovery-effect-unsupported' },
colon_slug_windows_write_through: { code: 'colon_slug_windows_write_through', docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through' },
embedding_auth_failed: { code: 'embedding_auth_failed', docs: 'docs/guides/write-refusals.md#embedding_auth_failed' },
activation_source_path_missing: { code: 'source_changed', docs: 'docs/guides/write-refusals.md#activation_source_path_missing' },
diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.ts
index 56ba9bee47..5f83ab0b4f 100644
--- a/src/core/op-checkpoint.ts
+++ b/src/core/op-checkpoint.ts
@@ -493,7 +493,8 @@ export function syncFingerprint(p: { sourceId?: string; lastCommit: string }): s
* census (candidates and scan cursors), paid fence-repair attempt claims
* and memos, and uncommitted legacy fence-repair notices of a live source
* incarnation leave only on resolution (or with
- * the incarnation), and connector hold-retry requests never expire (#5988).
+ * the incarnation), and connector hold-retry requests and stuck-recovery
+ * resolution audit entries never expire (#5988, #6650).
*/
export async function purgeStaleCheckpoints(
engine: BrainEngine,
@@ -509,6 +510,7 @@ export async function purgeStaleCheckpoints(
WHERE updated_at < now() - ($1 || ' days')::interval
AND op NOT IN ('managed-atoms','managed-atoms-generation','managed-connector','managed-connector-retry','managed-connector-state','managed-connector-migration')
AND op<>'connector-hold-retry'
+ AND op<>'stuck-recovery-resolution'
AND NOT (op IN ('sync-hold','sync-hold-retry','sync-import-provenance','sync-hold-summary','sync-conversions','${FENCE_CANDIDATE_OP}','${FENCE_SCAN_OP}','${FENCE_REPAIR_ATTEMPT_OP}','${FENCE_UNCOMMITTED_OP}')
AND NOT (op='sync-hold-summary' AND COALESCE((completed_keys->0->>'count')::int,0)=0)
AND EXISTS (SELECT 1 FROM sources s WHERE s.id=op_checkpoints.completed_keys->0->>'source_id'
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index a1d9d6dad5..df0f15d25d 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -4,7 +4,7 @@
* recovery path must finish: publication boundaries, after an effect's side
* effect but before its completion is recorded, before a recovery record is
* cleared, between sync checkpoints, after the consumer prepared a
- * claimed request, and (`lane:applied`) when a lane group has applied its pages and waits for its commit turn. Production never installs a hook, so every call is a
+ * claimed request, (`lane:applied`) when a lane group has applied its pages and waits for its commit turn, and (`stuck_recovery:*`) between the steps of a stuck-recovery resolution. Production never installs a hook, so every call is a
* no-op there; the gate's workers install one that SIGKILLs or stalls the
* process at a chosen point.
*/
@@ -19,7 +19,10 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
// #6511: the page purge's in-transaction journal lookups (page-purge.ts `journalLookup`); a hook that throws a 57014 models a statement timeout there.
| 'purge:slug_lookup' | 'purge:tail_recheck' | 'purge:pending_recheck' | 'purge:redaction_read'
// #6511: before each keyset chunk of the preparation-time journal sweep (a stalling hook models a slow chunk), and the fact purge's planning read.
- | 'purge:sweep_chunk' | 'purge:carrying_lookup';
+ | 'purge:sweep_chunk' | 'purge:carrying_lookup'
+ // #6650: `gbrain repair stuck-recovery` (recovery-resolve.ts): after the backup is durable (before its journal step), after the prior
+ // bytes are written (before their journal step), after a --keep disk write is abandoned (its journal step written), and after recoverPublication returns.
+ | 'stuck_recovery:backed_up' | 'stuck_recovery:written' | 'stuck_recovery:abandoned' | 'stuck_recovery:recovered';
/**
* `signal` (#6278, `consumer:preparing` only): the preparation's abort signal, so
* a stalling hook can model both the reporter's cases: a preparer that honours
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index b2d64a16a3..69ec7b8be7 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'stuck-recovery';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/persistence/recovery-resolve.ts b/src/core/persistence/recovery-resolve.ts
new file mode 100644
index 0000000000..1e28feb2c0
--- /dev/null
+++ b/src/core/persistence/recovery-resolve.ts
@@ -0,0 +1,398 @@
+/**
+ * `gbrain repair stuck-recovery` (#6650 §1.10, #6640 §B): resolve a page publication recovery that the owner's
+ * recovery pass refuses with `unexpected_file_bytes` (a canonical file matches neither its recorded prior nor its
+ * published bytes, usually a human edit made while the write was publishing). Until it is resolved its worktree
+ * claims nothing, and the resident consumer re-parks it every 30 s.
+ *
+ * The preview starts from the head blocker's `request_recovery` ids (the recovery records on the source's
+ * worktree), lists every file of each record with its prior and disk fingerprints, and writes a private diff of the
+ * two into the owner host's backup directory. Its hash binds each record's identity, each file's disk bytes and the
+ * page's database revision.
+ *
+ * Only a live (non-terminal) request is resolved: its database transaction never committed, so neither choice rolls back
+ * committed bytes. `--keep prior` writes the prior bytes back through the coordinator's confined durable publication
+ * (`publishPersistenceFile`, staged at the record's reserved restoration path, which `upgradeRecoveryStaging` reserves
+ * and accounts for older records) and recovery finishes by its own rule (a request with no recorded failure is requeued
+ * and its write publishes again; one with a failure ends terminal). `--keep disk` (#6640's `drop`) keeps the edited
+ * bytes and abandons the publication: it completes the request terminal (`completeWrite`; `source_changed`, so
+ * `conflict`, when it recorded no failure, else that failure by the owner's rule via `finishUnpublishedFailure`), and
+ * recovery's terminal path then only cleans its staging and clears the record (`clearResolvedRecovery`), releasing its
+ * reserved bytes. The record is never rewritten, so no recovery bytes move outside the accounting.
+ * A terminal request whose recovery record is still set is refused (`recovery_choice_refused`): its outcome is immutable,
+ * recovery never restores its canonical file, and `--keep prior` would roll back a committed write. A withdrawal-mirror
+ * effect recovery blocking the worktree is listed as refused (`recovery_effect_unsupported`): it only finishes forward,
+ * and either choice could put withdrawn content back on disk.
+ *
+ * The apply runs on the owner host under the worktree lock, so the resident recovery pass cannot interleave. Each
+ * record moves through a journal (`op_checkpoints`, op `stuck-recovery-resolution`, keyed by request and preview
+ * hash): `backed_up` (the disk and prior bytes are in the backup directory, always), then `written` (`--keep
+ * prior`: the prior bytes are back on disk, an absent prior unlinked) or `abandoned` (`--keep disk`: the request is
+ * terminal), then `done` once `recoverPublication` finished it by its unchanged rule. Every step is idempotent, so a
+ * run killed at any boundary resumes, and an older resident consumer can finish a resolution this command started.
+ * The finished journal row is the resolution's audit entry; a terminal receipt is never rewritten.
+ */
+import { closeSync, constants, existsSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
+import { dirname, join, relative } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { catalogueError } from '../error-catalogue.ts';
+import { gbrainPath } from '../config.ts';
+import { mkdirPrivate } from '../atomic-write.ts';
+import { flushDirectory } from '../fs-durable.ts';
+import { isWriteTargetContained } from '../path-confine.ts';
+import { unifiedDiff } from '../skillpack/diff-text.ts';
+import { digest, sha256 } from './digest.ts';
+import { localHostId } from './identity.ts';
+import { acquireWorktree, containsPath, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
+import { canonicalFilesystemPath } from './root-registry.ts';
+import { completeWrite, getWriteRequestById } from './journal.ts';
+import { isTerminal, recoveryFiles, type FileRecoveryRecord, type WriteRequest } from './model.ts';
+import { finishUnpublishedFailure, publishPersistenceFile, recoverPublication, transientDatabaseFailure } from './coordinator.ts';
+import { mayReprepare } from './semantic.ts';
+import { cleanupRecoveryStaging, upgradeRecoveryStaging } from './staging.ts';
+import { withFilesystemPublication } from './filesystem-guard.ts';
+import { readHeadBlockers } from './head-blocker.ts';
+import { previewChangedError } from './preview-approval.ts';
+import { faultPoint } from './fault-points.ts';
+
+export const RESOLUTION_OP = 'stuck-recovery-resolution';
+export type KeepChoice = 'prior' | 'disk';
+
+export type PriorView = { absent: true } | { absent: false; sha256: string; size: number | null; mode: number | null; stored: boolean };
+export type DiskView = { deleted: true } | { deleted: false; kind: 'file' | 'symlink' | 'directory' | 'other'; sha256: string | null; size: number; mode: number };
+export interface RecoveryFileView {
+ path: string; root: string; relative: string; prior: PriorView; disk: DiskView;
+ /** What recovery itself makes of the disk bytes: the prior, the published bytes, or neither (the blocked case). */
+ matches: 'prior' | 'published' | 'neither';
+ /** Preview only: the private diff and the command that reproduces it (absent for a remote caller). */
+ diff_path?: string; diff_command?: string;
+}
+/** The identity the hash binds: the publication attempt, its owner epoch and each file's path and published hash. */
+export interface RecoveryIdentity { attempt: string; owner_epoch: string; files: Array<{ path: string; after_hash: string | null }> }
+export interface StuckRecovery {
+ id: string; request_id: string; source_id: string; slug: string; operation: string; state: string; blocked_reason: string | null;
+ worktree_id: string; sequence: string; page_revision: string | null; identity: RecoveryIdentity;
+ /** The failure the request already recorded, if any: with one, either choice ends the request terminal with it. */
+ recorded_error: string | null;
+ /** Each file's recorded prior hash, so an apply can tell its own write from a later edit. */
+ prior_hashes: Array<string | null>; files: RecoveryFileView[]; choices: Record<KeepChoice, boolean>;
+ /** Digest of the identity, each file's disk bytes and the page revision: what an apply re-verifies. */
+ digest: string;
+}
+/** A blocked terminal request or a withdrawal-mirror effect recovery: listed, never resolved (see the module comment). */
+export interface RefusedRecovery { code: 'recovery_choice_refused' | 'recovery_effect_unsupported'; request_id: string; source_id: string; slug: string; state: string;
+ blocked_reason: string | null; reason: string; effect_id?: string }
+export interface StuckRecoveryScan { items: StuckRecovery[]; residuals: Record<string, number>; refused: RefusedRecovery[];
+ heads: Array<{ source_id: string; queued_request_id: string | null; blocked_by: string | null }> }
+
+interface Journal {
+ id: string; request_id: string; source_id: string; slug: string; preview_hash: string; keep: KeepChoice;
+ phase: 'backed_up' | 'written' | 'abandoned' | 'done'; backup_dir: string; original: { state: string; blocked_reason: string | null; prior_hashes: Array<string | null>; disk_hashes: Array<string | null> };
+ result?: ResolutionResult;
+}
+export interface ResolutionResult {
+ outcome: 'resolved' | 'still_blocked'; keep: KeepChoice; request_state: string; blocked_reason: string | null;
+ finished_by: 'this_run' | 'another_pass'; backup_dir: string; next: string;
+}
+
+const statusFix = (sourceId: string) => readFix(`Shows source ${sourceId}'s canonical owner with its recovering write requests, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+export const stuckRecoveryPreviewCommand = (sourceIds: string[], requestId?: string) =>
+ `gbrain repair stuck-recovery${sourceIds.length === 1 ? ` --source ${sourceIds[0]}` : ''}${requestId ? ` --request-id ${requestId}` : ''}`;
+const backupRoot = () => gbrainPath('backups', 'stuck-recovery');
+const fileMode = (mode: number) => mode & 0o777;
+
+function identityOf(files: FileRecoveryRecord[], record: { attempt: string; ownerEpoch: string }): RecoveryIdentity {
+ return { attempt: record.attempt, owner_epoch: String(record.ownerEpoch), files: files.map(file => ({ path: file.path, after_hash: file.afterHash })) };
+}
+
+function diskView(path: string): { view: DiskView; bytes: Buffer | null } {
+ let stat;
+ try { stat = lstatSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { view: { deleted: true }, bytes: null }; throw error; }
+ if (!stat.isFile()) return { view: { deleted: false, kind: stat.isSymbolicLink() ? 'symlink' : stat.isDirectory() ? 'directory' : 'other', sha256: null, size: stat.size, mode: fileMode(stat.mode) }, bytes: null };
+ const bytes = readFileSync(path);
+ return { view: { deleted: false, kind: 'file', sha256: sha256(bytes), size: bytes.length, mode: fileMode(stat.mode) }, bytes };
+}
+
+function priorBytes(record: FileRecoveryRecord): Buffer | null { return record.before === null ? null : Buffer.from(record.before, 'base64'); }
+function priorView(record: FileRecoveryRecord): PriorView {
+ if (record.beforeHash === null) return { absent: true };
+ const bytes = priorBytes(record);
+ return { absent: false, sha256: record.beforeHash, size: bytes?.length ?? null, mode: record.mode, stored: bytes !== null && sha256(bytes) === record.beforeHash };
+}
+
+/** The private backup directory, refused when it is not a private directory of this user or sits inside a canonical checkout. */
+async function privateBackupDir(engine: BrainEngine, ...segments: string[]): Promise<string> {
+ const root = backupRoot();
+ const dir = join(root, ...segments);
+ mkdirPrivate(dir, root);
+ const stat = lstatSync(root);
+ const owned = process.platform === 'win32' || ((stat.mode & 0o077) === 0 && (typeof process.getuid !== 'function' || stat.uid === process.getuid()));
+ if (!stat.isDirectory() || stat.isSymbolicLink() || !owned) throw opError('permission_denied', 'The stuck-recovery backup directory must be private, owned and free of symlinks.',
+ `Nothing was written. Ask the user to make ${root} a real directory they own with mode 0700 (not a symlink), then run the same command again.`);
+ const roots = await engine.executeRaw<{ local_path: string }>(`SELECT local_path FROM sources WHERE local_path IS NOT NULL
+ UNION SELECT local_path FROM persistence_host_bindings WHERE local_path IS NOT NULL`);
+ const resolved = canonicalFilesystemPath(dir);
+ if (roots.some(row => existsSync(row.local_path) && containsPath(canonicalFilesystemPath(row.local_path), resolved))) {
+ throw opError('permission_denied', 'Stuck-recovery backups must be stored outside every canonical source checkout.',
+ `Nothing was written: ${root} sits inside a source checkout. The user must move the gbrain config directory (GBRAIN_HOME) out of the checkout, then run the same command again.`);
+ }
+ return dir;
+}
+
+/** Writes `bytes` to `path` 0600 and durable, then reads it back; an existing identical file is kept. */
+function writePrivateFile(path: string, bytes: Buffer): void {
+ if (existsSync(path) && sha256(readFileSync(path)) === sha256(bytes)) return;
+ const temporary = `${path}.${randomUUID()}.tmp`;
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
+ try { writeFileSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); }
+ try { renameSync(temporary, path); } catch (error) { try { unlinkSync(temporary); } catch { /* already gone */ } throw error; }
+ flushDirectory(dirname(path));
+ if (sha256(readFileSync(path)) !== sha256(bytes)) throw opError('storage_error', 'A stuck-recovery backup did not read back as written.',
+ `Nothing was changed on disk or in the journal. Check free space and the filesystem under ${dirname(path)}, then run the same command again.`);
+}
+
+/** Prior and disk bytes of every unexpected file (and their diff) under `dir`; returns the paths by file index. */
+function writeArtifacts(dir: string, item: { files: RecoveryFileView[] }, records: FileRecoveryRecord[], disks: Array<Buffer | null>) {
+ return item.files.map((file, index) => {
+ const prior = priorBytes(records[index]);
+ const priorPath = prior === null ? null : join(dir, `${index}.prior`);
+ const diskPath = disks[index] === null ? null : join(dir, `${index}.disk`);
+ if (priorPath) writePrivateFile(priorPath, prior!);
+ if (diskPath) writePrivateFile(diskPath, disks[index]!);
+ const diffPath = join(dir, `${index}.diff`);
+ writePrivateFile(diffPath, Buffer.from(unifiedDiff(prior?.toString('utf8') ?? '', disks[index]?.toString('utf8') ?? '',
+ { oldPath: `prior/${file.relative}`, newPath: `disk/${file.relative}` })));
+ return { diff_path: diffPath, diff_command: `diff -u ${priorPath ?? '/dev/null'} ${diskPath ?? '/dev/null'}` };
+ });
+}
+
+/** One record's current view: its files with disk fingerprints, the page revision and the state digest. */
+async function readItem(engine: BrainEngine, row: WriteRequest, binding: WorktreeBinding): Promise<{ item: StuckRecovery; records: FileRecoveryRecord[]; disks: Array<Buffer | null> }> {
+ if (row.recovery?.version === 2) throw catalogueError('recovery_bundle_unsupported', `Request ${row.request_id} in source ${row.source_id} is a shared-skill bundle recovery, which gbrain repair stuck-recovery does not resolve.`,
+ `Nothing was changed. Inspect it read-only with gbrain sources writer status --source ${row.source_id} --json and ask the user which version of each skill file to keep; resolve the bundle by hand, then let the resident writer finish its recovery.`);
+ const records = recoveryFiles(row.recovery!);
+ const [page] = await engine.executeRaw<{ revision: string | null }>('SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug]);
+ const disks: Array<Buffer | null> = [];
+ const files = records.map(record => {
+ const contained = isWriteTargetContained(record.path, record.root) && !!binding.local_path && isWriteTargetContained(record.path, binding.local_path);
+ const { view, bytes } = contained ? diskView(record.path) : { view: { deleted: false, kind: 'other', sha256: null, size: 0, mode: 0 } as DiskView, bytes: null };
+ disks.push(bytes);
+ const hash = view.deleted ? null : view.sha256;
+ const matches = (view.deleted || view.kind === 'file') && hash === record.beforeHash ? 'prior' : (view.deleted || view.kind === 'file') && hash === record.afterHash ? 'published' : 'neither';
+ return { path: record.path, root: record.root, relative: relative(binding.local_path ?? record.root, record.path), prior: priorView(record), disk: view, matches } as RecoveryFileView;
+ });
+ const writable = (file: RecoveryFileView) => file.disk.deleted || file.disk.kind === 'file';
+ const unexpected = files.filter(file => file.matches === 'neither');
+ const choices = { prior: unexpected.every(file => writable(file) && (file.prior.absent || file.prior.stored)), disk: unexpected.every(writable) };
+ const identity = identityOf(records, row.recovery!);
+ const page_revision = page?.revision ?? null;
+ return { records, disks, item: { id: row.id, request_id: row.request_id, source_id: row.source_id, slug: row.slug, operation: row.operation, state: row.state,
+ blocked_reason: row.blocked_reason ?? null, worktree_id: row.worktree_id!, sequence: String(row.sequence),
+ page_revision, identity, recorded_error: row.error_code ?? null, prior_hashes: records.map(record => record.beforeHash), files, choices,
+ digest: digest({ v: 'stuck-recovery-item-v1', id: row.id, request_id: row.request_id, identity, prior_hashes: records.map(record => record.beforeHash),
+ disk: files.map(file => file.disk), page_revision }) } };
+}
+
+function ownerBinding(binding: WorktreeBinding | null, sourceId: string, hostId: string): WorktreeBinding {
+ if (binding?.owner_host_id === hostId && binding.local_path) return binding;
+ throw opError('owner_unavailable', `Source ${sourceId}'s canonical worktree is not owned by this host, so its recovery files cannot be read or resolved here.`,
+ `Nothing was changed. Run gbrain repair stuck-recovery --source ${sourceId} on the host that owns the source (gbrain sources writer status --source ${sourceId} --json names it).`,
+ { fix: statusFix(sourceId) });
+}
+
+/**
+ * The resolvable recoveries in `sourceIds` (owner host only): every non-terminal page recovery record on each
+ * source's worktree that is blocked on unexpected bytes or whose file matches neither recorded version. `requestId`
+ * narrows to one request. `artifacts` writes each file's private diff (a remote caller's preview never does).
+ */
+export async function scanStuckRecoveries(engine: BrainEngine, sourceIds: string[], opts: { requestId?: string; artifacts?: boolean; hostId?: string } = {}): Promise<StuckRecoveryScan> {
+ const hostId = opts.hostId ?? localHostId();
+ const scan: StuckRecoveryScan = { items: [], residuals: {}, refused: [], heads: [] };
+ const residual = (key: string) => { scan.residuals[key] = (scan.residuals[key] ?? 0) + 1; };
+ for (const sourceId of sourceIds) {
+ const found = await getWorktreeBinding(engine, sourceId, hostId);
+ if (!found?.worktree_id) continue;
+ const rows = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL ORDER BY sequence', [found.worktree_id]);
+ const effects = await engine.executeRaw<{ id: string; request_id: string | null; kind: string; state: string; slug: string | null }>(`SELECT e.id::text,r.request_id::text,e.kind,e.state,
+ COALESCE(e.recovery->>'slug',r.slug) AS slug FROM persistence_effects e LEFT JOIN persistence_requests r ON r.id=e.request_id
+ WHERE e.worktree_id=$1::uuid AND e.recovery IS NOT NULL ORDER BY e.id`, [found.worktree_id]);
+ for (const effect of effects) {
+ if (opts.requestId && effect.request_id !== opts.requestId) continue;
+ const refused: RefusedRecovery = { code: 'recovery_effect_unsupported', request_id: effect.request_id ?? '', effect_id: effect.id, source_id: sourceId, slug: effect.slug ?? '',
+ state: effect.state, blocked_reason: null, reason: effectReason(effect.kind) };
+ if (opts.requestId && !rows.some(row => row.request_id === opts.requestId)) throw catalogueError('recovery_effect_unsupported', refused.reason, effectGuidance(sourceId));
+ scan.refused.push(refused);
+ residual('effect_recovery');
+ }
+ if (!rows.length) continue;
+ const binding = sourceIds.length === 1 || opts.requestId ? ownerBinding(found, sourceId, hostId) : found.owner_host_id === hostId && found.local_path ? found : null;
+ if (!binding) { residual('owned_by_other_host'); continue; }
+ const [head] = await engine.executeRaw<{ id: string; request_id: string }>("SELECT id::text, request_id::text FROM persistence_requests WHERE worktree_id=$1::uuid AND state='queued' ORDER BY sequence LIMIT 1", [binding.worktree_id]);
+ const read = head ? (await readHeadBlockers(engine, [head.id], hostId).catch(() => null))?.get(head.id) : undefined;
+ const blocker = read?.status === 'blocked' ? read.blocker : null;
+ scan.heads.push({ source_id: sourceId, queued_request_id: head?.request_id ?? null, blocked_by: blocker ? blocker.predicate : null });
+ const ids = blocker?.predicate === 'request_recovery' ? new Set(blocker.ids) : null;
+ for (const row of rows) {
+ if (opts.requestId && row.request_id !== opts.requestId) continue;
+ if (ids && !ids.has(row.request_id)) continue;
+ if (isTerminal(row)) {
+ if (!row.blocked_reason) { residual('terminal_cleanup'); continue; }
+ const refused: RefusedRecovery = { code: 'recovery_choice_refused', request_id: row.request_id, source_id: row.source_id, slug: row.slug, state: row.state,
+ blocked_reason: row.blocked_reason, reason: terminalReason(row) };
+ if (opts.requestId) throw choiceRefused(refused.reason, row.source_id);
+ scan.refused.push(refused);
+ residual('terminal_refused');
+ continue;
+ }
+ if (row.blocked_reason === 'unexpected_staging_bytes') { residual('unexpected_staging_bytes'); continue; }
+ const { item, records, disks } = await readItem(engine, row, binding);
+ if (row.blocked_reason !== 'unexpected_file_bytes' && item.files.every(file => file.matches !== 'neither')) { residual('recovers_on_its_own'); continue; }
+ if (opts.artifacts) {
+ const paths = writeArtifacts(await privateBackupDir(engine, row.request_id, item.digest.slice(0, 16)), item, records, disks);
+ item.files = item.files.map((file, index) => ({ ...file, ...paths[index] }));
+ }
+ scan.items.push(item);
+ }
+ }
+ if (opts.requestId && !scan.items.length) throw opError('invalid_params', `Request ${opts.requestId} holds no resolvable recovery record in ${sourceIds.length === 1 ? `source ${sourceIds[0]}` : 'the selected sources'}.`,
+ `Nothing was changed. Preview without the request id to list the stuck recoveries: ${stuckRecoveryPreviewCommand(sourceIds)}`);
+ return scan;
+}
+
+function terminalReason(row: WriteRequest): string {
+ return `Request ${row.request_id} already ended ${row.state}; a terminal outcome is immutable and its recovery never restores the canonical file, so `
+ + `--keep prior would roll back ${row.state === 'committed' ? 'a committed write' : 'the outcome it recorded'} and --keep disk has nothing to abandon. Its recovery only waits `
+ + `for staging cleanup (${row.blocked_reason}), which this command does not perform.`;
+}
+function effectReason(kind: string): string {
+ return `A ${kind} effect recovery blocks the worktree. It only finishes forward (it never restores the bytes from before a withdrawal), and either `
+ + '--keep choice could put withdrawn content back on disk, so gbrain repair stuck-recovery does not resolve it.';
+}
+const effectGuidance = (sourceId: string) => `Nothing was changed. Inspect the effect read-only with gbrain sources writer status --source ${sourceId} --json and ask the user `
+ + 'whether the edited file may be replaced by its withdrawn version; the resident writer finishes the effect once the file matches one of its recorded versions.';
+const choiceRefused = (reason: string, sourceId: string) => catalogueError('recovery_choice_refused', reason,
+ `Nothing was changed. Inspect the request read-only with gbrain sources writer status --source ${sourceId} --json and follow the guidance for its blocked reason.`);
+
+async function readJournal(engine: BrainEngine, key: string): Promise<Journal | null> {
+ const [row] = await engine.executeRaw<{ completed_keys: Journal[] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [RESOLUTION_OP, key]);
+ return row?.completed_keys?.[0] ?? null;
+}
+async function writeJournal(engine: BrainEngine, key: string, journal: Journal): Promise<void> {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`, [RESOLUTION_OP, key, JSON.stringify([journal])]);
+}
+/** The finished resolutions recorded under one preview hash (the audit entries an identical apply replays). */
+export async function readResolutions(engine: BrainEngine, previewHash: string): Promise<Journal[]> {
+ const rows = await engine.executeRaw<{ completed_keys: Journal[] }>("SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'preview_hash'=$2 ORDER BY fingerprint",
+ [RESOLUTION_OP, previewHash]);
+ return rows.map(row => row.completed_keys[0]);
+}
+
+/**
+ * `--keep disk`: ends the live request terminal without touching its record. With no recorded failure it ends `conflict`
+ * (`source_changed`); a recorded failure ends it by the owner's rule (`finishUnpublishedFailure`), except the two
+ * reprepare codes, which that helper would requeue and which are conflicts.
+ */
+async function abandonWrite(engine: BrainEngine, row: WriteRequest, previewHash: string): Promise<void> {
+ if (!row.error_code) {
+ await engine.transaction(tx => completeWrite(tx, row, 'conflict', {}, { code: 'source_changed',
+ message: `Publication abandoned by gbrain repair stuck-recovery --keep disk (preview ${previewHash.slice(0, 12)}): the canonical file was kept as edited on disk.` }));
+ return;
+ }
+ const recorded = new OperationError(row.error_code, row.error_message ?? 'Publication failed before database completion.',
+ `Read request ${row.request_id}'s receipt with gbrain write-request -- ${row.request_id}; the canonical file was kept as edited on disk.`);
+ if (!mayReprepare(row, recorded) && !transientDatabaseFailure(recorded)) { await finishUnpublishedFailure(engine, row, recorded); return; }
+ await engine.transaction(tx => completeWrite(tx, row, mayReprepare(row, recorded) ? 'conflict' : 'failed', {}, { code: recorded.code, message: recorded.message }));
+}
+
+const sameIdentity = (row: WriteRequest | null, item: StuckRecovery) => !!row?.recovery && row.recovery.version === 1
+ && digest(identityOf(recoveryFiles(row.recovery), row.recovery)) === digest(item.identity);
+
+function nextStep(item: StuckRecovery, keep: KeepChoice, state: string): string {
+ if (keep === 'disk') return `The bytes on disk are kept and the write's publication was abandoned (request ${state}); the database page still holds the content before the write, `
+ + `so the page shows as file/database drift until it is reconciled. Next: gbrain sources reconcile ${item.source_id} ${item.slug} --brain host --preview. This command does not mark the page repaired.`;
+ return state === 'queued' ? 'The prior bytes are back on disk and the write was requeued: the resident writer publishes it again on its next pass.'
+ : `The prior bytes are back on disk and the write ended ${state}; read its receipt with gbrain write-request -- ${item.request_id}.`;
+}
+
+/**
+ * Resolves one approved record (see the module comment). Runs on the owner host under the worktree lock; a run
+ * killed at any step resumes from its journal, and an identical apply after success returns the recorded result.
+ */
+export async function resolveStuckRecovery(engine: BrainEngine, item: StuckRecovery, opts: { keep: KeepChoice; previewHash: string; hostId?: string; lockWaitMs?: number }):
+Promise<ResolutionResult & { replayed: boolean }> {
+ const hostId = opts.hostId ?? localHostId();
+ const key = `${item.id}:${opts.previewHash}`;
+ const command = stuckRecoveryPreviewCommand([item.source_id], item.request_id);
+ let journal = await readJournal(engine, key);
+ if (journal && journal.keep !== opts.keep) throw opError('idempotency_conflict', `Preview ${opts.previewHash.slice(0, 12)} of request ${item.request_id} was ${journal.phase === 'done' ? 'resolved' : 'started'} with --keep ${journal.keep}.`,
+ `Nothing was changed. ${journal.phase === 'done' ? 'That resolution is final' : `Finish it with the same choice: rerun the apply with --keep ${journal.keep}`}; for a different choice, preview again (${command}) and apply the new hash.`);
+ if (journal?.phase === 'done' && journal.result) return { ...journal.result, replayed: true };
+ const binding = ownerBinding(await getWorktreeBinding(engine, item.source_id, hostId), item.source_id, hostId);
+ const lock = await acquireWorktree(binding, opts.lockWaitMs ?? 10_000, undefined, engine, { yieldLanes: true });
+ if (!lock) throw opError('writer_lock_unavailable', `Source ${item.source_id}'s worktree lock is held by another writer, so the recovery of request ${item.request_id} was not resolved.`,
+ `Nothing was changed. Rerun the same apply in a few seconds; if it stays busy, inspect the holder with gbrain sources writer status --source ${item.source_id} --json.`, { fix: statusFix(item.source_id) });
+ try {
+ let row = await getWriteRequestById(engine, item.id);
+ if (!journal) {
+ if (!sameIdentity(row, item)) throw previewChangedError(opts.previewHash, command);
+ if (isTerminal(row!)) throw choiceRefused(terminalReason(row!), item.source_id);
+ const current = await readItem(engine, row!, binding);
+ if (current.item.digest !== item.digest) throw previewChangedError(opts.previewHash, command);
+ if (!current.item.choices[opts.keep]) throw catalogueError('recovery_choice_refused', `--keep ${opts.keep} is not available for request ${item.request_id}: `
+ + (opts.keep === 'prior' ? 'the recovery record does not hold the prior bytes, or a blocked file is not a regular file.' : 'a blocked file is not a regular file.'),
+ `Nothing was changed. The preview lists the available choices; run it again (${command}) and apply one of those.`);
+ const dir = await privateBackupDir(engine, item.request_id, item.digest.slice(0, 16));
+ writeArtifacts(dir, current.item, current.records, current.disks);
+ await faultPoint('stuck_recovery:backed_up', { requestId: item.request_id, sourceId: item.source_id });
+ journal = { id: item.id, request_id: item.request_id, source_id: item.source_id, slug: item.slug, preview_hash: opts.previewHash, keep: opts.keep, phase: 'backed_up',
+ backup_dir: dir, original: { state: row!.state, blocked_reason: row!.blocked_reason ?? null, prior_hashes: item.prior_hashes,
+ disk_hashes: item.files.map(file => file.disk.deleted ? null : file.disk.sha256) } };
+ await writeJournal(engine, key, journal);
+ }
+ if (journal.phase === 'backed_up' && sameIdentity(row, item)) {
+ const records = recoveryFiles(row!.recovery!);
+ const unexpected = records.map((record, index) => ({ record, index })).filter(({ index }) => item.files[index].matches === 'neither');
+ for (const { record, index } of unexpected) {
+ const hash = diskView(record.path).view;
+ const now = hash.deleted ? null : hash.sha256;
+ const allowed = opts.keep === 'prior' ? [journal.original.disk_hashes[index], item.prior_hashes[index]] : [journal.original.disk_hashes[index]];
+ if (!allowed.includes(now)) throw opError('unexpected_file_bytes', `A canonical file of request ${item.request_id} changed again after the preview, so the resolution stopped before touching it.`,
+ `Nothing more was changed; the bytes from the preview are backed up under ${journal.backup_dir}. Preview again (${command}), show the user the new diff and apply the new hash.`, { fix: statusFix(item.source_id) });
+ }
+ if (opts.keep === 'prior') {
+ await upgradeRecoveryStaging(engine, 'persistence_requests', item.id, item.worktree_id, 'restore');
+ const staged = recoveryFiles((await getWriteRequestById(engine, item.id))!.recovery!);
+ await withFilesystemPublication([...new Set(staged.map(record => record.root))], async () => {
+ for (const { index } of unexpected) {
+ const record = staged[index];
+ cleanupRecoveryStaging(record);
+ publishPersistenceFile({ path: record.path, root: record.root, content: priorBytes(record) }, record.staging?.restoration?.path, undefined, record.mode);
+ }
+ });
+ await faultPoint('stuck_recovery:written', { requestId: item.request_id, sourceId: item.source_id });
+ journal = { ...journal, phase: 'written' };
+ await writeJournal(engine, key, journal);
+ } else {
+ if (!isTerminal(row!)) await abandonWrite(engine, row!, opts.previewHash);
+ journal = { ...journal, phase: 'abandoned' };
+ await writeJournal(engine, key, journal);
+ await faultPoint('stuck_recovery:abandoned', { requestId: item.request_id, sourceId: item.source_id });
+ }
+ row = await getWriteRequestById(engine, item.id);
+ }
+ const ours = sameIdentity(row, item);
+ const recovered = ours ? await recoverPublication(engine, item.id, hostId, true) : row!;
+ await faultPoint('stuck_recovery:recovered', { requestId: item.request_id, sourceId: item.source_id });
+ const blocked = sameIdentity(recovered, item);
+ const result: ResolutionResult = { outcome: blocked ? 'still_blocked' : 'resolved', keep: opts.keep, request_state: recovered.state,
+ blocked_reason: blocked ? recovered.blocked_reason ?? null : null, finished_by: ours ? 'this_run' : 'another_pass', backup_dir: journal.backup_dir,
+ next: blocked ? `The recovery is still blocked (${recovered.blocked_reason ?? 'recovering'}); rerun the same apply, or inspect it with gbrain sources writer status --source ${item.source_id} --json.`
+ : nextStep(item, opts.keep, recovered.state) };
+ if (!blocked) await writeJournal(engine, key, { ...journal, phase: 'done', result });
+ return { ...result, replayed: false };
+ } finally { await lock.release(); }
+}
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 80d121fd1e..79d2e3b743 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -35,7 +35,7 @@ import type { RepairKindSpec } from './registry.ts';
import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'stuck-recovery'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
@@ -86,7 +86,9 @@ export interface RepairListing { item: string; class: string; detail?: string }
export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[];
noLlm?: boolean; maxLlmUsd?: number; deadline?: number;
/** `ctx.remote !== false` of the run: a remote caller's plan never names a local path (unset reads as remote). */
- remote?: boolean }
+ remote?: boolean;
+ /** `stuck-recovery`: the version an apply keeps, and the one request a run selects. */
+ keep?: 'prior' | 'disk'; requestId?: string }
export interface RepairHandler {
kind: RepairKind;
@@ -266,6 +268,7 @@ function writerHeld(error: unknown): error is OperationError {
export async function runRepair(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,
opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];
explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;
+ keep?: 'prior' | 'disk'; requestId?: string;
spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;
/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */
publicationOwner?: () => Promise<{ alive: boolean; owner: string }> }): Promise<RepairResult> {
@@ -277,7 +280,8 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
const now = opts.now ?? Date.now;
const planOpts: RepairPlanOptions = { apply: opts.apply, expect: opts.expect, includeAmbiguous: opts.includeAmbiguous, only: opts.only, skip: opts.skip,
...(opts.slugs?.length ? { slugs: opts.slugs } : {}), ...(opts.noLlm ? { noLlm: true } : {}), ...(opts.maxLlmUsd !== undefined ? { maxLlmUsd: opts.maxLlmUsd } : {}),
- ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), remote: ctx.remote !== false };
+ ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), remote: ctx.remote !== false,
+ ...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}) };
const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);
const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;
const counters = await capacity(ctx);
@@ -298,6 +302,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
capacity: counters.map(({ scope: key, resource, used, limit, stop_at }) => ({ scope: key, resource, used, limit, stop_at })),
resumed_from: resumed, applied: 0, skipped: 0, failed: [], complete: false, ...(plan.warnings?.length ? { warnings: plan.warnings } : {}),
apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')}`
+ + `${opts.requestId ? ` --request-id ${opts.requestId}` : ''}${opts.keep ? ` --keep ${opts.keep}` : ''}`
+ `${[...(opts.only ?? []).flatMap(path => ['--only', path]), ...(opts.skip ?? []).flatMap(path => ['--skip', path]),
...(opts.slugs ?? []).flatMap(slug => ['--slug', slug])].map(arg => ` ${shellQuote([arg])}`).join('')}`
+ `${opts.includeAmbiguous ? ' --include-ambiguous' : ''}${llm && opts.noLlm ? ' --no-llm' : ''}${llm && opts.maxLlmUsd !== undefined ? ` --max-usd ${opts.maxLlmUsd}` : ''}`
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 3b4b0bcb84..5ae17b35ce 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -61,6 +61,7 @@ import { plannerStatsRepair } from './planner-stats.ts';
import { fencesRepair } from './fences.ts';
import { slugConflictsRepair } from './slug-conflicts.ts';
import { frontmatterKeysRepair } from './frontmatter-keys.ts';
+import { stuckRecoveryRepair } from './stuck-recovery.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
@@ -267,6 +268,21 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'to 1,000 pages, no file, body or embedding change. Each swept page advances its knowledge_revision once (a client holding an older revision '
+ 'gets one revision_conflict). Preview-bound: --apply --expect <hash> sweeps exactly the previewed set; runs only when named.',
},
+ 'stuck-recovery': {
+ handler: stuckRecoveryRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',
+ consentText: {
+ what: 'Resolve the previewed stuck publication recovery by keeping the chosen version of each blocked file',
+ why: 'The preview listed each blocked file with its recorded prior and its bytes on disk and wrote their diff; the apply keeps the version the user chose so the owner can finish the recovery.',
+ risk: 'Both the disk bytes and the prior bytes are backed up under ~/.gbrain/backups/stuck-recovery/ before anything changes. --keep prior overwrites the edited file and lets the accepted write publish again; --keep disk keeps the edit and abandons the write (it ends conflict). Terminal requests are never changed.',
+ user_message: 'Resolve the stuck recovery as previewed? The other version is kept only in the backup directory',
+ },
+ summary: 'Resolve a page publication recovery blocked on unexpected_file_bytes (#6650): a file that matches neither its recorded prior nor its '
+ + 'published bytes, which stops every write on its worktree. The preview starts from the head blocker, lists each file of each blocked record '
+ + '(prior and disk hash, size and mode) and writes a private diff to ~/.gbrain/backups/stuck-recovery/. --request-id <uuid> selects one request. '
+ + 'Apply on the owner host with --apply --expect <hash> --keep prior|disk --yes (no default): both versions are backed up first; prior writes the recorded '
+ + 'bytes back and the accepted write publishes again, disk keeps the edit and abandons the write (reconcile the page afterwards). A terminal request is '
+ + 'refused (recovery_choice_refused). Runs only when named.',
+ },
};
export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));
@@ -349,13 +365,13 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
* `maxLlmUsd`: what this run may spend on a paid chat model (`spends: 'llm'` kinds; undefined = no run cap).
*/
async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];
- slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number } = {}): Promise<RepairResult> {
+ slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number; keep?: 'prior' | 'disk'; requestId?: string } = {}): Promise<RepairResult> {
const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;
const spec = repairSpec(kind, opts.registry);
return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag, spec,
embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : [],
explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,
- maxLlmUsd: run.maxLlmUsd, deadline: run.deadline });
+ maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, keep: run.keep, requestId: run.requestId });
},
};
}
diff --git a/src/core/repair/stuck-recovery.ts b/src/core/repair/stuck-recovery.ts
new file mode 100644
index 0000000000..8a3713f21b
--- /dev/null
+++ b/src/core/repair/stuck-recovery.ts
@@ -0,0 +1,117 @@
+/**
+ * `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10): the repair-kind adapter for
+ * `persistence/recovery-resolve.ts`. Explicit-only, preview-bound and destructive-consent: the preview lists each
+ * recovery record blocked on unexpected bytes (prior and disk fingerprints, a private diff, the choices available)
+ * and saves the set under its hash; `--apply --expect <hash> --keep prior|disk --yes` resolves exactly that set. There is no
+ * default `--keep`, and a terminal request is listed as refused (see recovery-resolve.ts for the per-state semantics).
+ * Projection-only: no journal admission; each record finishes through the owner's own `recoverPublication`.
+ */
+import { OperationError } from '../ops/contract.ts';
+import { loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { readResolutions, resolveStuckRecovery, scanStuckRecoveries, stuckRecoveryPreviewCommand, type KeepChoice, type RecoveryFileView, type RefusedRecovery, type StuckRecovery }
+ from '../persistence/recovery-resolve.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
+
+type Selection = { sources: string[]; request_id: string | null };
+type ApprovedRecovery = StuckRecovery & { selection: Selection };
+type RecoveryItem = RepairItem & { recovery: StuckRecovery; hash: string; keep: KeepChoice };
+
+const CHOICE_TEXT: Record<KeepChoice, string> = {
+ prior: 'discard the edit: write the recorded prior bytes back (unlink the file when the prior was a create); the owner then finishes the recovery by its own rule, '
+ + 'so a request with no recorded failure is requeued and its write publishes again, and one with a failure ends with it',
+ disk: 'keep the edit and abandon the write: the request ends conflict (source_changed), or with the failure it already recorded, and its recovery record is '
+ + 'cleared; the database page keeps the content before the write, so reconcile the page afterwards',
+};
+
+function item(recovery: StuckRecovery, index: number, hash: string, keep: KeepChoice): RecoveryItem {
+ return { cursor: { phase: 0, id: index + 1 }, source_id: recovery.source_id, slug: recovery.slug, chars: 0, action: `resolve_keep_${keep}`,
+ change: { from: recovery.digest, to: keep }, recovery, hash, keep };
+}
+
+const selectionOf = (scope: RepairScope, requestId?: string): Selection => ({ sources: scope.source_ids, request_id: requestId ?? null });
+const hashOf = (scope: RepairScope, selection: Selection, items: StuckRecovery[]) =>
+ previewHash({ kind: 'stuck-recovery-v1', brain_id: scope.brain_id, selection, items: items.map(found => found.digest) });
+
+function fileLines(file: RecoveryFileView): string[] {
+ const prior = file.prior.absent ? 'absent: prior was a create'
+ : `sha256 ${file.prior.sha256.slice(0, 16)}… size ${file.prior.size ?? '?'} mode ${file.prior.mode === null ? '?' : file.prior.mode.toString(8)}${file.prior.stored ? '' : ' (bytes not stored in the record)'}`;
+ const disk = file.disk.deleted ? 'deleted on disk' : file.disk.kind !== 'file' ? `${file.disk.kind} (not a regular file; resolve it by hand)`
+ : `sha256 ${file.disk.sha256!.slice(0, 16)}… size ${file.disk.size} mode ${file.disk.mode.toString(8)}`;
+ return [` file ${file.relative}`, ` prior: ${prior}`, ` disk: ${disk}`,
+ ` recovery sees: ${file.matches === 'neither' ? 'neither the prior nor the published bytes (blocked)' : `the ${file.matches} bytes`}`,
+ ...(file.diff_path ? [` diff: ${file.diff_path}`, ` reproduce: ${file.diff_command}`] : [])];
+}
+
+export const stuckRecoveryRepair: RepairHandler = {
+ kind: 'stuck-recovery',
+ publication: 'projection',
+ embeds: false,
+ outcomeItemsLimit: 1000,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const command = stuckRecoveryPreviewCommand(scope.source_ids, opts?.requestId);
+ const selection = selectionOf(scope, opts?.requestId);
+ if (!opts?.apply) {
+ const scan = await scanStuckRecoveries(engine, scope.source_ids, { requestId: opts?.requestId, artifacts: opts?.remote === false });
+ const hash = hashOf(scope, selection, scan.items);
+ if (scan.items.length) await saveApprovedSet<ApprovedRecovery>(engine, { command: 'stuck-recovery', hash }, scan.items.map(found => ({ ...found, selection })));
+ const apply = (keep: KeepChoice) => `${command} --keep ${keep} --apply --expect ${hash} --yes`;
+ return { items: scan.items.map((found, index) => item(found, index, hash, 'prior')), preview_hash: hash, residuals: scan.residuals,
+ listing: scan.items.map(found => ({ item: `${found.source_id}:${found.slug}`, class: 'unexpected_file_bytes',
+ detail: `request ${found.request_id}, ${found.files.filter(file => file.matches === 'neither').length} of ${found.files.length} file(s) match neither recorded version` })),
+ details: { recoveries: scan.items, heads: scan.heads, refused: scan.refused,
+ choices: (['prior', 'disk'] as const).filter(keep => scan.items.length && scan.items.every(found => found.choices[keep]))
+ .map(keep => ({ keep, what: CHOICE_TEXT[keep], apply_command: apply(keep) })) } };
+ }
+ if (!opts.expect || !opts.keep) {
+ throw new OperationError('invalid_params', 'gbrain repair stuck-recovery --apply needs the preview hash and the version to keep.',
+ `Preview first: ${command} — show the user the diff it prints, then run the choice they pick: ${command} --keep prior --apply --expect <preview-hash> --yes, `
+ + `or ${command} --keep disk --apply --expect <preview-hash> --yes`, 'docs/guides/repair.md#stuck-recovery');
+ }
+ const { expect, keep } = opts;
+ let approved: ApprovedRecovery[];
+ try {
+ approved = (await loadApprovedSet<ApprovedRecovery>(engine, { command: 'stuck-recovery', hash: expect, previewCommand: command,
+ emptyHash: async () => hashOf(scope, selection, (await scanStuckRecoveries(engine, scope.source_ids, { requestId: opts.requestId })).items) })).items;
+ } catch (error) {
+ // An identical apply after the approved set aged out still replays its recorded resolutions.
+ const done = await readResolutions(engine, expect);
+ if (!done.length || done.some(entry => entry.phase !== 'done')) throw error;
+ approved = done.map(entry => ({ id: entry.id, request_id: entry.request_id, source_id: entry.source_id, slug: entry.slug, selection } as ApprovedRecovery));
+ }
+ if (approved.some(entry => JSON.stringify(entry.selection) !== JSON.stringify(selection))) throw previewChangedError(expect, command);
+ const started = new Set((await readResolutions(engine, expect)).map(entry => entry.id));
+ const fresh = approved.filter(entry => !started.has(entry.id));
+ if (fresh.length) {
+ // Re-verify the preview before anything is written: every record not yet started still has the bytes and revision the user saw.
+ const current = await scanStuckRecoveries(engine, scope.source_ids);
+ const digests = new Map(current.items.map(found => [found.id, found.digest]));
+ if (fresh.some(entry => digests.get(entry.id) !== entry.digest)) throw previewChangedError(expect, command);
+ }
+ const items = approved.map(({ selection: _selection, ...recovery }, index) => item(recovery, index, expect, keep));
+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: expect, residuals: {} };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { recovery, hash, keep } = entry as RecoveryItem;
+ const result = await resolveStuckRecovery(ctx.engine, recovery, { keep, previewHash: hash });
+ return { applied: result.outcome === 'resolved' && !result.replayed, outcome: result.replayed ? 'replayed' : result.outcome,
+ ...(result.blocked_reason ? { reason: result.blocked_reason } : {}),
+ detail: { request_id: recovery.request_id, keep, request_state: result.request_state, finished_by: result.finished_by, backup_dir: result.backup_dir, next: result.next } };
+ },
+ render(details) {
+ const recoveries = (details.recoveries ?? []) as StuckRecovery[];
+ const heads = (details.heads ?? []) as Array<{ source_id: string; queued_request_id: string | null; blocked_by: string | null }>;
+ const choices = (details.choices ?? []) as Array<{ keep: KeepChoice; what: string; apply_command: string }>;
+ const lines: string[] = [];
+ for (const head of heads) if (head.queued_request_id) lines.push(` source ${head.source_id}: queued write ${head.queued_request_id} is blocked by ${head.blocked_by ?? 'nothing known'}`);
+ for (const found of recoveries) {
+ lines.push(` request ${found.request_id} (${found.operation} ${found.source_id}:${found.slug}, ${found.state}${found.blocked_reason ? `, ${found.blocked_reason}` : ''}; page revision ${found.page_revision ?? 'none'})`);
+ lines.push(` ${found.recorded_error ? `recorded failure ${found.recorded_error}: either choice ends the request with it` : 'no recorded failure: --keep prior requeues the write, --keep disk abandons it'}`);
+ for (const file of found.files) lines.push(...fileLines(file));
+ }
+ for (const refused of (details.refused ?? []) as RefusedRecovery[]) lines.push(` refused ${refused.effect_id ? `effect ${refused.effect_id} of ` : ''}${refused.request_id} (${refused.source_id}:${refused.slug}, ${refused.state}${refused.blocked_reason ? `, ${refused.blocked_reason}` : ''}) ${refused.code}: ${refused.reason}`);
+ if (recoveries.length && !choices.length) lines.push(' no choice is available for every listed record: resolve the files listed above by hand, then rerun the preview');
+ for (const choice of choices) lines.push(` --keep ${choice.keep}: ${choice.what}.`, ` apply (after the user picks it): ${choice.apply_command}`);
+ if (choices.length) lines.push(' either choice first backs up the disk and prior bytes beside the diff above');
+ return lines;
+ },
+};
diff --git a/test/e2e/repair-stuck-recovery-postgres.test.ts b/test/e2e/repair-stuck-recovery-postgres.test.ts
new file mode 100644
index 0000000000..de16e78c32
--- /dev/null
+++ b/test/e2e/repair-stuck-recovery-postgres.test.ts
@@ -0,0 +1,111 @@
+/**
+ * #6650 §1.10 on real Postgres: a `gbrain repair stuck-recovery` apply SIGKILLed at each of its fault seams (while it
+ * holds the native worktree lock) resumes to the same end state, a write abandoned by `--keep disk` keeps its recovery
+ * record unchanged for the unchanged resident recovery pass to clear, and an identical apply replays.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { getWriteRequestById } from '../../src/core/persistence/journal.ts';
+import { recoverPublication } from '../../src/core/persistence/coordinator.ts';
+import type { FaultPoint } from '../../src/core/persistence/fault-points.ts';
+import { sha256 } from '../../src/core/persistence/digest.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { AFTER, EDITED, PRIOR, stuckRecoveryFixture } from '../helpers/stuck-recovery-fixture.ts';
+
+const url = process.env.DATABASE_URL;
+const WORKER = resolve(import.meta.dir, '../fixtures/stuck-recovery-worker.ts');
+
+describe.skipIf(!url)('gbrain repair stuck-recovery on Postgres', () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-stuck-recovery-pg-'));
+ const roots: string[] = [];
+ let admin: ReturnType<typeof postgres>;
+ let database: string;
+ let databaseUrl: string;
+ let engine: PostgresEngine;
+ const run = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);
+ const fixture = () => stuckRecoveryFixture(engine, roots);
+
+ beforeAll(async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ admin = postgres(url!, { max: 1, prepare: false, onnotice() {} });
+ database = `gbrain_test_stuck_recovery_${randomUUID().replaceAll('-', '')}`;
+ await admin.unsafe(`CREATE DATABASE ${database}`);
+ const target = new URL(url!); target.pathname = `/${database}`; databaseUrl = target.toString();
+ engine = new PostgresEngine();
+ await engine.connect({ database_url: databaseUrl, poolSize: 4 });
+ await engine.initSchema();
+ await run(() => registerLocalWriter(engine, 'cli'));
+ }, 180_000);
+
+ afterAll(async () => {
+ await engine?.disconnect();
+ if (database) await admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`);
+ await admin?.end({ timeout: 1 });
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ /** Runs the apply in a child that blocks at `point`, waits for it to get there, then SIGKILLs it. */
+ async function killAt(sourceId: string, hash: string, keep: 'prior' | 'disk', point: FaultPoint): Promise<void> {
+ const configPath = join(home, `worker-${randomUUID()}.json`);
+ writeFileSync(configPath, JSON.stringify({ databaseUrl, sourceId, hash, keep, point }), { mode: 0o600 });
+ const env = { ...process.env, GBRAIN_HOME: home } as Record<string, string>;
+ delete env.DATABASE_URL;
+ const child = Bun.spawn([process.execPath, '--no-env-file', WORKER, configPath], { env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const decoder = new TextDecoder();
+ let output = '';
+ const reader = child.stdout.getReader();
+ const deadline = Date.now() + 60_000;
+ while (!output.includes('"event":"boundary"')) {
+ if (output.includes('"event":"failure"') || output.includes('"event":"done"')) throw new Error(`worker ended before ${point}: ${output}`);
+ if (Date.now() > deadline) throw new Error(`worker never reached ${point}: ${output}`);
+ const { value, done } = await reader.read();
+ if (done) throw new Error(`worker exited before ${point}: ${output}${await new Response(child.stderr).text()}`);
+ output += decoder.decode(value, { stream: true });
+ }
+ expect(child.exitCode).toBeNull();
+ child.kill('SIGKILL');
+ await child.exited;
+ expect(child.signalCode).toBe('SIGKILL');
+ }
+
+ const KILLS: Array<[FaultPoint, 'prior' | 'disk', string, boolean]> = [
+ ['stuck_recovery:backed_up', 'prior', EDITED, true], ['stuck_recovery:written', 'prior', PRIOR, true], ['stuck_recovery:recovered', 'prior', PRIOR, false],
+ ['stuck_recovery:backed_up', 'disk', EDITED, true], ['stuck_recovery:abandoned', 'disk', EDITED, true], ['stuck_recovery:recovered', 'disk', EDITED, false],
+ ];
+ for (const [point, keep, fileAtKill, recoveryAtKill] of KILLS) {
+ test(`SIGKILL at ${point} (--keep ${keep}) resumes to the same end state`, () => run(async () => {
+ const s = await fixture().stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const hash = (await fixture().repair(s.sourceId)).preview_hash!;
+ await killAt(s.sourceId, hash, keep, point);
+ expect(readFileSync(s.path, 'utf8')).toBe(fileAtKill);
+ expect((await getWriteRequestById(engine, s.id))!.recovery !== null).toBe(recoveryAtKill);
+ const [shape] = await engine.executeRaw<{ kind: string | null }>('SELECT jsonb_typeof(recovery) AS kind FROM persistence_requests WHERE id=$1::uuid', [s.id]);
+ expect(shape.kind).toBe(recoveryAtKill ? 'object' : null);
+ const resumed = await fixture().repair(s.sourceId, { apply: true, expect: hash, keep });
+ expect(resumed.outcomes).toEqual({ resolved: 1 });
+ expect(readFileSync(s.path, 'utf8')).toBe(keep === 'prior' ? PRIOR : EDITED);
+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: keep === 'prior' ? 'queued' : 'conflict', recovery: null });
+ expect((await fixture().repair(s.sourceId, { apply: true, expect: hash, keep })).outcomes).toEqual({ replayed: 1 });
+ }), 120_000);
+ }
+
+ test('mixed version: after a SIGKILL once the write is abandoned, the unchanged resident recovery pass ends the abandoned write conflict', () => run(async () => {
+ const s = await fixture().stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const hash = (await fixture().repair(s.sourceId)).preview_hash!;
+ await killAt(s.sourceId, hash, 'disk', 'stuck_recovery:abandoned');
+ const [record] = await engine.executeRaw<{ before_hash: string; state: string }>("SELECT recovery->>'beforeHash' AS before_hash,state FROM persistence_requests WHERE id=$1::uuid", [s.id]);
+ expect(record).toEqual({ before_hash: sha256(PRIOR), state: 'conflict' });
+ expect(await recoverPublication(engine, s.id)).toMatchObject({ state: 'conflict', error_code: 'source_changed', recovery: null });
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ const resumed = await fixture().repair(s.sourceId, { apply: true, expect: hash, keep: 'disk' });
+ expect(resumed.outcome_items![0]!.detail).toMatchObject({ finished_by: 'another_pass', request_state: 'conflict' });
+ }), 120_000);
+});
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index c21d99a241..a25430be72 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -195,7 +195,8 @@ for (const backend of testBackends()) {
const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };
const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts',
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes',
- frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys' };
+ frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys',
+ 'stuck-recovery': 'gbrain repair stuck-recovery' };
// The post-upgrade banner names both findings with the kind's read-only preview.
const banner = await postUpgradeRecoveryBanner(engine, 'host');
diff --git a/test/fixtures/stuck-recovery-worker.ts b/test/fixtures/stuck-recovery-worker.ts
new file mode 100644
index 0000000000..65c07bf720
--- /dev/null
+++ b/test/fixtures/stuck-recovery-worker.ts
@@ -0,0 +1,36 @@
+/**
+ * Child process for `test/e2e/repair-stuck-recovery-postgres.test.ts` (#6650): runs one
+ * `gbrain repair stuck-recovery` apply against a Postgres test database and blocks at the named fault seam, so the
+ * parent can SIGKILL it there while it holds the worktree lock and the journal is mid-step.
+ * Prints one JSON line per event on stdout: `{event:'boundary', point}` or `{event:'done', outcomes}` / `{event:'failure', message}`.
+ */
+import { readFileSync } from 'node:fs';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { installFaultHook, type FaultPoint } from '../../src/core/persistence/fault-points.ts';
+import { resolveRepairScope } from '../../src/core/repair/core.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+
+interface WorkerConfig { databaseUrl: string; sourceId: string; hash: string; keep: 'prior' | 'disk'; point: FaultPoint }
+const emit = (event: Record<string, unknown>) => process.stdout.write(`${JSON.stringify(event)}\n`);
+
+if (import.meta.main) {
+ const config: WorkerConfig = JSON.parse(readFileSync(process.argv[2]!, 'utf8'));
+ const engine = new PostgresEngine();
+ try {
+ await engine.connect({ database_url: config.databaseUrl, poolSize: 2 });
+ installFaultHook(async point => {
+ if (point !== config.point) return;
+ emit({ event: 'boundary', point });
+ await new Promise(() => {});
+ });
+ const runner = await repairRunner(engine, { apply: true });
+ const result = await runner.run('stuck-recovery', await resolveRepairScope(engine, config.sourceId),
+ { sourceFlag: config.sourceId, explicit: true, expect: config.hash, keep: config.keep });
+ emit({ event: 'done', outcomes: result.outcomes ?? {} });
+ await engine.disconnect();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Unknown worker failure';
+ emit({ event: 'failure', message: message.replaceAll(config.databaseUrl, '[test database]') });
+ process.exit(1);
+ }
+}
diff --git a/test/helpers/stuck-recovery-fixture.ts b/test/helpers/stuck-recovery-fixture.ts
new file mode 100644
index 0000000000..adbb786e9c
--- /dev/null
+++ b/test/helpers/stuck-recovery-fixture.ts
@@ -0,0 +1,70 @@
+/**
+ * #6650: the real `unexpected_file_bytes` blocked state, shared by the PGLite unit test and the Postgres E2E.
+ * A source is claimed on this host; a write is admitted, claimed and records its recovery (prior bytes on disk),
+ * the file is edited by hand, and one owner recovery pass parks the request.
+ */
+import { existsSync, mkdtempSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { expect } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';
+import { submissionAuthority } from '../../src/core/persistence/authority.ts';
+import { admitWrite, prepareRecovery } from '../../src/core/persistence/journal.ts';
+import { recoverPublication } from '../../src/core/persistence/coordinator.ts';
+import { sha256 } from '../../src/core/persistence/digest.ts';
+import { resolveRepairScope, type RepairResult } from '../../src/core/repair/core.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+
+export const PRIOR = 'line one\nline two\nline three\n';
+export const AFTER = 'line one\nline two\nline three\nappended by the write\n';
+export const EDITED = 'line one\nline two, edited by hand\nline three\n';
+
+export interface Stuck { sourceId: string; root: string; path: string; id: string; requestId: string; follower: string | null }
+
+let counter = 0;
+
+export function stuckRecoveryFixture(engine: BrainEngine, roots: string[]) {
+ const ctxFor = (sourceId: string) => ({ engine, remote: false, sourceId, config: { engine: engine.kind }, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } } as OperationContext);
+
+ async function source(): Promise<{ sourceId: string; root: string }> {
+ const sourceId = `stuck-${process.pid}-${++counter}`;
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-stuck-root-')); roots.push(root);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ return { sourceId, root };
+ }
+
+ async function stuck(opts: { prior: string | null; after: string; disk: string | null; slug?: string; failed?: boolean; follower?: boolean; at?: { sourceId: string; root: string } }): Promise<Stuck> {
+ const { sourceId, root } = opts.at ?? await source();
+ const slug = opts.slug ?? 'page';
+ const path = join(root, `${slug}.md`);
+ if (opts.prior !== null) writeFileSync(path, opts.prior, { mode: 0o644 });
+ const binding = (await getWorktreeBinding(engine, sourceId))!;
+ const authority = await submissionAuthority(ctxFor(sourceId), 'put_page', sourceId, binding.source_incarnation, slug);
+ const admission = { principal: authority.principal, authority, operation: 'put_page', sourceId, sourceIncarnation: binding.source_incarnation, slug,
+ worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation, callerIntent: { content: opts.after }, intent: { content: opts.after } };
+ const accepted = await admitWrite(engine, admission);
+ const [row] = await engine.executeRaw<any>(`UPDATE persistence_requests SET state='running',execution_token=gen_random_uuid(),claim_expires_at=now()+interval '1 hour'
+ ${opts.failed ? ",error_code='storage_error',error_message='Publication failed before database completion.'" : ''} WHERE id=$1::uuid RETURNING *`, [accepted.id]);
+ const lock = await acquireWorktree(binding); expect(lock).not.toBeNull();
+ try {
+ await prepareRecovery(engine, row, { version: 1, path, root, before: opts.prior === null ? null : Buffer.from(opts.prior).toString('base64'),
+ beforeHash: opts.prior === null ? null : sha256(opts.prior), afterHash: sha256(opts.after), mode: 0o644, ownerEpoch: String(binding.owner_epoch), attempt: row.execution_token }, 65536);
+ } finally { await lock!.release(); }
+ if (opts.disk === null) { if (existsSync(path)) unlinkSync(path); } else writeFileSync(path, opts.disk);
+ await engine.executeRaw("UPDATE persistence_requests SET state='recovering' WHERE id=$1::uuid", [row.id]);
+ expect(await recoverPublication(engine, row.id)).toMatchObject({ state: 'recovering', blocked_reason: 'unexpected_file_bytes' });
+ const follower = opts.follower ? (await admitWrite(engine, { ...admission, callerIntent: { content: 'Later' }, intent: { content: 'Later' } })).id : null;
+ return { sourceId, root, path, id: row.id, requestId: row.request_id, follower };
+ }
+
+ async function repair(sourceId: string, opts: { apply?: boolean; expect?: string; keep?: 'prior' | 'disk'; requestId?: string } = {}): Promise<RepairResult> {
+ const runner = await repairRunner(engine, { apply: opts.apply === true });
+ return runner.run('stuck-recovery', await resolveRepairScope(engine, sourceId), { sourceFlag: sourceId, explicit: true, expect: opts.expect, keep: opts.keep, requestId: opts.requestId });
+ }
+
+ return { source, stuck, repair };
+}
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index fc9e344573..4dd216860e 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys'];
+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'stuck-recovery'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));
diff --git a/test/repair-stuck-recovery.test.ts b/test/repair-stuck-recovery.test.ts
new file mode 100644
index 0000000000..e559635c71
--- /dev/null
+++ b/test/repair-stuck-recovery.test.ts
@@ -0,0 +1,431 @@
+/**
+ * #6650 §1.10: `gbrain repair stuck-recovery` resolves a page publication recovery the owner refuses with
+ * unexpected_file_bytes. Every fixture builds the real blocked state (a claimed write with a recovery record, a
+ * human edit of its file, one owner recovery pass that parks it) and resolves it through the registered repair kind.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { getWriteRequestById } from '../src/core/persistence/journal.ts';
+import { recoverPublication } from '../src/core/persistence/coordinator.ts';
+import { readHeadBlockers } from '../src/core/persistence/head-blocker.ts';
+import { installFaultHook, type FaultPoint } from '../src/core/persistence/fault-points.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import { RESOLUTION_OP, resolveStuckRecovery, scanStuckRecoveries } from '../src/core/persistence/recovery-resolve.ts';
+import { acquireWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { REPAIR_KINDS } from '../src/core/repair/core.ts';
+import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, repairRunner, repairSpec } from '../src/core/repair/registry.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { AFTER, EDITED, PRIOR, stuckRecoveryFixture } from './helpers/stuck-recovery-fixture.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-stuck-recovery-'));
+const roots: string[] = [];
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await withEnv({ GBRAIN_HOME: home }, () => registerLocalWriter(engine, 'cli'));
+}, 120_000);
+afterEach(() => installFaultHook(undefined));
+afterAll(async () => {
+ await engine.disconnect();
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+});
+
+const run = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);
+const fixture = () => stuckRecoveryFixture(engine, roots);
+const source = () => fixture().source();
+const stuck = (opts: Parameters<ReturnType<typeof fixture>['stuck']>[0]) => fixture().stuck(opts);
+const repair = (sourceId: string, opts: Parameters<ReturnType<typeof fixture>['repair']>[1] = {}) => fixture().repair(sourceId, opts);
+
+async function refusal(fn: () => Promise<unknown>): Promise<OperationError> {
+ try { await fn(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+
+async function cli(args: string[], env: Record<string, string> = {}): Promise<string> {
+ let printed = '';
+ const original = console.log, write = process.stdout.write;
+ console.log = (...parts: unknown[]) => { printed += `${parts.map(String).join(' ')}\n`; };
+ process.stdout.write = ((chunk: string | Uint8Array) => { printed += String(chunk); return true; }) as typeof process.stdout.write;
+ try { await withEnv({ GBRAIN_HOME: home, ...env }, () => runRepairCommand(engine, args)); } finally { console.log = original; process.stdout.write = write; }
+ return printed;
+}
+
+async function journal(id: string) {
+ return (await engine.executeRaw<{ completed_keys: any[] }>("SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2", [RESOLUTION_OP, `${id}:%`]))
+ .map(row => row.completed_keys[0]);
+}
+
+
+/** The recovery bytes still reserved by the request's worktree, from the rows and from the counter. */
+async function recoveryAccounting(id: string) {
+ const row = (await getWriteRequestById(engine, id))!;
+ const [counts] = await engine.executeRaw<{ reserved: string; counter: string }>(`SELECT (SELECT COALESCE(SUM(recovery_bytes),0) FROM persistence_requests WHERE worktree_id=$1::uuid)::text AS reserved,
+ (SELECT recovery_bytes FROM persistence_counters WHERE key='worktree:'||$1)::text AS counter`, [row.worktree_id]);
+ return { reserved: Number(counts.reserved), counter: Number(counts.counter) };
+}
+
+describe('gbrain repair stuck-recovery', () => {
+ test('is an explicit-only, preview-bound, destructive-consent repair kind that no unnamed runner can start', () => run(async () => {
+ expect(REPAIR_KINDS).toContain('stuck-recovery');
+ expect(EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind)).toContain('stuck-recovery');
+ expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).not.toContain('stuck-recovery');
+ expect(repairSpec('stuck-recovery')).toMatchObject({ explicit_only: true, preview_bound: true, consent: 'destructive', embeds: 'none' });
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const runner = await repairRunner(engine, { apply: true });
+ const unnamed = await refusal(() => runner.run('stuck-recovery', { brain_id: 'host', source_ids: [s.sourceId] }, { keep: 'prior', expect: 'x' }));
+ expect(unnamed.code).toBe('explicit_kind_required');
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ }));
+
+ test('previews a human one-line edit: fingerprints, a private one-hunk diff with its command, the available choices; writes nothing canonical', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED, follower: true });
+ const out = await cli(['stuck-recovery', '--source', s.sourceId]);
+ expect(out).toContain(`request ${s.requestId} (put_page ${s.sourceId}:page, recovering, unexpected_file_bytes`);
+ expect(out).toContain(`queued write`);
+ expect(out).toContain('is blocked by request_recovery');
+ expect(out).toContain(`prior: sha256 ${sha256(PRIOR).slice(0, 16)}… size ${PRIOR.length} mode 644`);
+ expect(out).toContain(`disk: sha256 ${sha256(EDITED).slice(0, 16)}… size ${EDITED.length}`);
+ expect(out).toContain('recovery sees: neither the prior nor the published bytes (blocked)');
+ const diffPath = /diff: (\S+)/.exec(out)![1]!;
+ expect(diffPath.startsWith(join(home, '.gbrain', 'backups', 'stuck-recovery'))).toBe(true);
+ expect(statSync(diffPath).mode & 0o077).toBe(0);
+ const diff = readFileSync(diffPath, 'utf8');
+ expect(diff).toContain('-line two\n');
+ expect(diff).toContain('+line two, edited by hand\n');
+ expect(diff.match(/^@@/gm)).toHaveLength(1);
+ const command = /reproduce: (diff -u \S+ \S+)/.exec(out)![1]!;
+ expect(readFileSync(command.split(' ')[2]!, 'utf8')).toBe(PRIOR);
+ expect(readFileSync(command.split(' ')[3]!, 'utf8')).toBe(EDITED);
+ const hash = /--expect ([0-9a-f]{64})/.exec(out)![1]!;
+ expect(out).toContain(`--keep prior: discard the edit: write the recorded prior bytes back`);
+ expect(out).toContain("no recorded failure: --keep prior requeues the write, --keep disk abandons it");
+ expect(out).toContain(`gbrain repair stuck-recovery --source ${s.sourceId} --keep prior --apply --expect ${hash} --yes`);
+ expect(out).toContain(`gbrain repair stuck-recovery --source ${s.sourceId} --keep disk --apply --expect ${hash} --yes`);
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'recovering', blocked_reason: 'unexpected_file_bytes' });
+ }));
+
+ test('--keep prior writes the prior bytes back, the owner finishes the recovery, and the queued head is claimable again', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED, follower: true });
+ const blockedBy = async () => { const read = (await readHeadBlockers(engine, [s.follower!], localHostId())).get(s.follower!)!; return read.status === 'blocked' ? read.blocker.predicate : read.status; };
+ expect(await blockedBy()).toBe('request_recovery');
+ const preview = await repair(s.sourceId);
+ expect(preview.listing).toHaveLength(1);
+ const result = await repair(s.sourceId, { apply: true, expect: preview.preview_hash, keep: 'prior' });
+ expect(result).toMatchObject({ applied: 1, complete: true, outcomes: { resolved: 1 } });
+ expect(result.apply_command).toContain('--keep prior --apply');
+ expect(readFileSync(s.path, 'utf8')).toBe(PRIOR);
+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'queued', recovery: null, blocked_reason: null });
+ const detail = result.outcome_items![0]!.detail!;
+ expect(detail).toMatchObject({ keep: 'prior', request_state: 'queued', finished_by: 'this_run' });
+ expect(readFileSync(join(String(detail.backup_dir), '0.disk'), 'utf8')).toBe(EDITED);
+ expect(readFileSync(join(String(detail.backup_dir), '0.prior'), 'utf8')).toBe(PRIOR);
+ expect(await blockedBy()).not.toBe('request_recovery');
+ expect((await readHeadBlockers(engine, [s.id], localHostId())).get(s.id)).toEqual({ status: 'claimable' });
+ const [entry] = await journal(s.id);
+ expect(entry).toMatchObject({ phase: 'done', keep: 'prior', request_id: s.requestId, original: { state: 'recovering', blocked_reason: 'unexpected_file_bytes' } });
+ }));
+
+ test('--keep disk (#6640 drop) keeps the edited bytes, abandons the live write as a conflict instead of requeueing it, and hands off to reconcile', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const preview = await repair(s.sourceId);
+ const result = await repair(s.sourceId, { apply: true, expect: preview.preview_hash, keep: 'disk' });
+ expect(result.outcomes).toEqual({ resolved: 1 });
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'conflict', error_code: 'source_changed', recovery: null });
+ const next = String(result.outcome_items![0]!.detail!.next);
+ expect(next).toContain(`gbrain sources reconcile ${s.sourceId} page --brain host --preview`);
+ expect(next).not.toContain('file-drift');
+ expect(next).toContain('does not mark the page repaired');
+ expect(readFileSync(join(String(result.outcome_items![0]!.detail!.backup_dir), '0.prior'), 'utf8')).toBe(PRIOR);
+ }));
+
+ test('absent prior (the write was a create): the preview says so, and --keep prior unlinks the edited file after backing it up', () => run(async () => {
+ const s = await stuck({ prior: null, after: AFTER, disk: EDITED });
+ const out = await cli(['stuck-recovery', '--source', s.sourceId]);
+ expect(out).toContain('prior: absent: prior was a create');
+ expect(out).toContain('reproduce: diff -u /dev/null ');
+ const hash = /--expect ([0-9a-f]{64})/.exec(out)![1]!;
+ const result = await repair(s.sourceId, { apply: true, expect: hash, keep: 'prior' });
+ expect(result.outcomes).toEqual({ resolved: 1 });
+ expect(existsSync(s.path)).toBe(false);
+ expect(readFileSync(join(String(result.outcome_items![0]!.detail!.backup_dir), '0.disk'), 'utf8')).toBe(EDITED);
+ expect((await getWriteRequestById(engine, s.id))!.recovery).toBeNull();
+ }));
+
+ test('a file deleted on disk is previewed as deleted and --keep disk keeps it deleted', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: null });
+ const out = await cli(['stuck-recovery', '--source', s.sourceId]);
+ expect(out).toContain('disk: deleted on disk');
+ const hash = /--expect ([0-9a-f]{64})/.exec(out)![1]!;
+ expect((await repair(s.sourceId, { apply: true, expect: hash, keep: 'disk' })).outcomes).toEqual({ resolved: 1 });
+ expect(existsSync(s.path)).toBe(false);
+ expect((await getWriteRequestById(engine, s.id))!.recovery).toBeNull();
+ }));
+
+ test('a live request with a recorded failure ends with that failure under either choice; --keep disk keeps its error', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED, failed: true });
+ const out = await cli(['stuck-recovery', '--source', s.sourceId]);
+ expect(out).toContain('recorded failure storage_error: either choice ends the request with it');
+ const hash = /--expect ([0-9a-f]{64})/.exec(out)![1]!;
+ await repair(s.sourceId, { apply: true, expect: hash, keep: 'disk' });
+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'failed', error_code: 'storage_error', recovery: null });
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ }));
+
+ test('a terminal request whose recovery record is still set is listed as refused, never resolved: no committed bytes are rolled back', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ await engine.executeRaw("UPDATE persistence_requests SET state='committed',completed_at=now() WHERE id=$1::uuid", [s.id]);
+ const out = await cli(['stuck-recovery', '--source', s.sourceId]);
+ expect(out).toContain(`refused ${s.requestId}`);
+ expect(out).toContain('--keep prior would roll back a committed write');
+ expect(out).not.toContain('--keep prior --apply');
+ const preview = await repair(s.sourceId);
+ expect(preview).toMatchObject({ affected: 0, residuals: { terminal_refused: 1 } });
+ const named = await refusal(() => repair(s.sourceId, { requestId: s.requestId }));
+ expect(named.code).toBe('recovery_choice_refused');
+ expect(named.toJSON()).toMatchObject({ docs: 'docs/guides/repair.md#recovery-choice-refused' });
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'committed', blocked_reason: 'unexpected_file_bytes' });
+ }));
+
+ test('a choice the record cannot support is not offered and its apply refuses recovery_choice_refused', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ await engine.executeRaw(`UPDATE persistence_requests SET recovery=jsonb_set(recovery,'{before}','null'::jsonb) WHERE id=$1::uuid`, [s.id]);
+ const out = await cli(['stuck-recovery', '--source', s.sourceId]);
+ expect(out).toContain('(bytes not stored in the record)');
+ expect(out).not.toContain('--keep prior --apply');
+ expect(out).toContain('--keep disk --apply');
+ const hash = /--expect ([0-9a-f]{64})/.exec(out)![1]!;
+ const error = await refusal(() => repair(s.sourceId, { apply: true, expect: hash, keep: 'prior' }));
+ expect(error.code).toBe('recovery_choice_refused');
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ expect(await journal(s.id)).toEqual([]);
+ }));
+
+ test('multi-file: every blocked record of the root is listed and resolved; --request-id narrows to one', () => run(async () => {
+ const at = await source();
+ const a = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED, slug: 'alpha', at });
+ const b = await stuck({ prior: 'b prior\n', after: 'b after\n', disk: 'b edited\n', slug: 'beta', at });
+ const all = await repair(at.sourceId);
+ expect(all.listing!.map(entry => entry.item)).toEqual([`${at.sourceId}:alpha`, `${at.sourceId}:beta`]);
+ const only = await repair(at.sourceId, { requestId: b.requestId });
+ expect(only.listing!.map(entry => entry.item)).toEqual([`${at.sourceId}:beta`]);
+ expect(only.preview_hash).not.toBe(all.preview_hash);
+ const result = await repair(at.sourceId, { apply: true, expect: all.preview_hash, keep: 'prior' });
+ expect(result).toMatchObject({ applied: 2, outcomes: { resolved: 2 } });
+ expect(readFileSync(a.path, 'utf8')).toBe(PRIOR);
+ expect(readFileSync(b.path, 'utf8')).toBe('b prior\n');
+ for (const id of [a.id, b.id]) expect((await getWriteRequestById(engine, id))!.recovery).toBeNull();
+ }));
+
+ test('the apply re-verifies the preview: an edit after the preview refuses preview_changed and changes nothing', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const preview = await repair(s.sourceId);
+ writeFileSync(s.path, `${EDITED}another edit\n`);
+ const error = await refusal(() => repair(s.sourceId, { apply: true, expect: preview.preview_hash, keep: 'prior' }));
+ expect(error.code).toBe('preview_changed');
+ expect(readFileSync(s.path, 'utf8')).toBe(`${EDITED}another edit\n`);
+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'recovering', blocked_reason: 'unexpected_file_bytes' });
+ expect(await journal(s.id)).toEqual([]);
+ }));
+
+ test('the hash binds the page revision: a database change after the preview refuses preview_changed', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ await engine.putPage('page', { type: 'note', title: 'Page', compiled_truth: 'database body', timeline: '' }, { sourceId: s.sourceId });
+ const preview = await repair(s.sourceId);
+ await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE source_id=$1 AND slug=$2', [s.sourceId, 'page']);
+ expect((await refusal(() => repair(s.sourceId, { apply: true, expect: preview.preview_hash, keep: 'prior' }))).code).toBe('preview_changed');
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ }));
+
+ test('an identical apply after success replays its result; the terminal receipt stays immutable', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED, failed: true });
+ const preview = await repair(s.sourceId);
+ const first = await repair(s.sourceId, { apply: true, expect: preview.preview_hash, keep: 'prior' });
+ expect(first.outcome_items![0]!.detail).toMatchObject({ request_state: 'failed' });
+ const receipt = await getWriteRequestById(engine, s.id);
+ expect(receipt).toMatchObject({ state: 'failed', error_code: 'storage_error', recovery: null });
+ const again = await repair(s.sourceId, { apply: true, expect: preview.preview_hash, keep: 'prior' });
+ expect(again).toMatchObject({ applied: 0, outcomes: { replayed: 1 } });
+ expect(again.outcome_items![0]!.detail).toEqual(first.outcome_items![0]!.detail);
+ expect(await getWriteRequestById(engine, s.id)).toEqual(receipt);
+ expect(readFileSync(s.path, 'utf8')).toBe(PRIOR);
+ const other = await refusal(() => repair(s.sourceId, { apply: true, expect: preview.preview_hash, keep: 'disk' }));
+ expect(other.code).toBe('idempotency_conflict');
+ }));
+
+ test('the CLI apply asks for consent: without --yes a non-interactive run exits 3 with a user_message and changes nothing', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const hash = (await repair(s.sourceId)).preview_hash!;
+ _resetCliExitVerdictForTests();
+ const out = await cli(['stuck-recovery', '--source', s.sourceId, '--keep', 'prior', '--apply', '--expect', hash, '--json'], { GBRAIN_INTERACTIVE: '0', CI: '1' });
+ expect(currentExitCode()).toBe(3);
+ expect(out).toContain('user_message');
+ expect(out).toContain('keep prior');
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ expect(await journal(s.id)).toEqual([]);
+ _resetCliExitVerdictForTests();
+ await cli(['stuck-recovery', '--source', s.sourceId, '--keep', 'prior', '--apply', '--expect', hash, '--yes', '--json'], { GBRAIN_INTERACTIVE: '0', CI: '1' });
+ expect(readFileSync(s.path, 'utf8')).toBe(PRIOR);
+ _resetCliExitVerdictForTests();
+ }));
+
+ test('an apply without --keep is refused with both choices named', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const hash = (await repair(s.sourceId)).preview_hash!;
+ const error = await refusal(() => repair(s.sourceId, { apply: true, expect: hash }));
+ expect(error.code).toBe('invalid_params');
+ expect(error.suggestion).toContain('--keep prior');
+ expect(error.suggestion).toContain('--keep disk');
+ }));
+
+ test('a v2 shared-skill bundle record is refused with recovery_bundle_unsupported', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const [row] = await engine.executeRaw<{ recovery: any }>('SELECT recovery FROM persistence_requests WHERE id=$1::uuid', [s.id]);
+ const bundle = { version: 2, target: 'skill_bundle', root: s.root, ownerEpoch: row.recovery.ownerEpoch, attempt: row.recovery.attempt, files: [row.recovery] };
+ // Fixture only: the protocol trigger admits a bundle row solely through the shared-skill writer, so it is bypassed for this one update.
+ await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL session_replication_role = replica');
+ await tx.executeRaw("UPDATE persistence_requests SET recovery=$2::text::jsonb,target_kind='skill_bundle',protocol_version=2 WHERE id=$1::uuid", [s.id, JSON.stringify(bundle)]);
+ });
+ const error = await refusal(() => repair(s.sourceId));
+ expect(error.code).toBe('recovery_bundle_unsupported');
+ expect(error.toJSON()).toMatchObject({ docs: 'docs/guides/repair.md#recovery-bundle-unsupported' });
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ }));
+
+ test('races the resident recovery pass: while the apply holds the worktree lock the pass changes nothing', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const hash = (await repair(s.sourceId)).preview_hash!;
+ const seen: unknown[] = [];
+ installFaultHook(async point => {
+ if (point !== 'stuck_recovery:backed_up') return;
+ const resident = await recoverPublication(engine, s.id);
+ seen.push({ state: resident.state, blocked_reason: resident.blocked_reason, file: readFileSync(s.path, 'utf8') });
+ });
+ const result = await repair(s.sourceId, { apply: true, expect: hash, keep: 'prior' });
+ expect(seen).toEqual([{ state: 'recovering', blocked_reason: 'unexpected_file_bytes', file: EDITED }]);
+ expect(result.outcomes).toEqual({ resolved: 1 });
+ expect(readFileSync(s.path, 'utf8')).toBe(PRIOR);
+ }));
+
+ const KILLS: Array<[FaultPoint, 'prior' | 'disk', string, boolean]> = [
+ ['stuck_recovery:backed_up', 'prior', EDITED, true], ['stuck_recovery:written', 'prior', PRIOR, true], ['stuck_recovery:recovered', 'prior', PRIOR, false],
+ ['stuck_recovery:backed_up', 'disk', EDITED, true], ['stuck_recovery:abandoned', 'disk', EDITED, true], ['stuck_recovery:recovered', 'disk', EDITED, false],
+ ];
+ for (const [point, keep, fileAtKill, recoveryAtKill] of KILLS) {
+ test(`a run killed at ${point} (--keep ${keep}) resumes to the same end state`, () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const hash = (await repair(s.sourceId)).preview_hash!;
+ installFaultHook(hit => { if (hit === point) throw new Error(`killed at ${hit}`); });
+ await expect(repair(s.sourceId, { apply: true, expect: hash, keep })).rejects.toThrow(`killed at ${point}`);
+ installFaultHook(undefined);
+ expect(readFileSync(s.path, 'utf8')).toBe(fileAtKill);
+ expect((await getWriteRequestById(engine, s.id))!.recovery !== null).toBe(recoveryAtKill);
+ const resumed = await repair(s.sourceId, { apply: true, expect: hash, keep });
+ expect(resumed.outcomes).toEqual({ resolved: 1 });
+ expect(readFileSync(s.path, 'utf8')).toBe(keep === 'prior' ? PRIOR : EDITED);
+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: keep === 'prior' ? 'queued' : 'conflict', recovery: null });
+ expect((await journal(s.id)).map(entry => entry.phase)).toEqual(['done']);
+ expect(await recoveryAccounting(s.id)).toEqual({ reserved: 0, counter: 0 });
+ }));
+ }
+
+ for (const [point, keep] of [['stuck_recovery:written', 'prior'], ['stuck_recovery:abandoned', 'disk']] as const) {
+ test(`mixed version: an older resident consumer finishes a resolution killed at ${point}, and the rerun records it`, () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const hash = (await repair(s.sourceId)).preview_hash!;
+ installFaultHook(hit => { if (hit === point) throw new Error(`killed at ${hit}`); });
+ await expect(repair(s.sourceId, { apply: true, expect: hash, keep })).rejects.toThrow(`killed at ${point}`);
+ installFaultHook(undefined);
+ // The resident pass of any version runs the unchanged recoverPublication: after --keep prior the file equals the
+ // recorded prior (requeued); after --keep disk the request is already terminal, so it only cleans and clears the record.
+ const state = keep === 'prior' ? 'queued' : 'conflict';
+ expect(await recoverPublication(engine, s.id)).toMatchObject({ state, recovery: null });
+ const resumed = await repair(s.sourceId, { apply: true, expect: hash, keep });
+ expect(resumed.outcomes).toEqual({ resolved: 1 });
+ expect(resumed.outcome_items![0]!.detail).toMatchObject({ finished_by: 'another_pass', request_state: state });
+ expect(readFileSync(s.path, 'utf8')).toBe(keep === 'prior' ? PRIOR : EDITED);
+ expect((await repair(s.sourceId, { apply: true, expect: hash, keep })).outcomes).toEqual({ replayed: 1 });
+ }));
+ }
+
+ test('a withdrawal-mirror effect recovery on the worktree is listed as refused recovery_effect_unsupported and never touched', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const worktree = (await getWriteRequestById(engine, s.id))!.worktree_id;
+ const [effect] = await engine.executeRaw<{ id: string }>(`INSERT INTO persistence_effects(request_id,kind,data,worktree_id,recovery)
+ VALUES($1::uuid,'withdrawal-mirror','{}'::jsonb,$2::uuid,'{"slug":"page"}'::jsonb) RETURNING id::text`, [s.id, worktree]);
+ try {
+ const out = await cli(['stuck-recovery', '--source', s.sourceId]);
+ expect(out).toContain(`refused effect ${effect.id} of ${s.requestId}`);
+ expect(out).toContain('recovery_effect_unsupported: A withdrawal-mirror effect recovery blocks the worktree');
+ expect((await repair(s.sourceId)).residuals).toMatchObject({ effect_recovery: 1 });
+ await engine.executeRaw("UPDATE persistence_requests SET recovery=NULL,recovery_bytes=0,state='committed',completed_at=now() WHERE id=$1::uuid", [s.id]);
+ const named = await refusal(() => repair(s.sourceId, { requestId: s.requestId }));
+ expect(named.code).toBe('recovery_effect_unsupported');
+ expect(named.toJSON()).toMatchObject({ docs: 'docs/guides/repair.md#recovery-effect-unsupported' });
+ expect((await engine.executeRaw<{ recovery: unknown }>('SELECT recovery FROM persistence_effects WHERE id=$1', [effect.id]))[0].recovery).toEqual({ slug: 'page' });
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ } finally { await engine.executeRaw('DELETE FROM persistence_effects WHERE id=$1', [effect.id]); }
+ }));
+
+ test('the apply waits a bounded time for the worktree lock, then refuses writer_lock_unavailable without changing anything', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const preview = await repair(s.sourceId);
+ const [item] = (await scanStuckRecoveries(engine, [s.sourceId])).items;
+ const held = await acquireWorktree((await getWorktreeBinding(engine, s.sourceId))!);
+ expect(held).not.toBeNull();
+ try {
+ const started = Date.now();
+ const error = await refusal(() => resolveStuckRecovery(engine, item!, { keep: 'prior', previewHash: preview.preview_hash!, lockWaitMs: 300 }));
+ expect(error.code).toBe('writer_lock_unavailable');
+ expect(Date.now() - started).toBeLessThan(5_000);
+ } finally { await held!.release(); }
+ expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
+ expect(await journal(s.id)).toEqual([]);
+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'recovering', blocked_reason: 'unexpected_file_bytes' });
+ }));
+
+ test('--keep prior publishes through the record\'s reserved restoration stage, and a complete stage left by a killed write is cleaned first', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const stage = (await getWriteRequestById(engine, s.id))!.recovery as { staging?: { restoration?: { path: string } } };
+ expect(stage.staging?.restoration?.path).toBeTruthy();
+ writeFileSync(stage.staging!.restoration!.path, PRIOR);
+ const preview = await repair(s.sourceId);
+ expect((await repair(s.sourceId, { apply: true, expect: preview.preview_hash, keep: 'prior' })).outcomes).toEqual({ resolved: 1 });
+ expect(readFileSync(s.path, 'utf8')).toBe(PRIOR);
+ expect(existsSync(stage.staging!.restoration!.path)).toBe(false);
+ expect(await recoveryAccounting(s.id)).toEqual({ reserved: 0, counter: 0 });
+ }));
+
+ test('--keep disk never rewrites the recovery record: the bytes it reserved are released with it', () => run(async () => {
+ const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
+ const before = (await getWriteRequestById(engine, s.id))!;
+ expect(Number(before.recovery_bytes)).toBeGreaterThan(0);
+ expect(await recoveryAccounting(s.id)).toEqual({ reserved: Number(before.recovery_bytes), counter: Number(before.recovery_bytes) });
+ let seen: unknown = null;
+ installFaultHook(async point => { if (point === 'stuck_recovery:abandoned') seen = (await getWriteRequestById(engine, s.id))!.recovery; });
+ const preview = await repair(s.sourceId);
+ await repair(s.sourceId, { apply: true, expect: preview.preview_hash, keep: 'disk' });
+ installFaultHook(undefined);
+ expect(seen).toEqual(before.recovery);
+ expect(await recoveryAccounting(s.id)).toEqual({ reserved: 0, counter: 0 });
+ }));
+
+ test('nothing stuck: the preview lists nothing and an apply of its hash changes nothing', () => run(async () => {
+ const { sourceId } = await source();
+ const preview = await repair(sourceId);
+ expect(preview).toMatchObject({ affected: 0, listing: [] });
+ expect((await repair(sourceId, { apply: true, expect: preview.preview_hash, keep: 'prior' })).applied).toBe(0);
+ }));
+});