Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
stuck-recovery: resolve large-file page recoveries in bounded memory (C-22)
garrytan5448086de9af
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.mdindex 64aa9f4496..f28bd029be 100644--- a/docs/architecture/key-files/core-persistence-request-indexes.md+++ b/docs/architecture/key-files/core-persistence-request-indexes.md@@ -6,5 +6,5 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa- `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`), `large_file:stage_streaming` (after each piece `stageStreamedContent` writes to a stage's in-progress name), `effect_recovery:before_stage` / `effect_recovery:staged` (a streamed, version 2 withdrawal mirror: once its record is durable, before its file is streamed into the publication stage, and after that step, before the recovery transaction renames the stage), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `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`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).-- `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`.+- `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. A record whose prior file is over the single-string ceiling (`staging.before`) resolves the same way in bounded memory: the disk file and the staged copy are hashed in pieces (the copy's state, `verified`, `missing` or `mismatched`, is in the prior view and the digest), backups are kernel copies checked by streamed hash, the diff file is a summary (both fingerprints, the first differing byte, a window of at most 1 KiB; `cmp` reproduces it), `--keep prior` runs recovery's `restoreBeforeStage` after `cleanupRecoveryStaging(keepBefore)`, and `--keep disk` backs up a mismatched copy (`<index>.prior-stage`) and removes it before abandoning. `--keep prior` without a verified copy refuses `recovery_prior_stage_unavailable` (registry entry; its fix is the `--keep disk` apply under the same hash). Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`, `test/large-pages/stuck-recovery-large.slow.test.ts`.- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. An older binary refuses a version 2 record (it has no embedded file) and leaves it for this one. Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 20a055f052..c8c22e13f6 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2886,6 +2886,16 @@ More: [docs/guides/company-brain-ingestion.md#agent-and-ci-use](../../docs/guideMore: [docs/guides/sync-unblock-runbook.md#dry-run-convergence-classes](../../docs/guides/sync-unblock-runbook.md#dry-run-convergence-classes)+### recovery_prior_stage_unavailable++<a id="recovery_prior_stage_unavailable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain repair stuck-recovery cannot apply that --keep choice to a page recovery over the single-string ceiling, because the staged copy of its prior file is missing, does not match its recorded SHA-256, or is not a regular file; nothing was changed. | A prior file over 24 MiB is not embedded in its recovery record: the record names a staged copy beside the file by path and SHA-256, and only that copy can put the prior bytes back. Without it --keep prior has nothing safe to restore, so the remaining exit is --keep disk, which the user must agree to. | Stop and ask the user; re-run only with the authorization the message names. | user | `repeat the read that failed` | 1 | no |++More: [docs/guides/repair.md#recovery-prior-stage-unavailable](../../docs/guides/repair.md#recovery-prior-stage-unavailable)+### recovery_required<a id="recovery_required"></a>diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 7406200baa..b7dd270df0 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -135,7 +135,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, or (#6834) a cursor whose checkpoint can never publish because the source's `last_commit` moved elsewhere (`checkpoint_moved`). `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). |+| `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. A file over 24 MiB resolves the same way, read in pieces, with a bounded diff summary. 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`), `--keep prior` on a large-file recovery whose staged prior copy is missing or damaged (`recovery_prior_stage_unavailable`; `--keep disk` still resolves it), 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. |@@ -752,6 +752,25 @@ listed record. The hash binds each record's identity, each file's disk bytesand the page's database revision, so an edit or a page write after thepreview refuses the apply with `preview_changed`.+A file over the 24 MiB single-string ceiling (normal with segmented page+storage, up to `pages.max_bytes`) resolves the same way, in bounded memory.+Its write kept the prior file as a hidden staged copy beside it+(`.<sha256>.tmp.before-<uuid>`) instead of inside the recovery record. The+preview hashes the file and that copy in pieces and prints the copy's state+after the prior fingerprint: `staged copy verified`, `missing` or `does not+match its recorded SHA-256`. Both versions are backed up by copy, each+checked against its fingerprint, and the diff file is a summary instead of a+full diff (both hashes and sizes, the first byte where they differ, and a+window of at most 1 KiB around it), marked `(summary: ...)` in the preview;+its `reproduce` line is a `cmp` of the two backups. `--keep prior` renames+the verified staged copy back over the file, as the writer's own recovery+does, and the write publishes again. A missing or damaged staged copy can't+restore the prior, so the preview offers only `--keep disk`, and `--keep+prior` refuses with+[`recovery_prior_stage_unavailable`](#recovery-prior-stage-unavailable).+`--keep disk` keeps a damaged copy in the backup directory (`0.prior-stage`)+and removes it from the checkout.+The choice is the user's: there is no default `--keep`, the kind never runsfrom `--all`, `gbrain doctor --remediate` or a remediation step, and anon-interactive apply without `--yes` exits 3 with the consent payload and@@ -2704,20 +2723,26 @@ put those bytes in place by hand, and let the resident writer finish therecovery. Pass `--request-id` to resolve the page recoveries on the samesource.-### Recovery large file unsupported--`recovery_large_file_unsupported`: `gbrain repair stuck-recovery` found a page-recovery whose prior file is over the 24 MiB single-string ceiling. Its prior-bytes are kept as a staged copy beside the file (named in the record, with its-SHA-256) instead of inside the record, and the preview's diff would read both-files whole, so nothing was changed. The preview lists such a recovery under-`refused` with this code and still lists the source's other recoveries; with-`--request-id` naming it, the command refuses with this code. Inspect the request read-only with-`gbrain sources writer status --source <id> --json`, ask the user which version-to keep, put those bytes at the canonical path by hand (the staged copy holds-the prior bytes; never delete it), and let the resident writer finish the-recovery: it renames the copy back when the file holds the published bytes, and-removes it when the file holds the prior ones.+### Recovery prior stage unavailable++<a id="recovery-large-file-unsupported"></a>++`recovery_prior_stage_unavailable`: `gbrain repair stuck-recovery` can't apply+that `--keep` choice to a page recovery whose prior file is over the 24 MiB+single-string ceiling, and nothing was changed. Such a recovery keeps its prior+bytes as a staged copy beside the file, named in the record by path and+SHA-256, and that copy is missing, doesn't match its recorded SHA-256, or isn't+a regular file. Without it `--keep prior` has nothing safe to put back. The+refusal's `fix` is the remaining exit, the `--keep disk` apply under the same+preview hash (`next: ask_user`, because it keeps the edit and abandons the+write), with `gbrain sources writer status --source <id> --json` as its+`verify`. When the staged copy isn't a regular file, `--keep disk` can't back+it up either; the `fix` is then that read-only status, and the preview offers+the choices again once the path holds a regular file.++Builds before this one listed every large-file recovery as refused with+`recovery_large_file_unsupported` and had no exit for it; this build resolves+them with `gbrain repair stuck-recovery`.### Recovery choice refuseddiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 0f0cfbe08b..fde9ee5cac 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -896,6 +896,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', text: 'Upgrading builds the index `ingest_log_marked_idx` (migration v257): on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. It took 0.4 s for 1M `ingest_log` rows on Postgres and 0.5 s on PGLite. The segmented storage writer hold now judges every recent import, sync or connector run and resident process by its version, including those of a gbrain that already records reading segmented pages (v0.60.290.0), and the index keeps that read to the last 7 days of the log: 600 buffers on a 1M-row log, where a scan reads the whole table.' },{ since: 'TBD', text: 'Upgrading builds the index `pages_segmented_body_bytes_idx` (migration v258) over pages stored in segments: on Postgres online (`CREATE INDEX CONCURRENTLY`), on PGLite as a plain build that holds writes until it ends. With it, the default `persistence.limits.worktree_recovery_bytes` also leaves room for the largest page already stored in segments, deleted pages included: turning `pages.segmented_storage` off or lowering `pages.max_bytes` no longer makes a delete, restore or withdrawal mirror of such a page fail with `request_too_large` (a withdrawn row stayed in its file). A value you set is kept, and a request it cannot hold is refused with `request_too_large` naming both recovery budgets and the bytes it needed.' },{ since: 'TBD', text: 'Doctor `segmented_storage` no longer tells you to upgrade this host when the only writes holding segmented storage off are this host\'s own from before its upgrade and it has since written with the upgraded gbrain: it reports the hold as information with the time it clears. Another host, or an older `serve` or worker still running on this host, keeps the warning and the `gbrain upgrade` fix.' },+ { since: 'TBD', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 77f68d2aac..0d8166cdd3 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -52,8 +52,6 @@ export const ERROR_CATALOGUE = {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' },- // Wave B: a page recovery whose prior file is over the single-string ceiling (staged as a copy) is refused: its preview diff would read both files whole.- recovery_large_file_unsupported: { code: 'recovery_large_file_unsupported', docs: 'docs/guides/repair.md#recovery-large-file-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.diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex eb2e5c6db3..7b996e31eb 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -500,6 +500,7 @@ export const CODES = {docs: 'docs/guides/sync-unblock-runbook.md#dry-run-convergence-classes',suggestion: "Check the checkout with git -C <dir> status, then rerun the read-only status; report it with gbrain doctor --json if it repeats.",fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--detail', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-reads the convergence shadow; writes nothing.' } },+ recovery_prior_stage_unavailable: { class: 'consent', actor: 'user', summary: "gbrain repair stuck-recovery cannot apply that --keep choice to a page recovery over the single-string ceiling, because the staged copy of its prior file is missing, does not match its recorded SHA-256, or is not a regular file; nothing was changed.", why: "A prior file over 24 MiB is not embedded in its recovery record: the record names a staged copy beside the file by path and SHA-256, and only that copy can put the prior bytes back. Without it --keep prior has nothing safe to restore, so the remaining exit is --keep disk, which the user must agree to.", docs: 'docs/guides/repair.md#recovery-prior-stage-unavailable' },recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes.", why: "Details name the exit when there is one: physical_root_device_changed (the checkout's filesystem device number changed; re-stamped by itself when ownership verifies) and physical_root_directory_changed (the directory at the recorded path was recreated, or its birth time drifted beyond 1 µs; the relocated-root self-transfer, `transfer prepare/accept <source> --self-transfer --confirm-relocated-root`, re-stamps it). Both are explained in docs/guides/write-refusals.md." },redirect_uri_mismatch: { class: 'caller', summary: "Google connect credential error: redirect uri mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },ref_not_in_answer: { class: 'caller', summary: "The rated page is not one of the pages the answer used.", docs: 'docs/guides/retrieval-feedback.md#ref_not_in_answer' },diff --git a/src/core/persistence/recovery-resolve.ts b/src/core/persistence/recovery-resolve.tsindex ce6bcb043c..cf01139f05 100644--- a/src/core/persistence/recovery-resolve.ts+++ b/src/core/persistence/recovery-resolve.ts@@ -21,9 +21,16 @@* 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. So is a page recovery whose prior file is over the- * single-string ceiling (`recovery_large_file_unsupported`: its diff would read both files whole), when it is blocked on- * unexpected bytes or its file (hashed in pieces) matches neither recorded version.+ * and either choice could put withdrawn content back on disk.+ *+ * A page recovery whose prior file is over the single-string ceiling (large-file.ts) embeds no prior bytes: its prior is+ * the staged copy beside the file (`staging.before`, by path and SHA-256). It resolves the same way in bounded memory: the+ * disk file and the staged copy are hashed in pieces, both are backed up by kernel copy checked by streamed hash, the+ * preview's diff is a summary (both fingerprints, the first differing byte and a window of at most a kilobyte), and+ * `--keep prior` renames the verified staged copy back as recovery's own restoration does (`restoreBeforeStage`: verified,+ * mode set, atomic rename, directory flushed). A staged copy that is missing or does not match refuses `--keep prior`+ * (`recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply); `--keep disk` backs a mismatched copy up and+ * removes it, because recovery's cleanup never deletes a copy it cannot verify. The hash also binds the staged copy's state.** 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@@ -33,7 +40,7 @@* 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 { closeSync, constants, copyFileSync, existsSync, fchmodSync, 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';@@ -53,8 +60,9 @@ 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 { hashFile } from './large-file.ts';+import { cleanupRecoveryStaging, restoreBeforeStage, upgradeRecoveryStaging } from './staging.ts';+import { FileBytes, hashDescriptor, hashFile, LARGE_FILE_MIN_BYTES, largeFileWork, validateBeforeStagePath } from './large-file.ts';+import { SEGMENT_MAX_BYTES } from '../page-body/limits.ts';import { withFilesystemPublication } from './filesystem-guard.ts';import { readHeadBlockers } from './head-blocker.ts';import { previewChangedError } from './preview-approval.ts';@@ -64,7 +72,13 @@ import { KEEP_DISK_ABANDONED_PREFIX } from './verb-errors.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 };+/**+ * A prior file over the single-string ceiling is not in the record: it is the staged copy beside the canonical file+ * (`staging.before`). `verified`: that copy is a regular file of the recorded length and SHA-256; `missing`: no file there;+ * `mismatched`: anything else (`sha256` is what it holds now, null when it is not a single-link regular file).+ */+export interface PriorStageView { state: 'verified' | 'missing' | 'mismatched'; path: string; sha256: string | null; size: number | null }+export type PriorView = { absent: true } | { absent: false; sha256: string; size: number | null; mode: number | null; stored: boolean; stage?: PriorStageView };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;@@ -72,6 +86,8 @@ export interface RecoveryFileView {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 diff is a bounded summary (a version is over the single-string ceiling), not a full diff. */+ diff_summary?: true;}/** 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 }> }@@ -85,11 +101,8 @@ export interface StuckRecovery {/** Digest of the identity, each file's disk bytes and the page revision: what an apply re-verifies. */digest: string;}-/**- * A blocked terminal request, a withdrawal-mirror effect recovery or a page recovery whose prior file is over the- * single-string ceiling: listed, never resolved (see the module comment).- */-export interface RefusedRecovery { code: 'recovery_choice_refused' | 'recovery_effect_unsupported' | 'recovery_large_file_unsupported'; request_id: string; source_id: string; slug: string; state: 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 }> }@@ -115,20 +128,55 @@ function identityOf(files: FileRecoveryRecord[], record: { attempt: string; ownereturn { 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 } {+/** Where one version's bytes are read from: held in memory (at most the single-string ceiling), a file read in pieces, or nowhere. */+type Bytes = { bytes: Buffer } | { path: string } | null;++/** The disk version: a file over the single-string ceiling is hashed in pieces and never read whole. */+function diskView(path: string): { view: DiskView; source: Bytes } {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 };+ try { stat = lstatSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { view: { deleted: true }, source: 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) }, source: null };+ if (stat.size > LARGE_FILE_MIN_BYTES) {+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ const { hash, bytes } = hashDescriptor(fd);+ return { view: { deleted: false, kind: 'file', sha256: hash, size: bytes, mode: fileMode(stat.mode) }, source: { path } };+ } finally { closeSync(fd); }+ }const bytes = readFileSync(path);- return { view: { deleted: false, kind: 'file', sha256: sha256(bytes), size: bytes.length, mode: fileMode(stat.mode) }, bytes };+ return { view: { deleted: false, kind: 'file', sha256: sha256(bytes), size: bytes.length, mode: fileMode(stat.mode) }, source: { bytes } };}function priorBytes(record: FileRecoveryRecord): Buffer | null { return record.before === null ? null : Buffer.from(record.before, 'base64'); }+/** The staged copy of a prior file over the single-string ceiling, checked by its streamed SHA-256 (see PriorStageView). */+function priorStageView(record: FileRecoveryRecord): PriorStageView {+ const stage = record.staging!.before!;+ let named = isWriteTargetContained(stage.path, record.root);+ try { validateBeforeStagePath(record.path, stage.path); } catch { named = false; }+ if (!named) return { state: 'mismatched', path: stage.path, sha256: null, size: null };+ let leaf;+ try { leaf = lstatSync(stage.path); }+ catch (error) { if (['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) return { state: 'missing', path: stage.path, sha256: null, size: null }; throw error; }+ if (!leaf.isFile() || leaf.nlink !== 1) return { state: 'mismatched', path: stage.path, sha256: null, size: leaf.size };+ const hash = hashFile(stage.path);+ const verified = hash === stage.hash && leaf.size === stage.bytes && stage.hash === record.beforeHash;+ return { state: verified ? 'verified' : 'mismatched', path: stage.path, sha256: hash, size: leaf.size };+}function priorView(record: FileRecoveryRecord): PriorView {if (record.beforeHash === null) return { absent: true };+ if (record.staging?.before) {+ const stage = priorStageView(record);+ return { absent: false, sha256: record.beforeHash, size: record.staging.before.bytes, mode: record.mode, stored: stage.state === 'verified', stage };+ }const bytes = priorBytes(record);return { absent: false, sha256: record.beforeHash, size: bytes?.length ?? null, mode: record.mode, stored: bytes !== null && sha256(bytes) === record.beforeHash };}+function priorSource(record: FileRecoveryRecord, view: PriorView): Bytes {+ if (view.absent) return null;+ if (view.stage) return view.stage.state === 'verified' ? { path: view.stage.path } : null;+ const bytes = priorBytes(record);+ return bytes === null ? null : { bytes };+}/** 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> {@@ -161,48 +209,140 @@ function writePrivateFile(path: string, bytes: Buffer): void {`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>) {+/**+ * Copies the file at `from` to `path` 0600 and durable: the kernel copies it to a temporary name, the copy is hashed in+ * pieces and must hold `expected`, then it is fsynced and renamed. An existing copy holding `expected` is kept. A copy+ * that does not hold `expected` (the file changed since it was fingerprinted) is removed and `changed()` is thrown.+ */+function copyPrivateFile(path: string, from: string, expected: string, changed: () => OperationError): void {+ if (existsSync(path) && hashFile(path) === expected) return;+ const temporary = `${path}.${randomUUID()}.tmp`;+ let copied = false;+ try {+ copyFileSync(from, temporary, constants.COPYFILE_EXCL);+ const fd = openSync(temporary, constants.O_RDWR | (constants.O_NOFOLLOW ?? 0));+ try {+ fchmodSync(fd, 0o600);+ const copy = hashDescriptor(fd);+ largeFileWork.bytesCopied += copy.bytes;+ if (copy.hash !== expected) throw changed();+ fsyncSync(fd);+ } finally { closeSync(fd); }+ renameSync(temporary, path);+ copied = true;+ } finally {+ if (!copied) try { unlinkSync(temporary); } catch { /* never created */ }+ }+ flushDirectory(dirname(path));+}++const SUMMARY_CONTEXT_BYTES = 256, SUMMARY_WINDOW_BYTES = 768;+const MIB = 1024 * 1024;+const view = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);+function newlines(bytes: Buffer): number {+ let count = 0;+ for (let at = bytes.indexOf(10); at >= 0; at = bytes.indexOf(10, at + 1)) count++;+ return count;+}+const prefixed = (prefix: string, bytes: Uint8Array) => {+ const text = view(bytes).toString('utf8');+ return text ? (text.endsWith('\n') ? text.slice(0, -1) : text).split('\n').map(line => `${prefix}${line}`) : [];+};+/**+ * The bounded stand-in for a diff when a version is over the single-string ceiling: both fingerprints, the first byte+ * where the two differ (found by comparing them a segment at a time) and a window of at most a kilobyte around it.+ */+function diffSummary(file: RecoveryFileView, priorPath: string | null, diskPath: string | null): string {+ const prior = priorPath ? FileBytes.open(priorPath) : null;+ const disk = diskPath ? FileBytes.open(diskPath) : null;+ try {+ const shared = Math.min(prior?.length ?? 0, disk?.length ?? 0);+ let offset = shared, line = 1;+ for (let at = 0; at < shared; at += SEGMENT_MAX_BYTES) {+ const end = Math.min(at + SEGMENT_MAX_BYTES, shared);+ const a = view(prior!.subarray(at, end)), b = view(disk!.subarray(at, end));+ if (a.equals(b)) { line += newlines(a); continue; }+ let index = 0;+ while (a[index] === b[index]) index++;+ offset = at + index;+ line += newlines(a.subarray(0, index));+ break;+ }+ const start = Math.max(0, offset - SUMMARY_CONTEXT_BYTES);+ const side = (bytes: FileBytes | null, from: number, to: number) => bytes ? bytes.subarray(from, to) : new Uint8Array();+ const context = side(prior ?? disk, start, offset);+ const removed = side(prior, offset, offset + SUMMARY_WINDOW_BYTES), added = side(disk, offset, offset + SUMMARY_WINDOW_BYTES);+ const describe = (label: string, version: { sha256: string | null; size: number | null } | null) => version+ ? `${label} sha256 ${version.sha256} ${version.size} bytes` : `${label} absent`;+ return [+ `# summary only, no full diff: a version is over the ${LARGE_FILE_MIN_BYTES / MIB} MiB single-string ceiling, so neither is read whole`,+ describe(`--- prior/${file.relative}`, file.prior.absent ? null : { sha256: file.prior.sha256, size: prior?.length ?? file.prior.size }),+ describe(`+++ disk/${file.relative}`, file.disk.deleted ? null : { sha256: file.disk.sha256, size: file.disk.size }),+ offset === shared && (prior?.length ?? 0) === (disk?.length ?? 0) ? '# the two versions hold the same bytes'+ : `# first difference at byte ${offset} (line ${line}); the window below is cut at byte offsets, not lines`,+ `@@ bytes ${start}..${offset + removed.length} of prior, ${start}..${offset + added.length} of disk @@`,+ ...prefixed(' ', context), ...prefixed('-', removed), ...prefixed('+', added),+ `# reproduce: cmp ${priorPath ?? '/dev/null'} ${diskPath ?? '/dev/null'}`, '',+ ].join('\n');+ } finally { prior?.close(); disk?.close(); }+}++/**+ * Both versions of every file (and their diff) under `dir`; returns the paths by file index. A version over the+ * single-string ceiling is copied by the kernel and checked by its streamed hash, and its diff is a bounded summary.+ * A staged prior copy that matches nothing recorded is kept too (`<index>.prior-stage`): `--keep disk` removes it.+ */+function writeArtifacts(dir: string, item: { files: RecoveryFileView[] }, sources: Array<{ prior: Bytes; disk: Bytes }>, changed: () => OperationError) {return item.files.map((file, index) => {- const prior = priorBytes(records[index]);+ const { prior, disk } = sources[index];+ const keep = (path: string, source: NonNullable<Bytes>, expected: string | null) => 'bytes' in source ? writePrivateFile(path, source.bytes) : copyPrivateFile(path, source.path, expected!, changed);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 diskPath = disk === null ? null : join(dir, `${index}.disk`);+ if (priorPath) keep(priorPath, prior!, file.prior.absent ? null : file.prior.sha256);+ if (diskPath) keep(diskPath, disk!, file.disk.deleted ? null : file.disk.sha256);+ const stage = file.prior.absent ? undefined : file.prior.stage;+ if (stage?.state === 'mismatched' && stage.sha256) copyPrivateFile(join(dir, `${index}.prior-stage`), stage.path, stage.sha256, changed);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'}` };+ if ((prior === null || 'bytes' in prior) && (disk === null || 'bytes' in disk)) {+ writePrivateFile(diffPath, Buffer.from(unifiedDiff(prior?.bytes.toString('utf8') ?? '', disk?.bytes.toString('utf8') ?? '',+ { oldPath: `prior/${file.relative}`, newPath: `disk/${file.relative}` })));+ return { diff_path: diffPath, diff_command: `diff -u ${priorPath ?? '/dev/null'} ${diskPath ?? '/dev/null'}` };+ }+ writePrivateFile(diffPath, Buffer.from(diffSummary(file, priorPath, diskPath)));+ return { diff_path: diffPath, diff_command: `cmp ${priorPath ?? '/dev/null'} ${diskPath ?? '/dev/null'}`, diff_summary: true as const };});}/** 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> }> {+async function readItem(engine: BrainEngine, row: WriteRequest, binding: WorktreeBinding): Promise<{ item: StuckRecovery; records: FileRecoveryRecord[]; sources: Array<{ prior: Bytes; disk: Bytes }> }> {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.`);- if (row.recovery?.version === 1 && row.recovery.staging?.before) throw catalogueError('recovery_large_file_unsupported', largeFileReason(row),- `Nothing was changed. Inspect it read-only with gbrain sources writer status --source ${row.source_id} --json and ask the user which version of the file to keep; its prior bytes are the staged copy the record names. Put the chosen bytes in place 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 sources: Array<{ prior: Bytes; disk: Bytes }> = [];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 { view, source } = contained ? diskView(record.path) : { view: { deleted: false, kind: 'other', sha256: null, size: 0, mode: 0 } as DiskView, source: null };+ const prior = priorView(record);+ sources.push({ prior: priorSource(record, prior), disk: source });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;+ return { path: record.path, root: record.root, relative: relative(binding.local_path ?? record.root, record.path), prior, disk: view, matches } as RecoveryFileView;});const writable = (file: RecoveryFileView) => file.disk.deleted || file.disk.kind === 'file';+ // --keep disk leaves the staged prior to recovery's cleanup, which refuses a copy it cannot verify: a mismatched copy is+ // backed up and removed first, so it must be a regular file this command can hash.+ const stageRemovable = (file: RecoveryFileView) => file.prior.absent || file.prior.stage?.state !== 'mismatched' || file.prior.stage.sha256 !== null;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 choices = { prior: unexpected.every(file => writable(file) && (file.prior.absent || file.prior.stored)), disk: unexpected.every(file => writable(file) && stageRemovable(file)) };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,+ const priorStages = files.map(file => file.prior.absent ? null : file.prior.stage ?? null);+ return { records, sources, 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 }) } };+ disk: files.map(file => file.disk), page_revision, ...(priorStages.some(Boolean) ? { prior_stages: priorStages } : {}) }) } };}function ownerBinding(binding: WorktreeBinding | null, sourceId: string, hostId: string): WorktreeBinding {@@ -257,21 +397,11 @@ export async function scanStuckRecoveries(engine: BrainEngine, sourceIds: stringcontinue;}if (row.blocked_reason === 'unexpected_staging_bytes') { residual('unexpected_staging_bytes'); continue; }- if (!opts.requestId && row.recovery?.version === 1 && row.recovery.staging?.before) {- const record = row.recovery;- const contained = isWriteTargetContained(record.path, record.root) && isWriteTargetContained(record.path, binding.local_path!);- const leaf = contained ? lstatSync(record.path, { throwIfNoEntry: false }) : undefined;- const disk = !contained ? undefined : !leaf ? null : leaf.isFile() ? hashFile(record.path) : undefined;- if (row.blocked_reason !== 'unexpected_file_bytes' && (disk === record.beforeHash || disk === record.afterHash)) { residual('recovers_on_its_own'); continue; }- scan.refused.push({ code: 'recovery_large_file_unsupported', request_id: row.request_id, source_id: row.source_id, slug: row.slug, state: row.state,- blocked_reason: row.blocked_reason ?? null, reason: largeFileReason(row) });- residual('large_file_refused');- continue;- }- const { item, records, disks } = await readItem(engine, row, binding);+ const { item, sources } = 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);+ const paths = writeArtifacts(await privateBackupDir(engine, row.request_id, item.digest.slice(0, 16)), item, sources,+ () => opError('source_changed', `A file of request ${row.request_id} changed while the preview copied it.`, `Nothing was changed. Run the preview again: ${stuckRecoveryPreviewCommand(sourceIds)}`));item.files = item.files.map((file, index) => ({ ...file, ...paths[index] }));}scan.items.push(item);@@ -287,9 +417,6 @@ function terminalReason(row: WriteRequest): string {+ `--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 largeFileReason(row: WriteRequest): string {- return `Request ${row.request_id} in source ${row.source_id} holds a page recovery whose prior file is over the single-string ceiling, which gbrain repair stuck-recovery does not resolve.`;-}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.';@@ -314,6 +441,49 @@ export async function readResolutions(engine: BrainEngine, previewHash: string):return rows.map(row => row.completed_keys[0]);}+/**+ * The refusal of a choice the staged prior copy cannot support (null when the copy is not why): `--keep prior` needs a+ * verified copy, and `--keep disk` a copy it can back up and remove. Its fix is the remaining exit, the `--keep disk`+ * apply under the same preview hash (destructive, so the user agrees first), or the read-only owner status when none is left.+ */+function priorStageUnavailable(item: StuckRecovery, keep: KeepChoice, previewHash: string): OperationError | null {+ const stage = item.files.filter(file => file.matches === 'neither').map(file => file.prior.absent ? undefined : file.prior.stage)+ .find(found => found && (keep === 'prior' ? found.state !== 'verified' : found.state === 'mismatched' && found.sha256 === null));+ if (!stage) return null;+ const docs = 'docs/guides/repair.md#recovery-prior-stage-unavailable';+ const status = ['gbrain', 'sources', 'writer', 'status', '--source', item.source_id, '--json'];+ const what = stage.state === 'missing' ? 'is missing' : stage.sha256 === null ? 'is not a regular file' : 'does not match its recorded SHA-256';+ const message = `The staged copy of the prior file of request ${item.request_id} in source ${item.source_id} ${what} (${stage.path}), so --keep ${keep} `+ + `cannot ${keep === 'prior' ? 'restore the prior bytes' : 'back it up and remove it'}.`;+ if (keep === 'prior' && item.choices.disk) {+ const argv = ['gbrain', 'repair', 'stuck-recovery', '--source', item.source_id, '--keep', 'disk', '--apply', '--expect', previewHash, '--yes'];+ return opError('recovery_prior_stage_unavailable', message,+ `Nothing was changed. The prior bytes cannot be put back, so the remaining exit keeps the edited file and abandons the write. Ask the user, then run: ${argv.join(' ')}`,+ { docs, fix: { argv, consent: ['destructive'], actor: 'agent', requires_exclusive: false, verify: { argv: status },+ why: 'Keeps the bytes on disk and abandons the write after backing up both versions; the recovery is then cleared and the worktree claims writes again.',+ user_message: `gbrain's saved copy of the previous version of ${item.slug} ${what}, so that version cannot be put back. `+ + 'Keep the file as it is on disk now and drop the write that was interrupted?' } });+ }+ return opError('recovery_prior_stage_unavailable', message,+ `Nothing was changed. Something other than gbrain replaced the staged copy at ${stage.path}. Show the user the owner status (gbrain sources writer status --source ${item.source_id} --json) and that path; once it is a regular file again, preview again (${stuckRecoveryPreviewCommand([item.source_id], item.request_id)}).`,+ { docs, fix: { ...statusFix(item.source_id), verify: { argv: status } } });+}++/**+ * `--keep disk` with a staged prior copy that matches nothing recorded: recovery's cleanup never deletes such a copy, so+ * once it is in the backup directory (`<index>.prior-stage`) it is removed here, only while it still holds the bytes the+ * preview hashed. Idempotent: an absent copy was already removed.+ */+function removeMismatchedStage(stage: PriorStageView, item: StuckRecovery, command: string): void {+ let leaf;+ try { leaf = lstatSync(stage.path); }+ catch (error) { if (['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) return; throw error; }+ if (!leaf.isFile() || hashFile(stage.path) !== stage.sha256) throw opError('unexpected_staging_bytes', `The staged prior copy of request ${item.request_id} changed after the preview, so the resolution stopped before removing it.`,+ `Nothing more was changed; the copy from the preview is backed up. Preview again (${command}), show the user the new state and apply the new hash.`, { fix: statusFix(item.source_id) });+ unlinkSync(stage.path);+ flushDirectory(dirname(stage.path));+}+/*** `--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@@ -374,11 +544,11 @@ Promise<ResolutionResult & { replayed: boolean }> {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}: `+ if (!current.item.choices[opts.keep]) throw priorStageUnavailable(current.item, opts.keep, opts.previewHash) ?? 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);+ writeArtifacts(dir, current.item, current.sources, () => previewChangedError(opts.previewHash, command));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,@@ -401,6 +571,12 @@ Promise<ResolutionResult & { replayed: boolean }> {await withFilesystemPublication([...new Set(staged.map(record => record.root))], async () => {for (const { index } of unexpected) {const record = staged[index];+ if (record.staging?.before) {+ // A prior over the single-string ceiling: recovery's own restoration renames the verified staged copy back.+ cleanupRecoveryStaging(record, { keepBefore: true });+ if (hashFile(record.path) !== record.beforeHash) restoreBeforeStage(record);+ continue;+ }cleanupRecoveryStaging(record);publishPersistenceFile({ path: record.path, root: record.root, content: priorBytes(record) }, record.staging?.restoration?.path, undefined, record.mode);}@@ -409,6 +585,11 @@ Promise<ResolutionResult & { replayed: boolean }> {journal = { ...journal, phase: 'written' };await writeJournal(engine, key, journal);} else {+ const mismatched = unexpected.map(({ record, index }) => ({ record, stage: item.files[index].prior.absent ? undefined : item.files[index].prior.stage }))+ .filter(({ stage }) => stage?.state === 'mismatched' && stage.sha256 !== null);+ if (mismatched.length) await withFilesystemPublication([...new Set(mismatched.map(({ record }) => record.root))], async () => {+ for (const { stage } of mismatched) removeMismatchedStage(stage!, item, command);+ });if (!isTerminal(row!)) await abandonWrite(engine, row!, opts.previewHash);journal = { ...journal, phase: 'abandoned' };await writeJournal(engine, key, journal);diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 62c7e76789..3e7f000cf7 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -323,7 +323,8 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ '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 '+ + 'bytes back and the accepted write publishes again, disk keeps the edit and abandons the write (reconcile the page afterwards). A file over 24 MiB is '+ + 'hashed, copied and compared in pieces, and its diff is a bounded summary. A terminal request is '+ 'refused (recovery_choice_refused). Runs only when named.',},'ghost-pages': {diff --git a/src/core/repair/stuck-recovery.ts b/src/core/repair/stuck-recovery.tsindex 0c7dc1ae30..bedd443759 100644--- a/src/core/repair/stuck-recovery.ts+++ b/src/core/repair/stuck-recovery.ts@@ -32,14 +32,23 @@ const selectionOf = (scope: RepairScope, requestId?: string): Selection => ({ soconst hashOf = (scope: RepairScope, selection: Selection, items: StuckRecovery[]) =>previewHash({ kind: 'stuck-recovery-v1', brain_id: scope.brain_id, selection, items: items.map(found => found.digest) });+/** A prior file over the single-string ceiling is the staged copy beside it (recovery-resolve.ts PriorStageView). */+const STAGE_TEXT = {+ verified: 'verified',+ missing: 'missing (--keep prior is unavailable)',+ mismatched: 'does not match its recorded SHA-256 (--keep prior is unavailable)',+} as const;+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)'}`;+ : `sha256 ${file.prior.sha256.slice(0, 16)}… size ${file.prior.size ?? '?'} mode ${file.prior.mode === null ? '?' : file.prior.mode.toString(8)}`+ + (file.prior.stage ? `, staged copy ${STAGE_TEXT[file.prior.stage.state]}` : 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}`] : [])];+ ...(file.diff_path ? [` diff: ${file.diff_path}${file.diff_summary ? ' (summary: a version is over the 24 MiB single-string ceiling, so no full diff)' : ''}`,+ ` reproduce: ${file.diff_command}`] : [])];}export const stuckRecoveryRepair: RepairHandler = {diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex d0e7fe5e3a..118976e8c9 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6393,7 +6393,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"write_interrupted\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"write_interrupted\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/large-pages/segmented-delete-stage-crash.slow.test.ts b/test/large-pages/segmented-delete-stage-crash.slow.test.tsindex 858e9743d8..f0de5f7dd9 100644--- a/test/large-pages/segmented-delete-stage-crash.slow.test.ts+++ b/test/large-pages/segmented-delete-stage-crash.slow.test.ts@@ -9,8 +9,8 @@* torn at the stage's own name (what a crash mid-copy left before the temporary name) while the file still holds* its prior bytes is dropped the same way. When recovery truly cannot proceed (the file was removed and its copy is* torn) the pass records `unexpected_staging_bytes` instead of throwing, and the `gbrain repair stuck-recovery`- * preview still runs: it counts that record, and lists a large-file record blocked on an edited file as refused- * (`recovery_large_file_unsupported`) instead of aborting.+ * preview still runs: it counts that record, and lists a large-file record blocked on an edited file as a resolvable+ * item (stuck-recovery-large.slow.test.ts resolves one) instead of aborting.* 2. Fails when: a torn copy at the stage name throws `unexpected_staging_bytes` on every pass without recording it (the* worktree wedges), the copy is made in place, a temporary copy is left behind, or the preview aborts on a large-file* record.@@ -69,12 +69,12 @@ const cases: Case[] = [for (let pass = 0; pass < 2; pass++) expect(await run('recover')).toMatchObject({ recovered: 'recovering', recovery: 'set', blocked_reason: 'unexpected_staging_bytes' });expect(await run('scan')).toEqual({ items: 0, refused: [], residuals: { unexpected_staging_bytes: 1 } });} },- { name: 'the file edited after its copy: the preview lists it as refused', seam: 'publication:prepared', crashed(crashed, initialized, file) {+ { name: 'the file edited after its copy: the preview lists it as resolvable', seam: 'publication:prepared', crashed(crashed, initialized, file) {expect(crashed.file_sha).toBe(initialized.sha);appendFileSync(file, 'edited by hand\n');}, async recover(run) {expect(await run('recover')).toMatchObject({ recovered: 'recovering', recovery: 'set', blocked_reason: 'unexpected_file_bytes' });- expect(await run('scan')).toEqual({ items: 0, refused: ['recovery_large_file_unsupported'], residuals: { large_file_refused: 1 } });+ expect(await run('scan')).toEqual({ items: 1, refused: [], residuals: {} });} },];diff --git a/test/large-pages/stuck-recovery-large.slow.test.ts b/test/large-pages/stuck-recovery-large.slow.test.tsnew file mode 100644index 0000000000..ca5bea15ba--- /dev/null+++ b/test/large-pages/stuck-recovery-large.slow.test.ts@@ -0,0 +1,341 @@+/**+ * `gbrain repair stuck-recovery` on a page recovery whose prior file is over the single-string ceiling (audit C-22).+ *+ * 1. Protects: a write replacing or removing a canonical file over 24 MiB (here a soft delete) keeps the prior file as a staged copy (`staging.before`)+ * instead of embedding it. When the file is edited while that write publishes, recovery parks the request with+ * `unexpected_file_bytes` and every write on the worktree stops. The repair kind previews it like a small recovery+ * (both fingerprints, a bounded summary instead of a full diff) and resolves it under the same preview hash, backup+ * journal and crash resumption: `--keep prior` puts the staged prior back byte for byte and the write publishes+ * again, `--keep disk` keeps the edit and abandons the write. Every read, hash and copy of the large file streams:+ * no whole-file `readFileSync` of the canonical file, its staged copy or a backup, and no piece over a segment.+ * A staged copy that is missing or does not match its recorded hash refuses `--keep prior` with+ * `recovery_prior_stage_unavailable`, whose fix is the exact `--keep disk` apply, and `--keep disk` still resolves.+ * 2. Fails when: the preview lists the recovery as refused (`recovery_large_file_unsupported`, the old dead end), the+ * preview or apply reads the file whole, the apply skips the preview binding or the backup journal, or the+ * stage refusal names no command.+ * 3. Existing coverage: test/repair-stuck-recovery.test.ts covers the embedded (small) record; segmented-delete-stage-crash.slow.test.ts+ * builds a large record by SIGKILL and checks the preview scan.+ * 4. Fault seams: `publication:prepared` (the hand edit, then a transient database error, so the publication is+ * interrupted with no recorded failure) and the `stuck_recovery:*` seams. `largeFileWork` is the module's counter.+ * Runs on PGLite, and on Postgres when DATABASE_URL is set (GBRAIN_TEST_BACKEND=postgres runs only the Postgres arm).+ */+import { afterAll, afterEach, beforeAll, expect, spyOn, test } from 'bun:test';+import * as fs from 'node:fs';+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, truncateSync, unlinkSync } from 'node:fs';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/operations.ts';+import { OperationError } from '../../src/core/ops/contract.ts';+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer, waitForWrite } from '../../src/core/persistence/service.ts';+import { getWriteRequestById } from '../../src/core/persistence/journal.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { RESOLUTION_OP } from '../../src/core/persistence/recovery-resolve.ts';+import { largeFileWork } from '../../src/core/persistence/large-file.ts';+import { resolveRepairScope, type RepairResult } from '../../src/core/repair/core.ts';+import { repairRunner } from '../../src/core/repair/registry.ts';+import { runRepairCommand } from '../../src/commands/repair.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { withEnv } from '../helpers/with-env.ts';+import { fileSha, writeCanonicalPage } from '../helpers/large-page-file.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-stuck-recovery-large-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const logger = { info() {}, warn() {}, error() {} };+const MiB = 1024 * 1024;+const EDIT = 'edited by hand while the write was publishing\n';++beforeAll(async () => {+ for (const kind of testBackends()) {+ if (kind === 'pglite') { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); continue; }+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);+afterEach(() => installFaultHook(undefined));+afterAll(async () => {+ await withEnv(env, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ });+ rmSync(home, { recursive: true, force: true });+});++interface Stuck {+ engine: BrainEngine; sourceId: string; root: string; slug: string; file: string; id: string; requestId: string;+ prior: { sha: string; size: number }; edited: { sha: string; size: number }; stage: { path: string; hash: string; bytes: number };+}++async function settled<T>(call: () => Promise<T>): Promise<T> {+ for (;;) {+ try { return await call(); }+ catch (error) { if ((error as { code?: string }).code !== 'write_pending') throw error; await Bun.sleep(1000); }+ }+}++/**+ * The real blocked state: a managed source with an imported page over the ceiling; a soft delete of it records its+ * recovery and stages the prior file, the file is edited by hand at `publication:prepared`, and a transient database+ * error interrupts the publication, so the owner's recovery pass parks the request on `unexpected_file_bytes`.+ */+async function stuckLarge(engine: BrainEngine, seed: number): Promise<Stuck> {+ await disposePersistenceConsumer(engine);+ await engine.setConfig('pages.segmented_storage', 'on');+ const root = join(home, `src-${randomUUID().slice(0, 8)}`);+ mkdirSync(join(root, 'notes'), { recursive: true });+ execFileSync('git', ['init', '-q'], { cwd: root });+ const sourceId = `stuck-large-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ await registerLocalWriter(engine, 'cli');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ const slug = `notes/large-${seed}`;+ const file = join(root, `${slug}.md`);+ const prior = writeCanonicalPage(file, 25 * MiB, seed);+ expect(await settled(() => importManagedFile(engine, file, `${slug}.md`, { sourceId, noEmbed: true }))).toMatchObject({ status: 'imported' });+ installFaultHook(async (point, detail) => {+ if (point !== 'publication:prepared' || detail.sourceId !== sourceId || detail.operation !== 'delete_page') return;+ appendFileSync(file, EDIT);+ throw Object.assign(new Error('simulated serialization failure'), { code: '40001' });+ });+ const expected_revision = (await engine.readPageSnapshot(slug, { sourceId }))!.revision;+ try { await submitPageMutation(ctx, { operation: 'delete_page', params: { slug, expected_revision, request_id: randomUUID() } }).catch(() => undefined); }+ finally { installFaultHook(undefined); }+ await disposePersistenceConsumer(engine);+ const [row] = await engine.executeRaw<{ id: string; request_id: string; state: string; blocked_reason: string | null; error_code: string | null; recovery: any }>(+ "SELECT id::text, request_id::text, state, blocked_reason, error_code, recovery FROM persistence_requests WHERE source_id=$1 AND operation='delete_page' ORDER BY sequence DESC LIMIT 1", [sourceId]);+ expect(row).toMatchObject({ state: 'recovering', blocked_reason: 'unexpected_file_bytes', error_code: null });+ expect(row!.recovery).toMatchObject({ before: null, beforeHash: prior.sha, staging: { before: { hash: prior.sha, bytes: prior.size } } });+ expect(fileSha(row!.recovery.staging.before.path)).toBe(prior.sha);+ return { engine, sourceId, root, slug, file, id: row!.id, requestId: row!.request_id, prior, edited: { sha: fileSha(file), size: statSync(file).size },+ stage: row!.recovery.staging.before };+}++const run = <T>(fn: () => Promise<T>) => withEnv(env, fn);++async function repair(s: Stuck, opts: { apply?: boolean; expect?: string; keep?: 'prior' | 'disk' } = {}): Promise<RepairResult> {+ const runner = await repairRunner(s.engine, { apply: opts.apply === true });+ return runner.run('stuck-recovery', await resolveRepairScope(s.engine, s.sourceId), { sourceFlag: s.sourceId, explicit: true, expect: opts.expect, keep: opts.keep });+}++async function cli(s: Stuck, args: 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 runRepairCommand(s.engine, args); } finally { console.log = original; process.stdout.write = write; }+ return printed;+}++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 journal(s: Stuck) {+ return (await s.engine.executeRaw<{ completed_keys: any[] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2', [RESOLUTION_OP, `${s.id}:%`]))+ .map(row => row.completed_keys[0]);+}++/** No recovery bytes left reserved by the source's worktree: on its rows and on its counter (the brain counter is shared by every test). */+async function countersZero(s: Stuck): Promise<boolean> {+ const worktree = (await getWriteRequestById(s.engine, s.id))!.worktree_id;+ const [counts] = await s.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`, [worktree]);+ return Number(counts!.reserved) === 0 && Number(counts!.counter) === 0;+}++const stagingLeft = (s: Stuck) => readdirSync(join(s.root, 'notes')).filter(name => name.includes('.tmp.'));++/**+ * Whole-file `readFileSync` calls made from src/ on any file over the single-string ceiling (the canonical file, its+ * staged copy, a backup), with the call's stack as evidence; and the large-file work counter from zero.+ */+function watchMemory() {+ const original = fs.readFileSync;+ const hits: string[] = [];+ const spy = spyOn(fs, 'readFileSync').mockImplementation(((...args: Parameters<typeof fs.readFileSync>) => {+ const stack = new Error().stack ?? '';+ const path = typeof args[0] === 'string' ? args[0] : null;+ if (path && stack.includes('/src/core/') && existsSync(path) && statSync(path).isFile() && statSync(path).size > 24 * MiB) hits.push(`${path}: ${stack.split('\n').slice(1, 4).join(' | ')}`);+ return original(...args);+ }) as typeof fs.readFileSync);+ for (const key of Object.keys(largeFileWork) as (keyof typeof largeFileWork)[]) largeFileWork[key] = 0;+ return { hits, restore: () => spy.mockRestore(), work: () => ({ ...largeFileWork }) };+}++function expectBounded(memory: ReturnType<typeof watchMemory>): void {+ memory.restore();+ expect(memory.hits).toEqual([]);+ const work = memory.work();+ expect(work.largestPiece).toBeGreaterThan(0);+ expect(work.largestPiece).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);+}++test('the preview lists a stuck large-file recovery with both fingerprints and a bounded summary, read in pieces', () => run(async () => {+ for (const engine of engines) {+ const s = await stuckLarge(engine, 11);+ const memory = watchMemory();+ let out: string;+ try { out = await cli(s, ['stuck-recovery', '--source', s.sourceId]); } finally { memory.restore(); }+ expectBounded(memory);+ expect(out).toContain(`request ${s.requestId} (delete_page ${s.sourceId}:${s.slug}, recovering, unexpected_file_bytes`);+ expect(out).not.toContain('recovery_large_file_unsupported');+ expect(out).toContain(`prior: sha256 ${s.prior.sha.slice(0, 16)}… size ${s.prior.size} mode 644, staged copy verified`);+ expect(out).toContain(`disk: sha256 ${s.edited.sha.slice(0, 16)}… size ${s.edited.size}`);+ expect(out).toContain('recovery sees: neither the prior nor the published bytes (blocked)');+ expect(out).toContain('(summary: a version is over the 24 MiB single-string ceiling, so no full diff)');+ const summaryPath = /diff: (\S+)/.exec(out)![1]!;+ expect(statSync(summaryPath).mode & 0o077).toBe(0);+ expect(statSync(summaryPath).size).toBeLessThan(16 * 1024);+ const summary = readFileSync(summaryPath, 'utf8');+ expect(summary).toContain('summary only, no full diff');+ expect(summary).toContain(`sha256 ${s.prior.sha} ${s.prior.size} bytes`);+ expect(summary).toContain(`sha256 ${s.edited.sha} ${s.edited.size} bytes`);+ expect(summary).toContain(`first difference at byte ${s.prior.size}`);+ expect(summary).toContain(`+${EDIT.trimEnd()}`);+ const [, priorCopy, diskCopy] = /reproduce: cmp (\S+) (\S+)/.exec(out)!;+ expect(fileSha(priorCopy!)).toBe(s.prior.sha);+ expect(fileSha(diskCopy!)).toBe(s.edited.sha);+ const hash = /--expect ([0-9a-f]{64})/.exec(out)![1]!;+ 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(fileSha(s.file)).toBe(s.edited.sha);+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'recovering', blocked_reason: 'unexpected_file_bytes' });+ }+}), 1_800_000);++test('--keep prior restores the staged prior byte for byte, streamed, and the write publishes again', () => run(async () => {+ for (const engine of engines) {+ const s = await stuckLarge(engine, 21);+ const preview = await repair(s);+ expect(preview.listing).toHaveLength(1);+ const memory = watchMemory();+ let result: RepairResult;+ try { result = await repair(s, { apply: true, expect: preview.preview_hash, keep: 'prior' }); } finally { memory.restore(); }+ expectBounded(memory);+ expect(result).toMatchObject({ applied: 1, complete: true, outcomes: { resolved: 1 } });+ expect(statSync(s.file).size).toBe(s.prior.size);+ expect(fileSha(s.file)).toBe(s.prior.sha);+ expect(stagingLeft(s)).toEqual([]);+ const detail = result.outcome_items![0]!.detail!;+ expect(detail).toMatchObject({ keep: 'prior', request_state: 'queued', finished_by: 'this_run' });+ expect(fileSha(join(String(detail.backup_dir), '0.prior'))).toBe(s.prior.sha);+ expect(fileSha(join(String(detail.backup_dir), '0.disk'))).toBe(s.edited.sha);+ const queued = (await getWriteRequestById(engine, s.id))!;+ expect(queued).toMatchObject({ state: 'queued', recovery: null, blocked_reason: null });+ expect(await countersZero(s)).toBe(true);+ expect((await journal(s)).map(entry => entry.phase)).toEqual(['done']);+ const published = await waitForWrite(engine, queued, { engine: engine.kind } as never, 120_000);+ expect(published.state).toBe('committed');+ expect(existsSync(s.file)).toBe(false);+ const [page] = await engine.executeRaw<{ deleted: boolean }>('SELECT deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND slug=$2', [s.sourceId, s.slug]);+ expect(page?.deleted).toBe(true);+ expect(stagingLeft(s)).toEqual([]);+ await disposePersistenceConsumer(engine);+ }+}), 1_800_000);++test('--keep disk keeps the edit byte for byte and abandons the write; the staged prior is backed up, then released', () => run(async () => {+ for (const engine of engines) {+ const s = await stuckLarge(engine, 31);+ const preview = await repair(s);+ const memory = watchMemory();+ let result: RepairResult;+ try { result = await repair(s, { apply: true, expect: preview.preview_hash, keep: 'disk' }); } finally { memory.restore(); }+ expectBounded(memory);+ expect(result.outcomes).toEqual({ resolved: 1 });+ expect(fileSha(s.file)).toBe(s.edited.sha);+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'conflict', error_code: 'source_changed', recovery: null });+ const detail = result.outcome_items![0]!.detail!;+ expect(fileSha(join(String(detail.backup_dir), '0.prior'))).toBe(s.prior.sha);+ expect(fileSha(join(String(detail.backup_dir), '0.disk'))).toBe(s.edited.sha);+ expect(existsSync(s.stage.path)).toBe(false);+ expect(stagingLeft(s)).toEqual([]);+ expect(await countersZero(s)).toBe(true);+ }+}), 1_800_000);++test('the preview hash binds the disk bytes: an edit after the preview refuses preview_changed and changes nothing', () => run(async () => {+ for (const engine of engines) {+ const s = await stuckLarge(engine, 41);+ const preview = await repair(s);+ appendFileSync(s.file, 'another edit after the preview\n');+ const changed = fileSha(s.file);+ const error = await refusal(() => repair(s, { apply: true, expect: preview.preview_hash, keep: 'prior' }));+ expect(error.code).toBe('preview_changed');+ expect(fileSha(s.file)).toBe(changed);+ expect(fileSha(s.stage.path)).toBe(s.prior.sha);+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'recovering', blocked_reason: 'unexpected_file_bytes' });+ expect(await journal(s)).toEqual([]);+ }+}), 1_800_000);++for (const point of ['stuck_recovery:backed_up', 'stuck_recovery:written'] as const) {+ test(`a --keep prior run killed at ${point} resumes from its journal to the same end state`, () => run(async () => {+ for (const engine of engines) {+ const s = await stuckLarge(engine, point.endsWith('backed_up') ? 51 : 52);+ const hash = (await repair(s)).preview_hash!;+ installFaultHook(hit => { if (hit === point) throw new Error(`killed at ${hit}`); });+ await expect(repair(s, { apply: true, expect: hash, keep: 'prior' })).rejects.toThrow(`killed at ${point}`);+ installFaultHook(undefined);+ expect(fileSha(s.file)).toBe(point.endsWith('backed_up') ? s.edited.sha : s.prior.sha);+ expect((await journal(s)).map(entry => entry.phase)).toEqual(point.endsWith('backed_up') ? [] : ['backed_up']);+ expect((await getWriteRequestById(engine, s.id))!.recovery).not.toBeNull();+ const resumed = await repair(s, { apply: true, expect: hash, keep: 'prior' });+ expect(resumed.outcomes).toEqual({ resolved: 1 });+ expect(fileSha(s.file)).toBe(s.prior.sha);+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'queued', recovery: null });+ expect((await journal(s)).map(entry => entry.phase)).toEqual(['done']);+ expect(stagingLeft(s)).toEqual([]);+ expect(await countersZero(s)).toBe(true);+ }+ }), 1_800_000);+}++for (const damage of ['missing', 'mismatched'] as const) {+ test(`a ${damage} staged prior refuses --keep prior with recovery_prior_stage_unavailable naming the exact --keep disk apply, which resolves`, () => run(async () => {+ for (const engine of engines) {+ const s = await stuckLarge(engine, damage === 'missing' ? 61 : 62);+ if (damage === 'missing') unlinkSync(s.stage.path);+ else truncateSync(s.stage.path, Math.floor(s.stage.bytes / 2));+ const torn = damage === 'mismatched' ? fileSha(s.stage.path) : null;+ const out = await cli(s, ['stuck-recovery', '--source', s.sourceId]);+ expect(out).toContain(damage === 'missing' ? 'staged copy missing' : 'staged copy does not match its recorded SHA-256');+ expect(out).not.toContain('--keep prior --apply');+ expect(out).toContain('--keep disk --apply');+ expect(out).not.toContain('by hand');+ const hash = /--expect ([0-9a-f]{64})/.exec(out)![1]!;+ const error = await refusal(() => repair(s, { apply: true, expect: hash, keep: 'prior' }));+ expect(error.code).toBe('recovery_prior_stage_unavailable');+ expect(error.suggestion).not.toContain('by hand');+ const keepDisk = ['gbrain', 'repair', 'stuck-recovery', '--source', s.sourceId, '--keep', 'disk', '--apply', '--expect', hash, '--yes'];+ expect(error.fix).toMatchObject({ argv: keepDisk, consent: ['destructive'], verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', s.sourceId, '--json'] } });+ expect(error.toJSON()).toMatchObject({ docs: 'docs/guides/repair.md#recovery-prior-stage-unavailable' });+ expect(fileSha(s.file)).toBe(s.edited.sha);+ expect(await journal(s)).toEqual([]);+ const result = await repair(s, { apply: true, expect: hash, keep: 'disk' });+ expect(result.outcomes).toEqual({ resolved: 1 });+ expect(fileSha(s.file)).toBe(s.edited.sha);+ expect(await getWriteRequestById(engine, s.id)).toMatchObject({ state: 'conflict', recovery: null });+ const backup = String(result.outcome_items![0]!.detail!.backup_dir);+ expect(fileSha(join(backup, '0.disk'))).toBe(s.edited.sha);+ if (torn) expect(fileSha(join(backup, '0.prior-stage'))).toBe(torn);+ expect(existsSync(s.stage.path)).toBe(false);+ expect(stagingLeft(s)).toEqual([]);+ expect(await countersZero(s)).toBe(true);+ }+ }), 1_800_000);+}