Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/master' into capy/gbra130-p2

garrytan750e19ebc7ba
diff --cc docs/architecture/key-files/core-persistence-request-indexes.md
index 711ea6c3c3,f28bd029be..6296624201
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@@ -5,8 -5,6 +5,9 @@@ Current behavior and load-bearing invar
The online-built request-table indexes (the managed sync checkpoint pair, the page purge's slug index, dream postprocessing's request-id index), the checkpoint validation they serve, the named fault seams the persistence gate and the purge tests inject at, and the stuck-recovery resolution (`gbrain repair stuck-recovery`) that uses them.
- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.
- - `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `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; GBRA-130 C-1, C-4), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk|withdrawn --yes`, a non-interactive apply without `--yes` exits 3; a `--keep` some approved record does not offer refuses `recovery_choice_refused` in the kind's plan before anything runs). `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 page record (`target: 'page'`) or a v2 shared-skill bundle record (`target: 'skill_bundle'`, every file of the bundle; a file matches a recorded version only when `bundleFileHash` also accepts its mode and shape). A bundle record `recoveryFiles` cannot read is listed in `refused` as `recovery_bundle_unsupported` (residual `bundle_refused`; named with `--request-id` it throws with the same ask_user fix). Every withdrawal-mirror effect recovery on the worktree whose file is not a regular file holding its pre-withdrawal or withdrawn bytes is an item too (`target: 'withdrawal_mirror'`, id `effect:<id>`, `effect_id`, the forget's `request_id`; its file view adds `withdrawn`, the recorded post-withdrawal fingerprint, and its only choice is `withdrawn`); a record without usable withdrawn bytes, or bound to another owner epoch, root or incarnation, is listed in `refused` as `recovery_effect_unsupported` (residual `effect_recovery`) with `fix` `{ ask_user, argv: gbrain repair stuck-recovery --source <id> --request-id <request> }` and a `user_message`, and named with `--request-id` it throws with that fix; 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 (an effect's `withdrawn`), 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. An effect item resolves through `resolveEffectRecovery` under the same lock and journal (key `effect:<id>:<preview hash>`): `backed_up` (the edited bytes beside the withdrawn bytes and their diff), `written` (first `rebaseStaleEffectRecovery` (`effect-recovery.ts`): when a later withdrawal moved the page past the record, the record is rebased under its page lock on the latest snapshot's `mirrorContent` bytes (the rendering `mirrorPage` itself writes), its publication stage and reserved bytes following them, and the journal stores the rebased `identity` in the same transaction, so the recorded bytes never put a later-withdrawn fact back on disk and a rerun resumes; a page deleted, replaced or segmented meanwhile refuses `recovery_effect_unsupported` with nothing written; then `upgradeRecoveryStaging` `forward` and the record's `after` bytes published at its publication stage, mode restored), then `claimAndRecoverEffect` (`effects.ts`, the resident pass's own claim + `recoverEffectPublication` + failure recording) materializes the page, clears the record and advances the effect's cursor, and `trueUpRequests` settles the forget's receipt; `--keep disk`/`prior` on it refuse `recovery_choice_refused`, since keeping the edited or pre-withdrawal bytes would let the next sync re-import the forgotten fact. A bundle's `--keep prior` writes the prior bytes of its edited files and `recoverPublication` restores the rest; `--keep disk` keeps every file and abandons the publication; both back up every file first. 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/pathological/c1-effect-stuck-recovery.test.ts` and `test/pathological/c4-bundle-stuck-recovery.test.ts` (both engines; the effect probe asserts the forgotten fact stays forgotten after the resolution, a commit and a sync).
+ - `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. 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`.
++- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10; GBRA-130 C-1, C-4), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk|withdrawn --yes`, a non-interactive apply without `--yes` exits 3; a `--keep` some approved record does not offer refuses `recovery_choice_refused` in the kind's plan before anything runs). `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 page record (`target: 'page'`) or a v2 shared-skill bundle record (`target: 'skill_bundle'`, every file of the bundle; a file matches a recorded version only when `bundleFileHash` also accepts its mode and shape). A bundle record `recoveryFiles` cannot read is listed in `refused` as `recovery_bundle_unsupported` (residual `bundle_refused`; named with `--request-id` it throws with the same ask_user fix). Every withdrawal-mirror effect recovery on the worktree whose file is not a regular file holding its pre-withdrawal or withdrawn bytes is an item too (`target: 'withdrawal_mirror'`, id `effect:<id>`, `effect_id`, the forget's `request_id`; its file view adds `withdrawn`, the recorded post-withdrawal fingerprint, and its only choice is `withdrawn`); a record without usable withdrawn bytes, or bound to another owner epoch, root or incarnation, is listed in `refused` as `recovery_effect_unsupported` (residual `effect_recovery`) with `fix` `{ ask_user, argv: gbrain repair stuck-recovery --source <id> --request-id <request> }` and a `user_message`, and named with `--request-id` it throws with that fix; 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 (an effect's `withdrawn`), 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). An effect item resolves through `resolveEffectRecovery` under the same lock and journal (key `effect:<id>:<preview hash>`): `backed_up` (the edited bytes beside the withdrawn bytes and their diff), `written` (first `rebaseStaleEffectRecovery` (`effect-recovery.ts`): when a later withdrawal moved the page past the record, the record is rebased under its page lock on the latest snapshot's `mirrorContent` bytes (the rendering `mirrorPage` itself writes), its publication stage and reserved bytes following them, and the journal stores the rebased `identity` in the same transaction, so the recorded bytes never put a later-withdrawn fact back on disk and a rerun resumes; a page deleted, replaced or segmented meanwhile refuses `recovery_effect_unsupported` with nothing written; then `upgradeRecoveryStaging` `forward` and the record's `after` bytes published at its publication stage, mode restored), then `claimAndRecoverEffect` (`effects.ts`, the resident pass's own claim + `recoverEffectPublication` + failure recording) materializes the page, clears the record and advances the effect's cursor, and `trueUpRequests` settles the forget's receipt; `--keep disk`/`prior` on it refuse `recovery_choice_refused`, since keeping the edited or pre-withdrawal bytes would let the next sync re-import the forgotten fact. A bundle's `--keep prior` writes the prior bytes of its edited files and `recoverPublication` restores the rest; `--keep disk` keeps every file and abandons the publication; both back up every file first. 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/pathological/c1-effect-stuck-recovery.test.ts` and `test/pathological/c4-bundle-stuck-recovery.test.ts` (both engines; the effect probe asserts the forgotten fact stays forgotten after the resolution, a commit and a sync).
+- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`). A path segment over 255 bytes, or `ENAMETOOLONG` from the lookup, refuses `invalid_params` with detail `file_name_too_long` and a fix naming a slug whose segments fit 240 bytes (`test/pathological/b12-slug-segment-bytes.test.ts`).
+- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. #6355: a session that drops under the attempt (`isConnectionLoss` in `retry-matcher.ts`: connection-class SQLSTATEs, postgres.js's connection codes, `57P01`/`57P02`/`57P03`, the socket errnos) re-runs the attempt after `CONNECTION_LOSS_RETRY_MS` (100/300/900 ms), which is safe because every attempt reads the retained request id first and replays an admitted row; when the session keeps dropping the caller gets `writeOutcomeUnknown` (`write_outcome_unknown`, `reason: connection_lost`, fix: read the request by id), never the raw socket error the crash robot's receipt oracle took for a refusal while the write committed (`test/persistence-admission-connection-loss.test.ts`, forced probes: a lost COMMIT acknowledgment; a dead lent transaction used once with the pool finishing the write). The optional `recover(error)` hook runs before each re-run; `admitWrite` uses it to rebuild the pool (`engine.reconnect`) and to move the re-run from a lent transaction (the consumer's lane, `onPersistenceLane`) to `engine.transaction`, since a dropped reservation fails every later use the same way ("Connection is no longer owned"). Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention. #6278 (B7): also the outstanding-request cap's `detail` format (`outstandingCapacityDetail`, `outstanding=N limit=M`, stamped by `journal.ts` `capacityError`) and its readers `isWriteCapacityWait` / `outstandingCapacityOf`, which the managed drain and `sync-run.ts`'s failure ledger use to tell a refusal that clears by itself from a cumulative cap.
+- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. `decideUnboundWrite` is the one rule page writers and fact writers (`remember`, loop-fact retirement and relink through `fact-write-target.ts`, #6608) apply to a rooted source with no binding: connector → `connector_database`; PGLite not activation-listed database-only (#6449) → automatic claim; otherwise a page with a recorded canonical file, or the key unset, refuses and the rest is database-only. `remember` keeps its frozen `unavailable` code and carries the refusal's detail, docs and fix (`verb-errors.ts`). On a classic brain (managed persistence not activated) the hint leads with the classic write path: write `<checkout>/<slug>.md`, commit it, `gbrain sync --source <id>` (a remote caller is told to ask the user to). The refusal is `retryable: false` with a `fix` of `next: ask_user` and a `user_message` (classic or managed wording), because every way out is the user's choice (`test/unbound-source-hint.test.ts`). Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).
+ - 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 --cc docs/architecture/key-files/core-persistence.md
index 0563152d15,bf17fb8cd0..45fa335c3f
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@@ -12,12 -12,11 +12,11 @@@ Managed facts extraction (withdrawn-can
- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders under the lease lock. Dry-run deletes nothing. Never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still need physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`). The report's `warnings[]` (dry run and real run) carries one `git_durability_not_enabled` entry per filesystem source the effect runner's policy (`gitDurabilityPolicy`) would leave non-durable, with `enable_command`, a read-only `git-durability --enable --dry-run` fix and the note that enabling re-queues skipped Git effects; `persistence-admin.ts` also prints them to stderr without `--json`, and activation proceeds (#5182, `test/writer-activate-durability-warnings-5182.test.ts`).
- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes. `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.
-- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).
+- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, queued, running or recovering effects (the predicate activation uses; each exit says what clears it, and a failing links or facts-backstop effect settles after five attempts), held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `failedEffectHistory` lists terminally failed effects as history (`failed_effects` on the dry run and the applied report, never blockers), each with its code and the exit that retries it: retry-effects for parked targets and failed Git, withdrawal, links and facts-backstop effects, `repair embedding-effects` for a failed embedding effect, none for `embedding_zero_norm` or an effect whose source was archived, replaced or removed (`test/pathological/a15-deactivate-exits.test.ts` runs every printed exit and checks it clears its entry); `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).
- - `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR`: a seven-day writer below it or unmarked keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
+ - `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR` (`page-body/writer-floor.ts`): a seven-day writer below it or unmarked keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`); marked rows of any role meet the floor (ingest log: two partial indexes, v254/v259). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry (`retryManagedAtomBatch` takes the job's signal and deadline, stops between stages on caller cancel, deadline or cycle-lock loss, shares one deadline-bound `MaintenanceWriteWait` with the model rerun, and reports a stop after admission as `write_pending` or an `AbortError` carrying the receipts, never `cancelled`; #6622), authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read (it takes the importer's path for the file: a frontmatter-less file under a directory-inference rule also matches when `readCanonicalAsImported` (BOM strip + `applyInference` at `scannerSourcePath`) reproduces the stored row, with an inferred type treated as undeclared, #6605; reconcile reads the file side through `reconcileFileReading` in `reconcile-state.ts`); the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).
- - `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.
Atom completion admits replacement and revision-pinned stale-atom deletion children together.
Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.
Derived atom pages may regenerate or retire when their canonical file is already absent, while ordinary page writes retain missing-file refusal.
@@@ -38,8 -38,9 +37,8 @@@
- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.
- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`. `pollCommand` (#6255) renders the envelope's receipt `fix.argv` (`gbrain write-request --brain <id> -- <request_id>`), else pins that argv to the CLI routing; each argument is shell-quoted (`src/core/shell-quote.ts`, fix wave 13 P1.15).
- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.
- - `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits), transient database failures and raw errors `classifyItemFailure` calls run-scoped (a lost connection, a failed transaction, an abort, a full disk) do not count). A `links` or `facts-backstop` effect counts its failures the same way (`data.target_failures`, no target; run-scoped failures, including run-scoped refusal codes, never count, and a 57014 counts as `statement_timeout`): at five a links effect completes as skipped with the code (`outcome: { links: 'skipped', reason }`; the edges are derived and `gbrain extract --stale` recovers them) and a facts-backstop effect fails with it; a pass's counted failures settle when the pass ends under an `ItemRun` (`effects.derived_retry_budget`), and a pass where most of them failed counts none (each retries as `item_failures_systemic`) (GBRA-130 A-11, `test/pathological/a11-effect-retry-budget.test.ts`). An embedding scan (a withdrawal's exact targets or a source scan) parks the page whose provider call keeps failing once its per-page budget (`MAX_RATE_LIMIT_RETRIES`) is spent, with the failure's code, and moves on with a fresh budget; provider throttling (`isEmbedRetriableError`), configuration, budget and disabled errors and run-scoped failures stay effect-wide (A-13, `a13-embedding-target-park.test.ts`): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Both claim queries hold a request's Git and embedding effects only while its withdrawal mirror is queued or running; each Git or embedding attempt rereads its mirror (`mirrorGates`, every mirror not committed plus a committed one that recorded its publications): a mirror queued or running again (retry-effects after the claim) makes the attempt wait (`withdrawal_mirror_pending`); otherwise the mirror's recovery records each page whose file it rewrote (`data.published`) and its cursor is never proof: a Git page walk commits a page the mirror passed only when the file's raw bytes hash-equal the mirror rendering of the current snapshot (the serialization `mirrorPage` writes; this also covers a mirror from before publications were recorded and a published file later reverted by hand) and otherwise skips it (`withdrawal_not_mirrored`), a single-file Git effect needs the recorded publication, embedding behind a failed mirror needs the recorded publication, and behind a failed mirror every other page, including a single-file Git effect's page in a coalesced group, is parked with `withdrawal_mirror_failed`, so Git never commits a file that may still hold withdrawn text. When the mirror commits, the same transaction re-arms its request's Git and embedding targets parked `withdrawal_mirror_failed` (`rearmWithheldTargets`: a scan revisits them through `data.retry_slugs`; other parks stay), and each effect pass repeats it for the requests it touched, so no second retry-effects is needed. Lifecycle settlement (`topology-locks.ts`) waits on a queued mirror, not a failed one (A-12, `a12-withdrawal-mirror-gate.test.ts`). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); it also covers parked embedding targets, failed Git, withdrawal-mirror, links and facts-backstop effects without parked targets (one more attempt; a mirror that failed `source_changed` reruns from its cursor once the source is back) and an embedding effect that failed `source_changed`, so one call reruns a failed mirror and re-arms the pages it withheld; `parkedOnly` keeps the credential-change retry (`retryParkedPushes`) to parked Git and withdrawal effects; tests: `persistence-effect-parking.test.ts`. `repair embedding-effects` skips failed embedding effects with parked targets and zero-norm refusals. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated. Only the writer, holding its writer lock, removes a lock `index-lock-reclaim.ts` proves abandoned (its header lists the proof), with a receipt doctor `parked_effects` reports, then retries the step and the effects that lock parked; otherwise `git_index_stale` carries an `ask_user` fix. Steps run with `GIT_OPTIONAL_LOCKS=0`, an index-scaled deadline (`gitStepTimeoutMs`) and a 10 s SIGTERM grace (#6932).
-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). A page stored in segments is mirrored and committed too, streamed (see the segmented withdrawal mirror entry in `core-persistence-request-indexes.md`). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated. Only the writer, holding its writer lock, removes a lock `index-lock-reclaim.ts` proves abandoned (its header lists the proof), with a receipt doctor `parked_effects` reports, then retries the step and the effects that lock parked; otherwise `git_index_stale` carries an `ask_user` fix. Steps run with `GIT_OPTIONAL_LOCKS=0`, an index-scaled deadline (`gitStepTimeoutMs`) and a 10 s SIGTERM grace (#6932).
++- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits), transient database failures and raw errors `classifyItemFailure` calls run-scoped (a lost connection, a failed transaction, an abort, a full disk) do not count). A `links` or `facts-backstop` effect counts its failures the same way (`data.target_failures`, no target; run-scoped failures, including run-scoped refusal codes, never count, and a 57014 counts as `statement_timeout`): at five a links effect completes as skipped with the code (`outcome: { links: 'skipped', reason }`; the edges are derived and `gbrain extract --stale` recovers them) and a facts-backstop effect fails with it; a pass's counted failures settle when the pass ends under an `ItemRun` (`effects.derived_retry_budget`), and a pass where most of them failed counts none (each retries as `item_failures_systemic`) (GBRA-130 A-11, `test/pathological/a11-effect-retry-budget.test.ts`). An embedding scan (a withdrawal's exact targets or a source scan) parks the page whose provider call keeps failing once its per-page budget (`MAX_RATE_LIMIT_RETRIES`) is spent, with the failure's code, and moves on with a fresh budget; provider throttling (`isEmbedRetriableError`), configuration, budget and disabled errors and run-scoped failures stay effect-wide (A-13, `a13-embedding-target-park.test.ts`): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). A page stored in segments is mirrored and committed too, streamed (see the segmented withdrawal mirror entry in `core-persistence-request-indexes.md`). Both claim queries hold a request's Git and embedding effects only while its withdrawal mirror is queued or running; each Git or embedding attempt rereads its mirror (`mirrorGates`, every mirror not committed plus a committed one that recorded its publications): a mirror queued or running again (retry-effects after the claim) makes the attempt wait (`withdrawal_mirror_pending`); otherwise the mirror's recovery records each page whose file it rewrote (`data.published`) and its cursor is never proof: a Git page walk commits a page the mirror passed only when the file's raw bytes hash-equal the mirror rendering of the current snapshot (the serialization `mirrorPage` writes; this also covers a mirror from before publications were recorded and a published file later reverted by hand) and otherwise skips it (`withdrawal_not_mirrored`), a single-file Git effect needs the recorded publication, embedding behind a failed mirror needs the recorded publication, and behind a failed mirror every other page, including a single-file Git effect's page in a coalesced group, is parked with `withdrawal_mirror_failed`, so Git never commits a file that may still hold withdrawn text. When the mirror commits, the same transaction re-arms its request's Git and embedding targets parked `withdrawal_mirror_failed` (`rearmWithheldTargets`: a scan revisits them through `data.retry_slugs`; other parks stay), and each effect pass repeats it for the requests it touched, so no second retry-effects is needed. Lifecycle settlement (`topology-locks.ts`) waits on a queued mirror, not a failed one (A-12, `a12-withdrawal-mirror-gate.test.ts`). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); it also covers parked embedding targets, failed Git, withdrawal-mirror, links and facts-backstop effects without parked targets (one more attempt; a mirror that failed `source_changed` reruns from its cursor once the source is back) and an embedding effect that failed `source_changed`, so one call reruns a failed mirror and re-arms the pages it withheld; `parkedOnly` keeps the credential-change retry (`retryParkedPushes`) to parked Git and withdrawal effects; tests: `persistence-effect-parking.test.ts`. `repair embedding-effects` skips failed embedding effects with parked targets and zero-norm refusals. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated. Only the writer, holding its writer lock, removes a lock `index-lock-reclaim.ts` proves abandoned (its header lists the proof), with a receipt doctor `parked_effects` reports, then retries the step and the effects that lock parked; otherwise `git_index_stale` carries an `ask_user` fix. Steps run with `GIT_OPTIONAL_LOCKS=0`, an index-scaled deadline (`gitStepTimeoutMs`) and a 10 s SIGTERM grace (#6932).
-- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`).
- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as do `takes_remove` and `takes_rebuild` (`LOCAL_CLI_LOCAL_ONLY_OPS`) for the `local_cli` principal (write scope still checked; `gbrain takes remove` and `gbrain takes rebuild` defer their engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).
diff --cc docs/architecture/key-files/files-and-sync-2.md
index fb40033baf,cba4cec384..c40a4d7d4d
--- a/docs/architecture/key-files/files-and-sync-2.md
+++ b/docs/architecture/key-files/files-and-sync-2.md
@@@ -21,7 -17,6 +21,7 @@@ Current behavior and load-bearing invar
- `src/core/repair/rename-identity.ts` — `gbrain repair rename-identity` (#6729), explicit-only, preview-bound, destructive. `plan` selects one open pair (`--slug`/`--from`), hashes `identityRemedyParts` (brain, pair, both page ids and revisions, disposition) and saves the approved set; with no pair named it lists the open pairs. On a managed brain a carry preview returns no items with `details.code: managed_remedy_unavailable` and the `--close` preview, and an apply refuses with that code. `carryIdentity` (classic only): one maintenance transaction under both page locks re-checks the hash, the open record and `fenceRowChecks`, merges matching fence rows onto the old rows, retires the provisional page under `purgedSlug`, moves the old page to the new slug (`updateSlug` redirect), moves the provisional's page-id rows (`movePageIdReferences`), imports the new file, settles the record `remedied`. `--close` settles `closed`. Refusals: `fact_rows_collide`, `managed_remedy_unavailable`, `changed_since_preview`, `preview_changed`, `invalid_params`.
- `src/core/persistence/sync-prescreen.ts` — #6712 PR 1 (L1): the discovery prescreen and drift baseline. After `discoverManagedSync` freezes identities, `prescreenSyncEntries` reads the pinned blobs (`readTreeBlobs`, one recursive listing for a large set) and the import provenance of every Git import of an existing page, and `classifyBaseline` marks each `prescreened` (disk blob, revision and `syncImportParserFor` fingerprint all match; bypassed under `--full` and for held paths) or `drift` (`database`: the page moved, the file did not; `both`/`unknown` in a tree walk or for a `file_drift` hold). A page whose current revision a committed managed-sync request wrote, or whose writer's publication wrote to its file (a write-through `git` effect), is not guarded (`fileBackedRevisions`), and drifted pages under `storage.keep_db` prefixes leave the manifest as drift candidates (`releaseKeepDbDrift`, `recordDriftSkip`). The run passes prescreened entries through `waivePrescreenedRun` (`sync-waivers.ts`); `freezeEntry` holds a drifted import `file_drift` (`fileDriftHold`, `sync-page-fault.ts`) unless `sameContentAtOrigin` proves it a no-op. `movedDriftHolds` re-screens drift holds whose page moved. Tests: `test/sync-prescreen-drift-6712.test.ts` (both engines).
- `src/core/persistence/sync-image.ts` — #6529: managed sync's image branch. With multimodal embedding on, `freezeEntry` (`sync-run.ts`) freezes an image entry as its bytes in base64 (`frozenImageIntent`; `rawHash` stays the file sha256, so the working-tree check and the hash no-op are unchanged) and `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncImage`, which runs `importImageFile` with `prepare` (the coordinated path `gbrain import` uses in `import-prepare.ts`): the importer decides the hash no-op, OCRs and embeds the image at preparation inside the sync budget (`--no-embed` skips both; the caption chunk's text vector is deferred to `embed --stale`), and the apply records `source_path`, releases the path's hold and re-reads the snapshot. A company plan refuses (`profile_incompatible`), a screening preparation (`sameContentAtOrigin`, the no-op waiver in `sync-waivers.ts` and `unchangedManagedImport` in `import-mutations.ts` return early for images) is refused rather than paid for, newer working-tree bytes or a vanished file refuse `source_changed`, and a Git rename publishes the new slug and soft-deletes the old page. `import-file.ts` records `source_path` on the legacy importer's hash-skip path too (`refreshSourcePath`), so no image import leaves it NULL. Tests: `test/managed-sync-images-5493.test.ts` (both engines), `test/embed-stale-images-managed-6529.test.ts`.
- - `src/core/persistence/sync-streamed.ts` — Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. With `pages.segmented_storage` on, `freezeEntry` (`sync-run.ts`) freezes such a file by reference instead of holding it by its size: `streamedSyncBodyRef` hashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) into `intent.body_ref` (`git_blob`, or `input_file` for an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file over `pages.max_bytes` or a non-Markdown file is held as before. `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncStreamed`, which streams it through `importStreamedMarkdownFile` (`page-body/streamed-import.ts`, `coordinated`; `moved` on a rename keeps an implicit type following the new path) and publishes database-only; a rename moves the page first and re-seals an unchanged body (`sealSegmentedPage`). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (`streamedRefusalHold` in `sync-screen.ts`); a dry run lists it in `screen_skipped` as `page_body_segmented`; `groupableIntent` (`sync-group.ts`) keeps it out of bulk groups. Tests: `test/large-pages/managed-sync-streamed.test.ts` (both engines), `managed-sync-streamed-crash.test.ts` (owner killed at `consumer:prepared`), `managed-sync-streamed-memory.slow.test.ts` (VmHWM).
+ - `src/core/persistence/sync-streamed.ts` — Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. With `pages.segmented_storage` on, `freezeEntry` (`sync-run.ts`) freezes such a file by reference instead of holding it by its size: `streamedSyncBodyRef` hashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) into `intent.body_ref` (`git_blob`, or `input_file` for an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file over `pages.max_bytes` or a non-Markdown file is held as before. `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncStreamed`, which streams it through `importStreamedMarkdownFile` (`page-body/streamed-import.ts`, `coordinated`; `moved` on a rename keeps an implicit type following the new path; `slug` is the admitted page, the one recording the file as its origin, as the inline import targets) and publishes database-only, recording the origin through `bindOrigin` (B-14: a renamed page keeping its origin takes the file, no twin at the path's slug); a rename moves the page first and re-seals an unchanged body (`sealSegmentedPage`). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (`streamedRefusalHold` in `sync-screen.ts`); a dry run lists it in `screen_skipped` as `page_body_segmented`; `groupableIntent` (`sync-group.ts`) keeps it out of bulk groups. Tests: `test/large-pages/managed-sync-streamed.test.ts` (both engines), `managed-sync-streamed-crash.test.ts` (owner killed at `consumer:prepared`), `managed-sync-streamed-memory.slow.test.ts` (VmHWM), `streamed-sync-origin-b14.test.ts` (both engines).
-- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?, expectedFileBytes?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.
+- `src/core/url-clone.ts` — gbrain-owned `sources add --url` clones (#6946, GBRA-130 C-2). `isOwnedClone` (config `managed_clone` or a `local_path` under the default clone dir) and `defaultCloneDir`; `urlCloneReadOnly` is the one predicate (owned clone on a brain without managed persistence) the fence writer (`fence-write.ts`, `databaseOnlyReason: 'url_clone'`), write-through (`skipped: 'url_clone'`), timeline write-through, unfenced-facts adoption, the empty-fence guard and `sourceMirrorReadOnly` consult, so nothing gbrain writes lands in a checkout it updates with `git pull --ff-only`. `urlClonePullBlock` reads the tracked changes of a clone whose pull failed and returns `pull_blocked_local_changes` with an `ask_user` fix naming the preview `gbrain repair url-clone-fences --source <id>`; `formatUrlClonePullBlock` renders it for sync's stderr (`sync/preflight.ts`) and `cycle.ts` puts it in the sync phase detail as `pull_blocked`. Test: `test/pathological/c2-url-clone-fences.test.ts`.
+- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?, expectedFileBytes?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward. #6946: on a gbrain-owned `--url` clone of an unmanaged brain (`urlCloneReadOnly`), `writePageThrough` returns `skipped: 'url_clone'` and `deletePageThrough` returns `removed: false, skipped: 'url_clone'`; `timeline-write-through.ts` skips the same way.
diff --cc docs/architecture/key-files/persistence-stalls.md
index 5a4b3b2b76,1eba082a92..de1c383bbe
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@@ -22,9 -22,9 +22,9 @@@ owner (`owner_wedged_here`), movement s
- `src/core/persistence/claim-phase.ts` — #6176 / #6278: the phase and step a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim `ClaimPhaseClock` in the consumer (single and group routes); `claimPhaseStamp` is the jsonb every claim, renewal and group dispatch mark stores in `persistence_requests.claim_phase` (v217): phase `preparing` or `publishing`, claim start, phase start, the execution token (so a later claim never reads an earlier claim's ages), the `step` in flight and when it began, `waiting_on` and the owning process (`owner`: command kind, pid, gbrain build; #6650 boot id, start). Preparers (`sync-prepare.ts`, `page-prepare.ts`, `prepared-maintenance.ts`, link resolution) call `enterClaimStep(clock, step, signal, waitingOn)` at each await boundary: it names the step, records what the await waits on (`git`, `fs`, `db`, `pool`, else `unknown`: set only where observed, never inferred) and throws the preparation's abort reason, so cancellation reaches a preparer between its queries even though the queries take no signal. `claimStateOf` reads a row back from the current claim's stamp only: `preparing`/`publishing` (live renewal), `publication_transaction` (claim lapsed while running, read on the database clock: a transaction holds the row or the owner is gone; requeued once it ends), `file_publication` (`publication_started`; recovery finishes it) or `unrecorded`, with claim and phase ages, `step`, `step_age_ms`, `waiting_on`, `owner`, `resumes_on_its_own` and a `why`. `claimStall` is the `preparation_overdue` verdict (`claim.stall`) for a preparing claim past its budget. `EXPIRED_PREPARING_CHARGE_SQL` is the one rule an expired-claim reclaim charges a preparation attempt by: only a claim stamped `preparing` under the token being reclaimed. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Consumer and group-publish store the stamp on every renewal, so writer status (`diagnostics.ts`, `claim` on each running blocker, never the token) and doctor name a stuck phase and step without an extra statement per write. Tests: `test/persistence-write-stall.test.ts`, `test/persistence-claim-step.test.ts`.
- `src/core/persistence/preparation-budget.ts` + `src/commands/config/preparation-keys.ts` — #6278: how long a claimed write may prepare and how many cut-offs it survives. `preparationKind` sorts a request into `foreground` (`remember`, and `put_page`/`edit_page` with no internal intent: the consumer's 30 s `preparationMs`), `sync` (`managed_sync_*` kinds: `persistence.sync_preparation_ms`, default 120000) or `maintenance` (every other kind: `persistence.maintenance_preparation_ms`, default 120000). `persistence.preparation_ceiling_ms` (default 600000, 60000 to 3600000, floored at the larger budget plus 30 s) is the hard ceiling for a preparation that ignores cancellation and `persistence.max_preparation_attempts` (default 2, 1 to 10) the cut-offs before a request finishes `preparation_stalled`; a missing or out-of-range value keeps its default (`resolvePreparationPolicy`). The four keys ride the write-switch snapshot (`switches.ts`, one statement, 5 s TTL) together with the `preparation_deadlines` kill switch, so a claim never reads config on its own. `startPreparation` runs a preparer under its budget and the budget wins the race even when the preparer ignores its signal (the signal aborts with `{ code: 'preparation_deadline' }`; a result that lands after the budget on the clock still reads as a deadline; the late result is the caller's to drop); `racePreparation` is its outcome-only form for the sync's out-of-consumer preparations (`sync-waivers.ts`). `validatePreparationConfigValue` is `config set`'s structured refusal (each key's range, and the ceiling rule across the sibling keys; usage error exit 2, nothing written), wired in by `refuseInvalidPreparationValue`. `persistence.max_claim_ms` keeps its doctor meaning. Tests: `test/persistence-preparation-budget.test.ts`.
- `src/core/persistence/bounded-reads.ts` — #6278 (plan item 1.4): a preparation read that can wait on a relation lock ends at the budget on the server. Phase 0 (`docs/eval/managed-sync-stall-repro.md`) showed that through a transaction-mode pooler gbrain's `statement_timeout` startup parameter is dropped, so a preparation read outside the publication transaction had no server-side bound; an `ACCESS EXCLUSIVE` lock on `pages` held elsewhere pinned the member's origin check and its connection until the lock lifted, and with the budget alone the released member's statement kept running as a zombie that blocked its root until the ceiling. `boundedReads(engine, clock)` is the engine view every preparer reads through (`prepareManagedSyncMutation` and its helpers, `preparePageMutation`, `prepareFactFenceAdoption`, the sync's out-of-consumer preparations): each unmemoized raw statement runs with `executeRaw`'s `timeoutMs` set to the clock's remaining budget (`ClaimPhaseClock.deadlineAt`, set by `startClaimPhase(now, signal, budgetMs)`) and the clock's signal, which ends only the wait for a free connection. On Postgres `timeoutMs` runs the statement on a reserved connection as `BEGIN; SET LOCAL statement_timeout; <statement>; COMMIT` in one pipelined round trip, so the bound holds through the pooler and `SET LOCAL` ends with it; inside a transaction and on PGLite the option is ignored. A statement the server ends (57014, or a 55P03 raised by a shorter session `lock_timeout`) surfaces as the member's own `preparation_deadline` (`PreparationDeadlineError`, or the signal's reason once it aborted), which `preparationAbortReason` classifies as the deadline: the consumer and the group route handle it as the deadline even inside the budget (charged release, `preparation_stalled` at the limit, the group cut like the timer), never as a `storage_error` receipt or an uncharged release. The memo rule holds: `preparationReads` answers a bounded read once with the member's bound and signal dropped. Engine helpers that bypass `executeRaw` (`readPageSnapshot`, the import pipeline) stay under the consumer's race and the ceiling. Tests: `test/persistence-bounded-reads.test.ts`, `test/e2e/persistence-preparation-lock-wait-postgres.test.ts` (a real lock held in another session), the server-ended cases in `test/persistence-consumer-scheduling.test.ts` and `test/e2e/persistence-group-deadline-postgres.test.ts`. GBRA-75 wave 9: `withBoundedReadSession` gives a waiver screen (`unchangedSyncImport`) one reserved ordinary-pool connection (a long-hold permit; none left, or PGLite, runs the screen as before) on which its bounded reads share one transaction: `BEGIN; SET LOCAL statement_timeout` once, `COMMIT` when the screen settles. The bound stays per statement on the server: it is set again in the read's pipeline once the bound in force differs from the read's own by more than `BOUNDED_SESSION_SLACK_MS` (25 ms). A waiver run (`waiveRun` in `sync-run.ts`) opens one session for all its screens, and a screen inside it joins it. Session reads are named prepared statements (`ReservedConnection.executeRaw` `prepare`, ANDed with the connection option as `runUnsafe` does). A failed read rolls back and the reads it aborted (25P02) run again in a new transaction; a read after the screen settled takes the per-read path. Test: `test/persistence-bounded-read-session.test.ts` (real lock wait and no remaining statement on Postgres).
-- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`.
+- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`. `transfer_in_progress` is `wait` until the drain's `prepared_at` is `TRANSFER_STALE_MINUTES` (30) old, then `ask_user` naming the accept and the exact `transfer cancel` argv (a drain with no `prepared_at` keeps the wait).
- `src/core/persistence/repair-busy.ts` — #6278: the busy set a repair must not write while a managed sync runs. `loadRepairBusySet(engine, sourceId, incarnation)` returns the paths and slugs named by queued, running and recovering requests and terminal rows with an open recovery (both rename endpoints included) plus, for every unfinished `managed-sync` cursor of the incarnation, the entries of its frozen `managed-sync-manifest` from the cursor's index on (a path with a `sync-hold` record is left out: the sync retries a held file only when its bytes change); it never throws and fails closed (`unknown` set, so `repairBusy` answers true for everything) when a query fails or a cursor's manifest is missing. `repairBusyMessage` is the hold text, `repairBusyError` the `sync_in_progress` refusal (`reason` `candidate_in_flight` or `busy_set_unreadable`) `submitManagedFileRepair` raises at admission. Tests: `test/repair-busy.test.ts`, `test/repair-fences.test.ts`, `test/repair-fences-during-catchup.test.ts` (Postgres: `test/e2e/repair-fences-during-catchup-postgres.test.ts`).
- - `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement, + the 5 s #6650 dead-owner scan, mirroring the claim, recovery, expired-claim, effect, projection (inline rows windowed by `projection-window.ts`) and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (PGLite, 1,000 pages: ~9.5 ms mean, ~18 ms p99 per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes); a provably dead owner's claim goes in 5 s (#6650). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`).
+ - `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement, + the 5 s #6650 dead-owner scan, mirroring the claim, recovery, expired-claim, effect, projection (inline rows windowed by `projection-window.ts`) and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. A statement the database ended with 57014 (statement timeout or cancel: `coordinator.ts` `writeInterruption`) is charged too, in `finishUnpublishedFailure` and in `publishMutation`'s recovery route, and at the limit ends the request `failed` with `write_interrupted` instead of a `database_contention` release; contention with other transactions (55P03, 40001, 40P01), a dropped connection or a restarting database is never charged (`test/persistence-write-interrupted.test.ts`). The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (PGLite, 1,000 pages: ~9.5 ms mean, ~18 ms p99 per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes); a provably dead owner's claim goes in 5 s (#6650). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`).
- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken or waived entry, or #6712 a slug or page id shared with a member in flight or held, `dependencyKeys`) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the pending entry (settled by fault class; later members stay in the window, #6712), a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). #6712: each member keeps its own fate (sync groups keep claim 64, width four, ordered release, `syncGroup`): a failed preparation settles before the rest publish as a group; a sync member its lane group's transaction refused settles alone, the rest requeue (`settleCulprit`); other failures roll back and members publish singly. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) and the files of one managed import batch (`intent.import_batch`, key `import:`, grouped on PGLite too; `independentGroup` names both) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). A single foreground page write publishes here too, as a group of one (core-persistence-continued.md, `switches.ts` entry). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). A `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member (GBRA-75 wave 10: `preparationReads` answers `getConfig` from one `getAllConfig` per group; an import group's members also read their own `{ sourceId, includeDeleted: true }` snapshot from one batch and coalesce `findDuplicatePage` into one `findDuplicatePages` statement through `import-reads.ts`, and the group's preparation runs inside `withScreeningPaths`; publication's `validate`/`checkPaths` run after it, unmemoized) and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-postgres.test.ts`.
- `src/core/persistence/identity.ts` — local writer and host identity. GBRA-75 wave 7: `localHostId` / `localHostIdentity` / `existingLocalHostId` share one cache of the validated `host.json`, keyed on the path (recomputed from `persistenceHome()` on every call, so a `GBRAIN_HOME` change misses) plus `statSync(bigint)` dev, ino, mtimeNs, ctimeNs and size. ENOENT is a miss (`existingLocalHostId` never mints); any other stat error reads uncached, so `writer_identity_invalid` still throws on every call; an invalid document is never cached; a file modified under 2 s ago is read but not cached (same-size rewrites inside one timestamp tick). `scripts/persistence/harness.ts` `selectFixtureHost` (rename over the path) stays correct. Tests: `test/persistence-host-identity-cache.test.ts`.
- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce, the `/proc/self/ns/pid` inode where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.
diff --cc docs/guides/repair.md
index 4ca5abff6d,513326228d..5627788632
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@@ -135,8 -135,7 +135,8 @@@ work behind exits 0, so scripts should
| `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. 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). |
+| `content-receipt-root` | `sync_freshness` (`content_receipt_stale`) | Explicit-only, preview-bound, owner host. Rebinds a gbrain-owned content source's shared-skills content receipt that still names an old root after a writer transfer or relocation, when the owner's tree still hashes to the recorded worktree manifest. The receipt row only; the previous value is kept under `<key>.backup`. See [content receipt root](#content-receipt-root). | A receipt whose source path, owner host or tree does not match: listed with its class and the step to run first. |
- | `stuck-recovery` | none (`gbrain sources writer status` shows the request `recovering`, or the withdrawal-mirror effect, with `unexpected_file_bytes`) | Explicit-only, preview-bound, destructive consent. Resolves a live page or shared-skill bundle publication recovery whose file matches neither its recorded prior nor its published bytes, and a withdrawal-mirror effect recovery whose file was edited while it was mirroring; each 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 (every file of a bundle one way); an effect's only choice, `--keep withdrawn`, backs up the edit and writes the withdrawn version. See [stuck recovery](#stuck-recovery). | A terminal request with its recovery still set (listed as refused, `recovery_choice_refused`), an effect or bundle record that cannot be resolved (listed as refused, `recovery_effect_unsupported` or `recovery_bundle_unsupported`, with an ask_user fix), 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`, or the withdrawal-mirror effect, with `unexpected_file_bytes`) | Explicit-only, preview-bound, destructive consent. Resolves a live page or shared-skill bundle publication recovery whose file matches neither its recorded prior nor its published bytes, and a withdrawal-mirror effect recovery whose file was edited while it was mirroring; each 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 (every file of a bundle one way); an effect's only choice, `--keep withdrawn`, backs up the edit and writes the withdrawn version. 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`), an effect or bundle record that cannot be resolved (listed as refused, `recovery_effect_unsupported` or `recovery_bundle_unsupported`, with an ask_user fix), `--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. |
@@@ -2894,29 -2795,33 +2913,35 @@@ applies to `gbrain jobs authorize-legac
`recovery_bundle_unsupported`: `gbrain repair stuck-recovery` found a
shared-skill bundle recovery record (several skill files published together)
-among the selected requests. It resolves page recoveries only, so nothing was
-changed. Inspect the request read-only with `gbrain sources writer status
---source <id> --json`, ask the user which version of each skill file to keep,
-put those bytes in place by hand, and let the resident writer finish the
-recovery. Pass `--request-id` to resolve the page recoveries on the same
-source.
+that this binary cannot read: an unknown shape, or more files than a bundle
+holds. A readable bundle record is resolved like a page recovery (see
+[stuck recovery](#stuck-recovery)). Nothing was changed. The preview lists it
+under `refused`, and its `fix` is `ask_user` with the exact preview command;
+naming it with `--request-id` refuses with this code. Upgrade gbrain on the
+brain host and preview again, or ask the user which version of each skill file
+to keep, put those bytes in place by hand, and let the resident writer finish
+the recovery.
- ### 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 refused
diff --cc scripts/page-body-readers-baseline.tsv
index 45dbd70641,79c501e37e..b72530641c
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@@ -376,8 -376,8 +376,9 @@@ src/core/persistence/connector-sync.ts
src/core/persistence/core-guard.ts prepareCoreGuard field INLINE
src/core/persistence/effect-facts.ts bodyAlreadyOffered field META
src/core/persistence/effect-links.ts mentionTargets field INLINE inline arm; a segmented page streams its compiled truth through extractSegmentedPageLinks
- src/core/persistence/effect-recovery.ts mirrorContent call:serializePageToMarkdown SEGW the withdrawal mirror's bytes: mirrorPage skips a segmented target (skipped reason page_body_segmented) and rebaseStaleEffectRecovery refuses one before rendering; per-segment mirror in PR 2
++src/core/persistence/effect-recovery.ts mirrorContent call:serializePageToMarkdown SEGW the inline withdrawal mirror bytes for a stale-record rebase: rebaseStaleEffectRecovery refuses a segmented page before rendering (a segmented mirror streams through unreadPageFile)
src/core/persistence/effects.ts publishGitPage call:serializePageToMarkdown SEGW segmented target skipped (skipped reason page_body_segmented) before the serialize
+ src/core/persistence/effects.ts mirrorPage call:serializePageToMarkdown SEGW segmented target skipped (skipped reason page_body_segmented) before the serialize; per-segment mirror in PR 2
src/core/persistence/embedding-settlement.ts listEmbeddingCandidates sql META
src/core/persistence/facts-maintenance.ts prepareManagedFactsSession field META
src/core/persistence/facts-prepare.ts prepareManagedFactsMutation call:serializePageToMarkdown SEGW assertInlineBody first
diff --cc src/core/cli-flag-registry.generated.ts
index 272f3f6fa6,29652e62be..9dabee0140
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@@ -74,10 -74,10 +74,10 @@@ export const CLI_FLAG_REGISTRY: Record<
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--catch-up', '--chat-model', '--check', '--clear-never-installed', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--install', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--catch-up', '--chat-model', '--check', '--clear-never-installed', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--install', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--type', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
++ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
diff --cc src/core/persistence/effect-model.ts
index 6e006bb609,d4fb834bb8..478d8403fa
--- a/src/core/persistence/effect-model.ts
+++ b/src/core/persistence/effect-model.ts
@@@ -29,13 -29,17 +29,19 @@@ export function contentRepairCommit(pat
return { subject: contentRepairCommitSubject(path), line: `${safe(path)} (frontmatter_slug_conflict)`, trailer: contentRepairTrailer(receipt) };
}
export interface ParkedTarget { slug?: string; error_code: string }
+ /** `page_body_segmented`: a segmented page an older binary's mirror or Git scan passed by; this one mirrors and commits it. */
-export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' | 'page_body_segmented' }
+export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' | 'page_body_segmented' | 'withdrawal_not_mirrored' }
+/** The code a page behind a failed withdrawal mirror is parked with: its file may still hold the withdrawn text. */
+export const WITHHELD_BY_MIRROR = 'withdrawal_mirror_failed';
/** A Git or withdrawal target parks after this many consecutive execution failures. */
export const PARK_AFTER_FAILURES = 5;
+ /**
+ * A withdrawal mirror's recovery record. Version 1 embeds the mirrored file (`after`, base64). Version 2 is a segmented
+ * page's file, never held whole: `after` is null and `staging.publication` names the file streamed from the page's
+ * segments by path, SHA-256 (`afterHash`) and length, written once the record is durable (effect-recovery.ts).
+ */
export interface EffectRecovery {
- version: 1;
+ version: 1 | 2;
kind: 'withdrawal-mirror';
path: string;
root: string;
diff --cc src/core/persistence/effect-recovery.ts
index 0f51cd2e1f,bc4b068589..ee1a3da732
--- a/src/core/persistence/effect-recovery.ts
+++ b/src/core/persistence/effect-recovery.ts
@@@ -6,11 -6,8 +6,11 @@@ import { readFix } from '../ops/op-fix.
import type { Action } from '../agent-output.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { materializePageSnapshot } from '../page-state/materialize.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
import type { JournalLimits } from './model.ts';
- import { readJournalLimits } from './limits.ts';
+ import { journalLimitKey, readJournalLimits } from './limits.ts';
import { lockCounters } from './journal.ts';
import { digest, sha256 } from './digest.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
@@@ -18,7 -15,10 +18,9 @@@ import { withFilesystemPublication } fr
import { persistenceFileHash, publishPersistenceFile } from './coordinator.ts';
import type { EffectRecovery, PersistenceEffect } from './effect-model.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
- import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFile, upgradeRecoveryStaging } from './staging.ts';
-import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, discardStreamingStage, publishStreamedStage, upgradeRecoveryStaging } from './staging.ts';
++import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, discardStreamingStage, publishStreamedStage, recoveryStagingFile, upgradeRecoveryStaging } from './staging.ts';
+ import { existsAt, stageStreamedContent, streamingStagePath, type StreamedFileContent } from './large-file.ts';
+ import { unreadPageFile } from './page-prepare.ts';
-import { isSegmentedPage } from '../page-body/page-shape.ts';
import { declarePersistenceProtocol } from './protocol.ts';
import { advanceEffectCursor } from './effect-journal.ts';
import { faultPoint } from './fault-points.ts';
@@@ -100,56 -100,84 +102,131 @@@ async function clearRecovery(tx: BrainE
await tx.executeRaw('UPDATE persistence_effects SET recovery=NULL,recovery_bytes=0 WHERE id=$1', [effect.id]);
}
+/** The bytes a withdrawal mirror writes for a page: its current markdown rendering (callers skip or refuse a segmented page first). */
+export function mirrorContent(snapshot: PageSnapshot): string {
+ return serializePageToMarkdown(snapshot.page, snapshot.tags);
+}
+
+/**
+ * Under the native lock, before anything publishes a stuck withdrawal-mirror record's `after` bytes (`gbrain repair
+ * stuck-recovery --keep withdrawn`): when the page moved past the record (a later withdrawal committed), the recorded bytes
+ * would put that withdrawal's fact back on disk, so the record is rebased on the latest snapshot under its page lock: `after`
+ * becomes the bytes `mirrorPage` renders for it, `pageId`/`revision` follow the snapshot, and the publication stage and
+ * reserved recovery bytes grow to fit the new bytes (`queue_capacity` when they do not). `persist` runs in the same
+ * transaction. Returns the current record (unchanged when it was not stale), null when it holds none, or 'unrenderable'
+ * when the page was deleted, replaced or segmented, so there are no current bytes to write.
+ */
+export async function rebaseStaleEffectRecovery(engine: BrainEngine, effectId: string | number, hostId: string,
+ persist: (tx: BrainEngine, record: EffectRecovery) => Promise<void>): Promise<EffectRecovery | null | 'unrenderable'> {
+ const [effect] = await engine.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1', [effectId]);
+ if (!effect?.recovery) return null;
+ const limits = await readJournalLimits(engine);
+ return engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
+ await guardEffectSource(tx, effect, hostId);
+ const counters = await lockCounters(tx, ['brain', `worktree:${effect.worktree_id}`]);
+ const [current] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [effectId]);
+ const record = current?.recovery;
+ if (!record) return null;
+ await tx.lockPageKeys([{ sourceId: current.source_id, slug: record.slug }]);
+ const snapshot = await tx.readPageSnapshot(record.slug, { sourceId: current.source_id, includeDeleted: true });
+ if (snapshot?.page.id === record.pageId && snapshot.revision === record.revision) return record;
+ if (!snapshot || snapshot.page.id !== record.pageId || snapshot.page.deleted_at || isSegmentedPage(snapshot.page)) return 'unrenderable';
+ const after = Buffer.from(mirrorContent(snapshot));
- const rebased: EffectRecovery = { ...record, after: after.toString('base64'), afterHash: sha256(after), revision: snapshot.revision,
++ const rebased: EffectRecovery = { ...record, version: 1, after: after.toString('base64'), afterHash: sha256(after), revision: snapshot.revision,
+ staging: { publication: recoveryStagingFile(record.path, after) } };
+ const extra = Math.max(0, Buffer.byteLength(JSON.stringify(rebased)) * 2 + 4096 - Number(current.recovery_bytes));
+ for (const counter of counters) if (Number(counter.recovery_bytes) + extra > (counter.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes)) {
+ throw opError('queue_capacity', 'Other publications hold the recovery capacity the current mirror bytes need.',
+ `Page ${record.slug} in source ${current.source_id} changed after its withdrawal mirror stopped, and writing its current version needs ${extra} more bytes of recovery space than other publications leave free, so nothing was written. Run the same apply again once they finish.`,
+ { fix: effectStatusFix(current) });
+ }
+ await withFilesystemPublication([record.root], async () => cleanupRecoveryStaging(record));
+ await tx.executeRaw('UPDATE persistence_effects SET recovery=$2::text::jsonb,recovery_bytes=recovery_bytes+$3,updated_at=now() WHERE id=$1', [current.id, JSON.stringify(rebased), extra]);
+ for (const counter of counters) await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes+$2 WHERE key=$1', [counter.key, extra]);
+ await persist(tx, rebased);
+ return rebased;
+ });
+}
+
+ /** Whether a mirror record belongs to the effect's current canonical binding (owner epoch, root and file path). */
+ function recordBelongs(record: EffectRecovery, effect: PersistenceEffect, binding: WorktreeBinding | null): binding is WorktreeBinding & { local_path: string } {
+ return !!binding?.local_path && record.kind === 'withdrawal-mirror' && record.sourceIncarnation === effect.source_incarnation
+ && String(binding.owner_epoch) === record.ownerEpoch && isWriteTargetContained(record.path, binding.local_path)
+ && isWriteTargetContained(record.path, record.root) && isWriteTargetContained(record.root, binding.local_path)
+ && resolve(record.root) === resolve(join(binding.local_path, binding.relative_path));
+ }
+
+ /**
+ * A version 2 record's publication stage (effect-model.ts) is written before the recovery transaction, as a streamed
+ * publication's is (coordinator.ts `stageLargeFiles`), one piece at a time: from `content`, the file the effect measured,
+ * or after a crash from the page's segments at the recorded revision (`unreadPageFile`). Nothing is staged when the file
+ * no longer holds its prior bytes, a leaf already holds the stage's name (the transaction verifies or refuses it), the
+ * record no longer belongs to the binding (the transaction refuses it) or the page moved on (the transaction clears it).
+ */
+ async function stageStreamedMirror(engine: BrainEngine, effect: PersistenceEffect, hostId: string, content?: StreamedFileContent,
+ between?: () => Promise<void>): Promise<void> {
+ const [row] = await engine.executeRaw<{ recovery: EffectRecovery | null }>(
+ 'SELECT recovery FROM persistence_effects WHERE id=$1 AND execution_token=$2::uuid', [effect.id, effect.execution_token]);
+ const record = row?.recovery;
+ const stage = record?.version === 2 ? record.staging?.publication : undefined;
+ if (!record || !stage || !recordBelongs(record, effect, await getWorktreeBinding(engine, effect.source_id, hostId))) return;
+ const detail = { effectId: effect.id, requestId: effect.request_id, sourceId: effect.source_id, slug: record.slug, path: stage.path };
+ await faultPoint('effect_recovery:before_stage', detail);
+ try { await withFilesystemPublication([record.root], async () => {
+ // A stream a crash cut short is still under its in-progress name; it is discarded and the stage produced again.
+ discardStreamingStage(record);
+ if (existsAt(stage.path) || record.beforeHash === record.afterHash || persistenceFileHash(record.path) !== record.beforeHash) return;
+ let file = content;
+ if (!file) {
+ const snapshot = await engine.readPageSnapshot(record.slug, { sourceId: effect.source_id, includeDeleted: true });
+ if (!snapshot || snapshot.page.id !== record.pageId || snapshot.revision !== record.revision) return;
+ file = await unreadPageFile(engine, snapshot, between);
+ }
+ await stageStreamedContent(engine, record.path, file, stage, record.mode);
+ }); } catch (error) {
+ if (stagingReported(error)) await releaseUnstagedRecord(engine, effect, hostId, record).catch(() => undefined);
+ throw error;
+ }
+ await faultPoint('effect_recovery:staged', detail);
+ }
+
+ /**
+ * The stage write ended with an error this process saw (a filesystem error such as EIO or ENOSPC, or a gbrain refusal),
+ * not with its death: the writer removed its in-progress file, so nothing of the stage is on disk.
+ */
+ function stagingReported(error: unknown): boolean {
+ if (error instanceof OperationError) return true;
+ const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };
+ return typeof code === 'string' && typeof syscall === 'string';
+ }
+
+ /**
+ * A version 2 record whose stage could not be written while the canonical file still holds its prior bytes protects
+ * nothing: no file changed and no stage, whole or in progress, exists. It is cleared with its reserved capacity in one
+ * transaction, so the worktree's other writes and effects are no longer held behind it and this effect retries (and
+ * parks) as any failed mirror does. A record whose file moved, or whose stage or in-progress stream is still on disk
+ * (the writer could not remove it), is kept for recovery, as it is when the release itself fails (the staging error is
+ * the one reported).
+ */
+ async function releaseUnstagedRecord(engine: BrainEngine, effect: PersistenceEffect, hostId: string, record: EffectRecovery): Promise<void> {
+ const stage = record.staging?.publication;
+ if (!stage || existsAt(stage.path) || existsAt(streamingStagePath(stage.path)) || persistenceFileHash(record.path) !== record.beforeHash) return;
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
+ await guardEffectSource(tx, effect, hostId);
+ await lockCounters(tx, ['brain', `worktree:${effect.worktree_id}`]);
+ const current = await lockedEffect(tx, effect);
+ if (digest(current.recovery) !== digest(record)) return;
+ await clearRecovery(tx, current);
+ });
+ }
+
/** Under the native lock: finish forward, never restore withdrawn bytes. */
export async function recoverEffectPublication(engine: BrainEngine, effect: PersistenceEffect, hostId: string,
- hooks: { boundary?: (name: 'before_mirror_file' | 'after_mirror_file' | 'before_mirror_commit') => Promise<void> } = {}): Promise<void> {
+ hooks: { boundary?: (name: 'before_mirror_file' | 'after_mirror_file' | 'before_mirror_commit') => Promise<void>; content?: StreamedFileContent;
+ /** Called between the pieces of a streamed stage (the effect's claim renewal). */
+ between?: () => Promise<void> } = {}): Promise<void> {
const releaseCapacity = tryAcquirePublicationCapacity(engine);
if (!releaseCapacity) throw opError('writer_pool_capacity', 'Mirror recovery is waiting for publication capacity.',
`Every publication slot of the writer pool is busy, so mirror recovery for source ${effect.source_id} has not started; the worker tries again once a slot frees. Nothing needs resubmitting.`,
@@@ -195,14 -227,12 +276,15 @@@
});
await hooks.boundary?.('after_mirror_file');
}
- await materializePageSnapshot(tx, snapshot);
+ // A segmented page's withdrawn rows were struck in its segments when the withdrawal committed: nothing to persist.
+ if (!isSegmentedPage(snapshot.page)) await materializePageSnapshot(tx, snapshot);
await clearRecovery(tx, current);
+ // GBRA-130 A-12: the page's file now holds the mirrored bytes; Git may commit only pages recorded here.
+ const published = [...new Set([...(current.data.published ?? []), record.slug])];
+ await tx.executeRaw(`UPDATE persistence_effects SET data=jsonb_set(data,'{published}',$2::text::jsonb) WHERE id=$1`, [current.id, JSON.stringify(published)]);
// One page per transaction/cursor checkpoint bounds work and restart cost;
// a retried parked target is consumed without rewinding the cursor.
- await advanceEffectCursor(tx, current, record.slug);
+ await advanceEffectCursor(tx, { ...current, data: { ...current.data, published } }, record.slug);
await hooks.boundary?.('before_mirror_commit');
}); } finally { releaseCapacity(); }
}
diff --cc src/core/persistence/effects.ts
index 79a76aafbd,ade3b71455..d5f2359b24
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@@ -32,10 -32,12 +32,12 @@@ import type { ResolvedColumn } from '..
import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { persistenceFileHash, transientDatabaseFailure } from './coordinator.ts';
import { sha256 } from './digest.ts';
- import { prepareFileTarget } from './page-prepare.ts';
+ import { prepareFileTarget, unreadPageFile } from './page-prepare.ts';
+ import { isStreamedContent, type StreamedFileContent } from './large-file.ts';
+ import { atomicStagingPath } from '../atomic-write.ts';
import { isSourceDbOnlySlug } from './source-storage.ts';
- import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, failEffect, hasRearmableTargets, mirrorGates, parkEffect, rearmWithheldTargets, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect, type MirrorGate } from './effect-journal.ts';
- import { guardEffectSource, mirrorContent, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';
-import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, effectClaimKeeper, failEffect, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect } from './effect-journal.ts';
++import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, effectClaimKeeper, failEffect, hasRearmableTargets, mirrorGates, parkEffect, rearmWithheldTargets, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect, type MirrorGate } from './effect-journal.ts';
+ import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';
import { commitGitTargets, DURABILITY_NOT_ENABLED, publishGitEffect, pushGitRoot, type GitEffectOwner } from './effect-git.ts';
import { retryIndexLockParks } from './effect-retry.ts';
import { gitDurabilityPolicy } from './git-durability-policy.ts';
@@@ -306,15 -280,16 +324,18 @@@ async function publishGitPage(engine: B
const snapshot = await selectedEffectPage(engine, effect);
if (!snapshot) { await completeEffect(engine, effect); return; }
attempt.target = snapshot.page.slug;
+ const verdict = await mirrorVerdict(engine, effect, attempt, snapshot.page.slug);
+ if (verdict === 'handled') return;
if (isMetafilePage(snapshot)) { await skipTarget(engine, effect, snapshot, 'metafile'); return; }
- if (isSegmentedPage(snapshot.page)) { await skipTarget(engine, effect, snapshot, 'page_body_segmented'); return; }
- const content = snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags);
++ const keep = effectClaimKeeper(engine, effect, effectRenewalIntervalMs);
++ const content = snapshot.page.deleted_at || isSegmentedPage(snapshot.page) ? null : serializePageToMarkdown(snapshot.page, snapshot.tags);
let file: Awaited<ReturnType<typeof prepareFileTarget>>;
try {
- file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true });
+ // Only the file's comparison with the stored page is needed here, so a segmented page's file is never rendered.
- file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,
- snapshot.page.deleted_at || isSegmentedPage(snapshot.page) ? null : serializePageToMarkdown(snapshot.page, snapshot.tags),
- opts.hostId, { allowMissing: true, between: effectClaimKeeper(engine, effect, effectRenewalIntervalMs) });
++ file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true, between: keep });
} catch (error) {
+ // A segmented page whose fence a withdrawal cannot read whole (page_body_segmented) retries and parks like any failed
+ // target, so writer status and doctor list it; only a file that differs from the database is passed by.
if (!isFileDatabaseDrift(error)) throw error;
await skipTarget(engine, effect, snapshot, 'file_database_drift');
return;
@@@ -330,11 -305,6 +351,13 @@@
await finishPage(engine, effect, snapshot, { git: 'skipped', reason: 'db_only' });
return;
}
+ // A page the mirror passed is committed only when its raw bytes are the mirror's rendering of the page as it is now.
- if (verdict === 'evidence' && (content === null || persistenceFileHash(path) !== fileContentHash(content))) {
++ // A segmented page's rendering is measured from its segments (unreadPageFile), never held as one string.
++ if (verdict === 'evidence' && (snapshot.page.deleted_at
++ || persistenceFileHash(path) !== (content === null ? (await unreadPageFile(engine, snapshot, keep)).hash : fileContentHash(content)))) {
+ await skipTarget(engine, effect, snapshot, 'withdrawal_not_mirrored');
+ return;
+ }
const result = await publishGitEffect(root, relative(root, path).split(sep).join('/'), opts.signal, hardened, gitCommitNote(effect), undefined, owner);
if (result.reason === 'durability_not_enabled') await completeEffect(engine, effect, result);
else await finishPage(engine, effect, snapshot, result);
@@@ -677,23 -585,6 +700,23 @@@ const GIT_GROUP_SIZE = 100
const GIT_YIELD_ATTEMPTS = 20;
const GIT_YIELD_MS = 250;
+/**
+ * Claims one effect recovery and finishes it forward (`recoverEffectPublication`); a failure is recorded on the effect,
+ * whose record stays. The caller holds the worktree's native lock: any old process holding it has exited, so no lease
+ * timeout is needed and no second process can steal this claim. Returns the claimed row, or undefined when the effect
+ * no longer holds a recovery record.
+ */
+export async function claimAndRecoverEffect(engine: BrainEngine, id: string | number, hostId: string,
+ hooks: Parameters<typeof recoverEffectPublication>[3] = {}): Promise<PersistenceEffect | undefined> {
+ let claimed: PersistenceEffect | undefined;
+ try {
+ [claimed] = await engine.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,
+ claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 AND recovery IS NOT NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [id, randomUUID()]);
- if (claimed) await recoverEffectPublication(engine, claimed, hostId, hooks);
++ if (claimed) await recoverEffectPublication(engine, claimed, hostId, { ...hooks, between: hooks.between ?? effectClaimKeeper(engine, claimed, effectRenewalIntervalMs) });
+ } catch (error) { if (claimed) await recordFailure(engine, claimed, error); }
+ return claimed;
+}
+
/**
* Bounded, idempotent work. Recovery obtains kernel exclusion before a DB claim.
* Resolves with the number of effects attempted, so a caller can keep draining.
@@@ -721,10 -606,18 +744,10 @@@ async function runEffectPass(engine: Br
if (!binding) continue;
const lock = await acquireWorktree(binding, 0, undefined, engine);
if (!lock) continue;
- let claimed: PersistenceEffect | undefined;
try {
- const claimed = await claimAndRecoverEffect(engine, recovery.id, opts.hostId, opts);
- // Any old process holding this native lock has exited. No lease timeout
- // can provide that proof and no second process can steal this claim now.
- [claimed] = await engine.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,
- claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 AND recovery IS NOT NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [recovery.id, randomUUID()]);
- if (claimed) {
- attempted++; touched.add(claimed.request_id);
- await recoverEffectPublication(engine, claimed, opts.hostId, { boundary: opts.boundary, between: effectClaimKeeper(engine, claimed, effectRenewalIntervalMs) });
- }
- } catch (error) { if (claimed) await recordFailure(engine, claimed, error); }
- finally { await lock.release(); }
++ const claimed = await claimAndRecoverEffect(engine, recovery.id, opts.hostId, { boundary: opts.boundary });
+ if (claimed) { attempted++; touched.add(claimed.request_id); }
+ } finally { await lock.release(); }
}
const run = async (claimed: PersistenceEffect, binding: WorktreeBinding | null, hardened?: boolean) => {
let effect = claimed;
diff --cc src/core/persistence/recovery-resolve.ts
index 9f4f3a6b92,cf01139f05..39f0f0e6cb
--- a/src/core/persistence/recovery-resolve.ts
+++ b/src/core/persistence/recovery-resolve.ts
@@@ -14,43 -13,37 +14,50 @@@
* committed bytes. `--keep prior` writes the prior bytes back through the coordinator's confined durable publication
* (`publishPersistenceFile`, staged at the record's reserved restoration path, which `upgradeRecoveryStaging` reserves
* and accounts for older records) and recovery finishes by its own rule (a request with no recorded failure is requeued
- * and its write publishes again; one with a failure ends terminal). `--keep disk` (#6640's `drop`) keeps the edited
- * bytes and abandons the publication: it completes the request terminal (`completeWrite`; `source_changed`, so
- * `conflict`, when it recorded no failure, else that failure by the owner's rule via `finishUnpublishedFailure`), and
- * recovery's terminal path then only cleans its staging and clears the record (`clearResolvedRecovery`), releasing its
- * reserved bytes. The record is never rewritten, so no recovery bytes move outside the accounting.
+ * and its write publishes again; one with a failure ends terminal; recovery restores every other file of a bundle).
+ * `--keep disk` (#6640's `drop`) keeps the bytes on disk (every file of a bundle) and abandons the publication: it
+ * completes the request terminal (`completeWrite`; `source_changed`, so `conflict`, when it recorded no failure, else
+ * that failure by the owner's rule via `finishUnpublishedFailure`), and recovery's terminal path then only cleans its
+ * staging and clears the record (`clearResolvedRecovery`), releasing its reserved bytes. The record is never rewritten,
+ * so no recovery bytes move outside the accounting.
* A terminal request whose recovery record is still set is refused (`recovery_choice_refused`): its outcome is immutable,
- * recovery never restores its canonical file, and `--keep prior` would roll back a committed write. 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 a bundle record this binary cannot read (`recovery_bundle_unsupported`).
- * 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.
++ * recovery never restores its canonical file, and `--keep prior` would roll back a committed write. So is a bundle
++ * record this binary cannot read (`recovery_bundle_unsupported`).
+ *
+ * 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.
*
+ * A withdrawal-mirror effect only finishes forward: its withdrawal is committed, and keeping the edited file (or the
+ * pre-withdrawal bytes) would leave the forgotten fact on disk for the next sync to import again. Its only choice is
+ * `--keep withdrawn`: the edited bytes are backed up, the recorded post-withdrawal bytes are written through the
+ * record's reserved publication stage, and the effect's own `recoverEffectPublication` finishes it. When a later
+ * withdrawal moved the page past the record, its bytes would put that fact back on disk, so before anything is written
+ * `rebaseStaleEffectRecovery` rebases the record under its page lock on the latest snapshot's rendering (the bytes the
+ * mirror itself writes) and the journal records the rebased identity, so a rerun after any interruption resumes it; a
+ * page deleted, replaced or segmented meanwhile has no current bytes and is refused (`recovery_effect_unsupported`). A record without
- * usable post-withdrawal bytes (or bound to another owner, root or incarnation) stays refused
- * (`recovery_effect_unsupported`) with an ask_user fix naming the exact preview.
++ * usable post-withdrawal bytes (a streamed version 2 record of a segmented page embeds none) or bound to another owner,
++ * root or incarnation stays refused (`recovery_effect_unsupported`) with an ask_user fix naming the exact preview.
+ *
* The apply runs on the owner host under the worktree lock, so the resident recovery pass cannot interleave. Each
- * record moves through a journal (`op_checkpoints`, op `stuck-recovery-resolution`, keyed by request and preview
- * hash): `backed_up` (the disk and prior bytes are in the backup directory, always), then `written` (`--keep
- * prior`: the prior bytes are back on disk, an absent prior unlinked) or `abandoned` (`--keep disk`: the request is
- * terminal), then `done` once `recoverPublication` finished it by its unchanged rule. Every step is idempotent, so a
- * run killed at any boundary resumes, and an older resident consumer can finish a resolution this command started.
- * The finished journal row is the resolution's audit entry; a terminal receipt is never rewritten.
+ * record moves through a journal (`op_checkpoints`, op `stuck-recovery-resolution`, keyed by record and preview
+ * hash): `backed_up` (the disk and recorded bytes are in the backup directory, always), then `written` (`--keep
+ * prior`: the prior bytes are back on disk, an absent prior unlinked; `--keep withdrawn`: the withdrawn bytes are on
+ * disk) or `abandoned` (`--keep disk`: the request is terminal), then `done` once the owner's recovery finished it by
+ * its unchanged rule. Every step is idempotent, so a run killed at any boundary resumes, and an older resident consumer
+ * can finish a resolution this command started. The finished journal row is the resolution's audit entry; a terminal
+ * receipt is never rewritten.
*/
- import { chmodSync, 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 { chmodSync, closeSync, constants, copyFileSync, existsSync, fchmodSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
+import { dirname, join, relative, resolve } from 'node:path';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
+import type { Action } from '../agent-output.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { catalogueError } from '../error-catalogue.ts';
@@@ -64,16 -57,12 +71,17 @@@ import { localHostId } from './identity
import { acquireWorktree, containsPath, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { completeWrite, getWriteRequestById } from './journal.ts';
-import { isTerminal, recoveryFiles, type FileRecoveryRecord, type WriteRequest } from './model.ts';
+import { isTerminal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';
+import type { EffectRecovery } from './effect-model.ts';
import { finishUnpublishedFailure, publishPersistenceFile, recoverPublication, transientDatabaseFailure } from './coordinator.ts';
+import { claimAndRecoverEffect } from './effects.ts';
+import { rebaseStaleEffectRecovery } from './effect-recovery.ts';
+import { trueUpRequests } from './receipt-true-up.ts';
+import { bundleFileHash } from './bundle-files.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';
@@@ -81,21 -70,24 +89,29 @@@ import { faultPoint } from './fault-poi
import { KEEP_DISK_ABANDONED_PREFIX } from './verb-errors.ts';
export const RESOLUTION_OP = 'stuck-recovery-resolution';
-export type KeepChoice = 'prior' | 'disk';
+export type KeepChoice = 'prior' | 'disk' | 'withdrawn';
+export const KEEP_CHOICES: readonly KeepChoice[] = ['prior', 'disk', 'withdrawn'];
+/** What the record publishes: one page file, every file of a shared-skill bundle, or a withdrawal mirror of a page file. */
+export type RecoveryTarget = 'page' | 'skill_bundle' | 'withdrawal_mirror';
- 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;
/** What recovery itself makes of the disk bytes: the prior, the published bytes, or neither (the blocked case). */
matches: 'prior' | 'published' | 'neither';
+ /** A withdrawal-mirror effect only: the recorded post-withdrawal bytes `--keep withdrawn` writes (`prior` is the pre-withdrawal file). */
+ withdrawn?: { sha256: string; size: number };
/** 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 }> }
@@@ -111,14 -101,9 +127,11 @@@ 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, an unusable withdrawal-mirror effect or bundle record, 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' | 'recovery_bundle_unsupported';
-/** 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 }
++/** A blocked terminal request, or an unusable withdrawal-mirror effect or bundle record: listed, never resolved (see the module comment). */
++export interface RefusedRecovery { code: 'recovery_choice_refused' | 'recovery_effect_unsupported' | 'recovery_bundle_unsupported';
+ request_id: string; source_id: string; slug: string; state: string; blocked_reason: string | null; reason: string; effect_id?: string;
+ /** The next step when it is not the read-only writer status: an ask_user action naming the exact preview. */
+ fix?: Action }
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 }> }
@@@ -133,10 -116,6 +146,8 @@@ export interface ResolutionResult
outcome: 'resolved' | 'still_blocked'; keep: KeepChoice; request_state: string; blocked_reason: string | null;
finished_by: 'this_run' | 'another_pass'; backup_dir: string; next: string;
}
+interface EffectRow { id: string; request_ref: string; request_id: string | null; kind: string; state: string; error_code: string | null; worktree_id: string;
+ recovery: EffectRecovery | null }
- /** What `writeArtifacts` compares each disk file against: the recorded prior bytes, or a mirror's withdrawn bytes. */
- type Reference = { label: 'prior' | 'withdrawn'; bytes: Buffer | null };
const statusFix = (sourceId: string) => readFix(`Shows source ${sourceId}'s canonical owner with its recovering write requests, read-only.`,
{ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
@@@ -149,26 -127,47 +160,55 @@@ const fileMode = (mode: number) => mod
function identityOf(files: FileRecoveryRecord[], record: { attempt: string; ownerEpoch: string }): RecoveryIdentity {
return { attempt: record.attempt, owner_epoch: String(record.ownerEpoch), files: files.map(file => ({ path: file.path, after_hash: file.afterHash })) };
}
+function effectIdentity(effectId: string, record: EffectRecovery): RecoveryIdentity {
+ return { attempt: `effect:${effectId}:${record.revision}`, owner_epoch: String(record.ownerEpoch), files: [{ path: record.path, after_hash: record.afterHash }] };
+}
+/** The record's files, or null for a bundle record this binary cannot read. */
+function filesOf(record: RecoveryRecord): FileRecoveryRecord[] | null {
+ try { return recoveryFiles(record); } catch { return null; }
+}
- 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 } };
}
+const diskHash = (view: DiskView) => view.deleted ? null : view.sha256;
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 };
}
@@@ -204,97 -209,142 +250,192 @@@ function writePrivateFile(path: string
`Nothing was changed on disk or in the journal. Check free space and the filesystem under ${dirname(path)}, then run the same command again.`);
}
- /** Each file's recorded and disk bytes (and their diff) under `dir`; returns the diff paths by file index. */
- function writeArtifacts(dir: string, files: RecoveryFileView[], references: Reference[], disks: Array<Buffer | null>) {
- return files.map((file, index) => {
- const { label, bytes } = references[index]!;
- const referencePath = bytes === null ? null : join(dir, `${index}.${label}`);
- const diskPath = disks[index] === null ? null : join(dir, `${index}.disk`);
- if (referencePath) writePrivateFile(referencePath, bytes!);
- if (diskPath) writePrivateFile(diskPath, disks[index]!);
+ /**
+ * 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 label = file.withdrawn ? 'withdrawn' : 'prior';
++ const reference = file.withdrawn ?? (file.prior.absent ? null : { sha256: file.prior.sha256, size: file.prior.size });
+ 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(`--- ${label}/${file.relative}`, reference ? { sha256: reference.sha256, size: prior?.length ?? reference.size } : null),
+ 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 @@`,
++ `@@ bytes ${start}..${offset + removed.length} of ${label}, ${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
++ * Both versions of every file (and their diff) under `dir`; returns the paths by file index. The recorded side is the
++ * prior (`<index>.prior`), or a withdrawal mirror's withdrawn bytes (`<index>.withdrawn`). 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, 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 label = file.withdrawn ? 'withdrawn' : 'prior';
++ const priorPath = prior === null ? null : join(dir, `${index}.${label}`);
+ const diskPath = disk === null ? null : join(dir, `${index}.disk`);
- if (priorPath) keep(priorPath, prior!, file.prior.absent ? null : file.prior.sha256);
++ if (priorPath) keep(priorPath, prior!, file.withdrawn?.sha256 ?? (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(bytes?.toString('utf8') ?? '', disks[index]?.toString('utf8') ?? '',
- { oldPath: `${label}/${file.relative}`, newPath: `disk/${file.relative}` })));
- return { diff_path: diffPath, diff_command: `diff -u ${referencePath ?? '/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}` })));
++ { oldPath: `${label}/${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 };
});
}
- const priorReferences = (records: FileRecoveryRecord[]): Reference[] => records.map(record => ({ label: 'prior', bytes: priorBytes(record) }));
-/** One record's current view: its files with disk fingerprints, the page revision and the state digest. */
+/** What recovery makes of a file's disk bytes; a bundle file also needs its recorded mode and a regular, unaliased file. */
+function recoveryMatch(record: FileRecoveryRecord, view: DiskView, bundle: boolean): RecoveryFileView['matches'] {
+ if (!view.deleted && view.kind !== 'file') return 'neither';
+ const hash = diskHash(view);
+ const match = hash === record.beforeHash ? 'prior' : hash === record.afterHash ? 'published' : 'neither';
+ if (match === 'neither' || !bundle) return match;
+ try { bundleFileHash(record); return match; } catch (error) {
+ if (error instanceof OperationError && ['unexpected_file_bytes', 'storage_error'].includes(error.code)) return 'neither';
+ throw error;
+ }
+}
+
+/** One page or bundle record's current view: its files with disk fingerprints, the page revision and the state digest. */
- async function readItem(engine: BrainEngine, row: WriteRequest, binding: WorktreeBinding): Promise<{ item: StuckRecovery; records: FileRecoveryRecord[]; disks: Array<Buffer | null> }> {
- if (row.recovery?.version === 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.`);
+ 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.`);
- const records = recoveryFiles(row.recovery!);
+ const records = filesOf(row.recovery!);
+ if (!records) throw refusalError(bundleRefusal(row));
+ const bundle = row.recovery!.version === 2;
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);
- return { path: record.path, root: record.root, relative: relative(binding.local_path ?? record.root, record.path), prior: priorView(record), disk: view,
+ 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, 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: recoveryMatch(record, view, bundle) } 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), withdrawn: false };
- const choices = { prior: unexpected.every(file => writable(file) && (file.prior.absent || file.prior.stored)), disk: unexpected.every(file => writable(file) && stageRemovable(file)) };
++ const choices = { prior: unexpected.every(file => writable(file) && (file.prior.absent || file.prior.stored)), disk: unexpected.every(file => writable(file) && stageRemovable(file)), withdrawn: false };
const identity = identityOf(records, row.recovery!);
const page_revision = page?.revision ?? null;
- return { records, disks, item: { id: row.id, target: bundle ? 'skill_bundle' : 'page', 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,
++ return { records, sources, item: { id: row.id, target: bundle ? 'skill_bundle' : 'page', 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 } : {}) }) } };
}
+const EFFECT_SQL = `SELECT e.id::text AS id, e.request_id::text AS request_ref, r.request_id::text AS request_id, e.kind, e.state, e.error_code,
+ e.worktree_id::text AS worktree_id, e.recovery FROM persistence_effects e LEFT JOIN persistence_requests r ON r.id=e.request_id`;
+
+/**
+ * One withdrawal-mirror effect recovery's view: null when its file holds a recorded version (it recovers on its own),
+ * a refusal when the record cannot be written forward on this binding, else the item with its withdrawn and disk bytes.
+ */
+async function readEffectItem(engine: BrainEngine, effect: EffectRow, binding: WorktreeBinding, sourceId: string):
- Promise<{ item: StuckRecovery; reference: Buffer; disk: Buffer | null } | RefusedRecovery | null> {
++Promise<{ item: StuckRecovery; sources: Array<{ prior: Bytes; disk: Bytes }> } | RefusedRecovery | null> {
+ const record = effect.recovery;
+ const slug = typeof record?.slug === 'string' ? record.slug : '';
+ const refused: RefusedRecovery = { code: 'recovery_effect_unsupported', request_id: effect.request_id ?? '', effect_id: effect.id, source_id: sourceId, slug,
+ state: effect.state, blocked_reason: effect.error_code, reason: effectReason(effect.kind), fix: effectFix(sourceId, effect.request_id) };
- if (!record || effect.kind !== 'withdrawal-mirror' || record.kind !== 'withdrawal-mirror' || typeof record.after !== 'string' || typeof record.afterHash !== 'string'
++ if (!record || effect.kind !== 'withdrawal-mirror' || record.kind !== 'withdrawal-mirror' || record.version !== 1 || typeof record.after !== 'string' || typeof record.afterHash !== 'string'
+ || typeof record.path !== 'string' || typeof record.root !== 'string' || !binding.local_path) return refused;
+ const after = Buffer.from(record.after, 'base64');
+ if (sha256(after) !== record.afterHash || record.ownerEpoch !== String(binding.owner_epoch) || record.sourceIncarnation !== binding.source_incarnation
+ || !isWriteTargetContained(record.path, record.root) || !isWriteTargetContained(record.path, binding.local_path)
+ || resolve(record.root) !== resolve(join(binding.local_path, binding.relative_path))) return refused;
- const { view, bytes } = diskView(record.path);
++ const { view, source } = diskView(record.path);
+ const regular = !view.deleted && view.kind === 'file';
+ if (regular && (diskHash(view) === record.beforeHash || diskHash(view) === record.afterHash)) return null;
+ const [page] = await engine.executeRaw<{ revision: string | null }>('SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ const identity = effectIdentity(effect.id, record);
+ const page_revision = page?.revision ?? null;
+ const file: RecoveryFileView = { path: record.path, root: record.root, relative: relative(binding.local_path, record.path),
+ prior: record.beforeHash === null ? { absent: true } : { absent: false, sha256: record.beforeHash, size: null, mode: record.mode, stored: false },
+ disk: view, matches: 'neither', withdrawn: { sha256: record.afterHash, size: after.length } };
- return { reference: after, disk: bytes, item: { id: `effect:${effect.id}`, target: 'withdrawal_mirror', effect_id: effect.id, request_id: effect.request_id ?? '',
++ return { sources: [{ prior: { bytes: after }, disk: source }], item: { id: `effect:${effect.id}`, target: 'withdrawal_mirror', effect_id: effect.id, request_id: effect.request_id ?? '',
+ source_id: sourceId, slug, operation: 'withdrawal-mirror', state: effect.state, blocked_reason: effect.error_code, worktree_id: effect.worktree_id,
+ sequence: effect.id, page_revision, identity, recorded_error: null, prior_hashes: [record.beforeHash], files: [file],
+ choices: { prior: false, disk: false, withdrawn: regular },
+ digest: digest({ v: 'stuck-recovery-effect-v1', id: effect.id, identity, disk: view, page_revision }) } };
+}
+
function ownerBinding(binding: WorktreeBinding | null, sourceId: string, hostId: string): WorktreeBinding {
if (binding?.owner_host_id === hostId && binding.local_path) return binding;
throw opError('owner_unavailable', `Source ${sourceId}'s canonical worktree is not owned by this host, so its recovery files cannot be read or resolved here.`,
@@@ -316,28 -365,20 +457,28 @@@ export async function scanStuckRecoveri
const found = await getWorktreeBinding(engine, sourceId, hostId);
if (!found?.worktree_id) continue;
const rows = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL ORDER BY sequence', [found.worktree_id]);
- const effects = await engine.executeRaw<{ id: string; request_id: string | null; kind: string; state: string; slug: string | null }>(`SELECT e.id::text,r.request_id::text,e.kind,e.state,
- COALESCE(e.recovery->>'slug',r.slug) AS slug FROM persistence_effects e LEFT JOIN persistence_requests r ON r.id=e.request_id
- WHERE e.worktree_id=$1::uuid AND e.recovery IS NOT NULL ORDER BY e.id`, [found.worktree_id]);
+ const effects = await engine.executeRaw<EffectRow>(`${EFFECT_SQL} WHERE e.worktree_id=$1::uuid AND e.recovery IS NOT NULL ORDER BY e.id`, [found.worktree_id]);
+ if (!rows.length && !effects.length) continue;
+ const binding = sourceIds.length === 1 || opts.requestId ? ownerBinding(found, sourceId, hostId) : found.owner_host_id === hostId && found.local_path ? found : null;
+ if (!binding) { residual('owned_by_other_host'); continue; }
for (const effect of effects) {
if (opts.requestId && effect.request_id !== opts.requestId) continue;
- const refused: RefusedRecovery = { code: 'recovery_effect_unsupported', request_id: effect.request_id ?? '', effect_id: effect.id, source_id: sourceId, slug: effect.slug ?? '',
- state: effect.state, blocked_reason: null, reason: effectReason(effect.kind) };
- if (opts.requestId && !rows.some(row => row.request_id === opts.requestId)) throw catalogueError('recovery_effect_unsupported', refused.reason, effectGuidance(sourceId));
- scan.refused.push(refused);
- residual('effect_recovery');
+ const read = await readEffectItem(engine, effect, binding, sourceId);
+ if (!read) { residual('recovers_on_its_own'); continue; }
+ if ('code' in read) {
+ if (opts.requestId) throw refusalError(read);
+ scan.refused.push(read);
+ residual('effect_recovery');
+ continue;
+ }
+ if (opts.artifacts) {
- const paths = writeArtifacts(await privateBackupDir(engine, read.item.request_id || read.item.id, read.item.digest.slice(0, 16)), read.item.files,
- [{ label: 'withdrawn', bytes: read.reference }], [read.disk]);
++ const paths = writeArtifacts(await privateBackupDir(engine, read.item.request_id || read.item.id, read.item.digest.slice(0, 16)), read.item, read.sources,
++ () => opError('source_changed', `A file of withdrawal-mirror effect ${read.item.effect_id} changed while the preview copied it.`, `Nothing was changed. Run the preview again: ${stuckRecoveryPreviewCommand(sourceIds)}`));
+ read.item.files = read.item.files.map((file, index) => ({ ...file, ...paths[index] }));
+ }
+ scan.items.push(read.item);
}
if (!rows.length) continue;
- const binding = sourceIds.length === 1 || opts.requestId ? ownerBinding(found, sourceId, hostId) : found.owner_host_id === hostId && found.local_path ? found : null;
- if (!binding) { residual('owned_by_other_host'); continue; }
const [head] = await engine.executeRaw<{ id: string; request_id: string }>("SELECT id::text, request_id::text FROM persistence_requests WHERE worktree_id=$1::uuid AND state='queued' ORDER BY sequence LIMIT 1", [binding.worktree_id]);
const read = head ? (await readHeadBlockers(engine, [head.id], hostId).catch(() => null))?.get(head.id) : undefined;
const blocker = read?.status === 'blocked' ? read.blocker : null;
@@@ -356,28 -397,11 +497,18 @@@
continue;
}
if (row.blocked_reason === 'unexpected_staging_bytes') { residual('unexpected_staging_bytes'); continue; }
+ if (row.recovery?.version === 2 && !filesOf(row.recovery)) {
+ const refused = bundleRefusal(row);
+ if (opts.requestId) throw refusalError(refused);
+ scan.refused.push(refused);
+ residual('bundle_refused');
+ 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.files, priorReferences(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);
@@@ -393,34 -417,12 +524,31 @@@ function terminalReason(row: WriteReque
+ `--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.';
+ return `A ${kind} effect recovery blocks the worktree, and its record does not hold usable withdrawn bytes for this canonical binding (missing, corrupt, `
+ + 'or recorded for another owner epoch, root or source incarnation), so gbrain repair stuck-recovery cannot write them back; it never restores the bytes from before a withdrawal.';
+}
+const effectFix = (sourceId: string, requestId: string | null): Action => ({ ask_user: true, argv: stuckRecoveryPreviewArgv([sourceId], requestId ?? undefined), consent: [],
+ actor: 'agent', requires_exclusive: false,
+ why: `A withdrawal mirror in source ${sourceId} stopped with its file edited, and its recovery record cannot write the withdrawn version back, so every write on the worktree waits. `
+ + 'The preview (read-only) lists the effect and its file; only the user can decide how the file is put back.',
+ user_message: `A file in source ${sourceId} was edited while gbrain was removing a forgotten fact from it, and gbrain cannot finish that on its own, so writes to the source are paused. `
+ + 'Copy the edited file somewhere safe and put it back to its committed version (do not delete it); gbrain then finishes removing the forgotten fact. Make the edit again afterwards, leaving that fact out.' });
+function bundleRefusal(row: WriteRequest): RefusedRecovery {
+ return { code: 'recovery_bundle_unsupported', request_id: row.request_id, source_id: row.source_id, slug: row.slug, state: row.state, blocked_reason: row.blocked_reason ?? null,
+ reason: `Request ${row.request_id} in source ${row.source_id} holds a shared-skill bundle recovery record this binary cannot read (an unknown shape or more files than a bundle holds).`,
+ fix: { ask_user: true, argv: stuckRecoveryPreviewArgv([row.source_id], row.request_id), consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Shared-skill request ${row.request_id} is stuck in recovery with a record gbrain repair stuck-recovery cannot read, so every write on source ${row.source_id} waits. `
+ + 'The preview (read-only) lists it; which version of each skill file to keep is the user\'s call.',
+ user_message: `A shared-skill publication in source ${row.source_id} is stuck and this gbrain cannot resolve it. Upgrade gbrain on the brain host and run the preview again; `
+ + 'or decide which version of each skill file to keep and put those bytes in place by hand.' } };
+}
+/** A listed refusal as the error a request-id preview throws. */
+function refusalError(refused: RefusedRecovery): OperationError {
+ const error = catalogueError(refused.code, refused.reason, `Nothing was changed. ${refused.fix?.user_message ?? `Inspect it read-only with gbrain sources writer status --source ${refused.source_id} --json.`}`);
+ if (refused.fix) error.fix = refused.fix;
+ return error;
}
-const effectGuidance = (sourceId: string) => `Nothing was changed. Inspect the effect read-only with gbrain sources writer status --source ${sourceId} --json and ask the user `
- + 'whether the edited file may be replaced by its withdrawn version; the resident writer finishes the effect once the file matches one of its recorded versions.';
const choiceRefused = (reason: string, sourceId: string) => catalogueError('recovery_choice_refused', reason,
`Nothing was changed. Inspect the request read-only with gbrain sources writer status --source ${sourceId} --json and follow the guidance for its blocked reason.`);
@@@ -439,6 -441,49 +567,50 @@@ export async function readResolutions(e
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 {
++export function priorStageUnavailable(item: StuckRecovery, keep: KeepChoice, previewHash: string): OperationError | null {
++ if (keep === 'withdrawn') return 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
@@@ -519,12 -544,11 +691,12 @@@ Promise<ResolutionResult & { replayed:
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.'),
+ + (opts.keep === 'prior' ? 'the recovery record does not hold the prior bytes, or a blocked file is not a regular file.'
+ : opts.keep === 'withdrawn' ? 'only a withdrawal-mirror effect recovery has withdrawn bytes to write.' : '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.files, priorReferences(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,
@@@ -572,77 -609,3 +755,80 @@@
return { ...result, replayed: false };
} finally { await lock.release(); }
}
+
+/**
+ * `--keep withdrawn` for a withdrawal-mirror effect recovery: back up the edited bytes, write the recorded
+ * post-withdrawal bytes through the record's publication stage, then finish the effect forward with its own
+ * `recoverEffectPublication` (it materializes the page, clears the record and advances the effect's cursor).
+ */
+async function resolveEffectRecovery(engine: BrainEngine, item: StuckRecovery, opts: { keep: KeepChoice; previewHash: string; hostId?: string; lockWaitMs?: number }):
+Promise<ResolutionResult & { replayed: boolean }> {
+ const hostId = opts.hostId ?? localHostId();
+ const key = `${item.id}:${opts.previewHash}`;
+ const command = stuckRecoveryPreviewCommand([item.source_id], item.request_id || undefined);
+ let journal = await startedJournal(engine, key, item, opts, command);
+ if (journal?.phase === 'done' && journal.result) return { ...journal.result, replayed: true };
+ if (opts.keep !== 'withdrawn') throw catalogueError('recovery_choice_refused', `--keep ${opts.keep} is not available for the withdrawal-mirror effect recovery of request ${item.request_id}: `
+ + 'the withdrawal is committed, and keeping the edited or pre-withdrawal bytes would leave the forgotten fact on disk for the next sync to import again.',
+ `Nothing was changed. The only choice is --keep withdrawn; run the preview again (${command}) and apply its hash with --keep withdrawn after the user agrees.`);
+ const { binding, lock } = await lockOwner(engine, item, hostId, opts.lockWaitMs);
+ try {
+ const read = async () => (await engine.executeRaw<EffectRow>(`${EFFECT_SQL} WHERE e.id=$1`, [item.effect_id]))[0] ?? null;
+ const same = (effect: EffectRow | null) => !!effect?.recovery && digest(effectIdentity(effect.id, effect.recovery)) === digest(journal?.identity ?? item.identity);
+ let effect = await read();
+ if (!journal) {
+ if (!same(effect)) throw previewChangedError(opts.previewHash, command);
+ const current = await readEffectItem(engine, effect!, binding, item.source_id);
+ if (!current || 'code' in current || current.item.digest !== item.digest) throw previewChangedError(opts.previewHash, command);
+ if (!current.item.choices.withdrawn) throw catalogueError('recovery_choice_refused', `--keep withdrawn is not available for request ${item.request_id}: its file is not a regular file.`,
+ `Nothing was changed. Put a regular file back at ${current.item.files[0]!.path} (the backup and the preview diff name the bytes), then preview again (${command}).`);
+ const dir = await privateBackupDir(engine, item.request_id || item.id, item.digest.slice(0, 16));
- writeArtifacts(dir, current.item.files, [{ label: 'withdrawn', bytes: current.reference }], [current.disk]);
++ 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: effect!.state, blocked_reason: effect!.error_code, prior_hashes: item.prior_hashes, disk_hashes: [diskHash(current.item.files[0]!.disk)] } };
+ await writeJournal(engine, key, journal);
+ }
+ if (journal.phase === 'backed_up' && same(effect)) {
+ const now = diskHash(diskView(effect!.recovery!.path).view);
+ if (![journal.original.disk_hashes[0], effect!.recovery!.afterHash].includes(now)) throw changedAgain(item, journal.backup_dir, command);
+ const started: Journal = journal;
+ const rebased = await rebaseStaleEffectRecovery(engine, item.effect_id!, hostId, async (tx, record) => {
+ journal = { ...started, identity: effectIdentity(item.effect_id!, record) };
+ await writeJournal(tx, key, journal);
+ });
+ if (rebased === 'unrenderable') throw catalogueError('recovery_effect_unsupported', `Page ${item.slug} in source ${item.source_id} was deleted, replaced or segmented after its withdrawal mirror stopped, so it has no current version to write.`,
+ `Nothing was written; the edited bytes are backed up under ${started.backup_dir}. ${effectFix(item.source_id, item.request_id || null).user_message}`);
+ await upgradeRecoveryStaging(engine, 'persistence_effects', item.effect_id!, item.worktree_id, 'forward');
+ const record = (await read())!.recovery!;
++ const after = record.version === 1 ? record.after : null;
++ if (after === null) throw catalogueError('recovery_effect_unsupported', effectReason('withdrawal-mirror'),
++ `Nothing was written; the edited bytes are backed up under ${started.backup_dir}. ${effectFix(item.source_id, item.request_id || null).user_message}`);
+ await withFilesystemPublication([record.root], async () => {
+ cleanupRecoveryStaging(record);
- publishPersistenceFile({ path: record.path, root: record.root, content: Buffer.from(record.after, 'base64') }, record.staging?.publication?.path);
++ publishPersistenceFile({ path: record.path, root: record.root, content: Buffer.from(after, 'base64') }, record.staging?.publication?.path);
+ if (record.mode !== null && existsSync(record.path)) chmodSync(record.path, record.mode);
+ });
+ await faultPoint('stuck_recovery:written', { requestId: item.request_id, sourceId: item.source_id });
+ journal = { ...journal, phase: 'written' };
+ await writeJournal(engine, key, journal);
+ effect = await read();
+ }
+ const ours = same(effect);
+ if (ours) {
+ await claimAndRecoverEffect(engine, item.effect_id!, hostId);
+ await trueUpRequests(engine, [effect!.request_ref]).catch(() => { /* idempotent; the request's next settlement retries it */ });
+ }
+ await faultPoint('stuck_recovery:recovered', { requestId: item.request_id, sourceId: item.source_id });
+ const finished = await read();
+ const blocked = same(finished);
+ const result: ResolutionResult = { outcome: blocked ? 'still_blocked' : 'resolved', keep: opts.keep, request_state: finished?.state ?? 'committed',
+ blocked_reason: blocked ? finished!.error_code : null, finished_by: ours ? 'this_run' : 'another_pass', backup_dir: journal.backup_dir,
+ next: blocked ? `The effect recovery is still blocked (${finished!.error_code ?? 'recovering'}); rerun the same apply, or inspect it with gbrain sources writer status --source ${item.source_id} --json.`
+ : `The withdrawn bytes are back in ${item.files[0]!.relative} and the withdrawal mirror finished it; the edited bytes are backed up under ${journal.backup_dir} (0.disk, with a diff against 0.withdrawn). `
+ + `Writes queued on source ${item.source_id} resume on the resident writer's next pass. Commit the file before the next sync (an uncommitted change is held as worktree_dirty). `
+ + 'If the edit held other changes, make them again from the backup, leaving the forgotten fact out.' };
+ if (!blocked) await writeJournal(engine, key, { ...journal, phase: 'done', result });
+ return { ...result, replayed: false };
+ } finally { await lock.release(); }
+}
diff --cc src/core/repair/stuck-recovery.ts
index ef77827724,bedd443759..12bd7609c5
--- a/src/core/repair/stuck-recovery.ts
+++ b/src/core/repair/stuck-recovery.ts
@@@ -1,18 -1,15 +1,18 @@@
/**
- * `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10): the repair-kind adapter for
- * `persistence/recovery-resolve.ts`. Explicit-only, preview-bound and destructive-consent: the preview lists each
- * recovery record blocked on unexpected bytes (prior and disk fingerprints, a private diff, the choices available)
- * and saves the set under its hash; `--apply --expect <hash> --keep prior|disk --yes` resolves exactly that set. There is no
- * default `--keep`, and a terminal request is listed as refused (see recovery-resolve.ts for the per-state semantics).
- * Projection-only: no journal admission; each record finishes through the owner's own `recoverPublication`.
+ * `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10; GBRA-130 C-1, C-4): the repair-kind
+ * adapter for `persistence/recovery-resolve.ts`. Explicit-only, preview-bound and destructive-consent: the preview lists
+ * each recovery record blocked on unexpected bytes (a page write's, a shared-skill bundle's or a withdrawal-mirror
+ * effect's: recorded and disk fingerprints, a private diff, the choices available) and saves the set under its hash;
+ * `--apply --expect <hash> --keep prior|disk|withdrawn --yes` resolves exactly that set. There is no default `--keep`,
+ * a choice some approved record does not offer is refused before anything runs, and a terminal request is listed as
+ * refused (see recovery-resolve.ts for the per-state semantics).
+ * Projection-only: no journal admission; each record finishes through the owner's own recovery.
*/
import { OperationError } from '../ops/contract.ts';
+import { catalogueError } from '../error-catalogue.ts';
import { loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
- import { KEEP_CHOICES, readResolutions, resolveStuckRecovery, scanStuckRecoveries, stuckRecoveryPreviewCommand, type KeepChoice, type RecoveryFileView, type RefusedRecovery,
-import { readResolutions, resolveStuckRecovery, scanStuckRecoveries, stuckRecoveryPreviewCommand, type KeepChoice, type RecoveryFileView, type RefusedRecovery, type StuckRecovery }
- from '../persistence/recovery-resolve.ts';
++import { KEEP_CHOICES, priorStageUnavailable, readResolutions, resolveStuckRecovery, scanStuckRecoveries, stuckRecoveryPreviewCommand, type KeepChoice, type RecoveryFileView, type RefusedRecovery,
+ type StuckRecovery } from '../persistence/recovery-resolve.ts';
import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
type Selection = { sources: string[]; request_id: string | null };
@@@ -38,28 -32,25 +38,37 @@@ const selectionOf = (scope: RepairScope
const hashOf = (scope: RepairScope, selection: Selection, items: StuckRecovery[]) =>
previewHash({ kind: 'stuck-recovery-v1', brain_id: scope.brain_id, selection, items: items.map(found => found.digest) });
+ /** 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 priorLabel = file.withdrawn ? 'before withdrawal' : 'prior';
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 || file.withdrawn ? '' : ' (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)');
++ + (file.prior.stage ? `, staged copy ${STAGE_TEXT[file.prior.stage.state]}` : file.prior.stored || file.withdrawn ? '' : ' (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`}`,
+ const seen = file.matches === 'neither' ? `neither the ${file.withdrawn ? 'pre-withdrawal nor the withdrawn' : 'prior nor the published'} bytes (blocked)` : `the ${file.matches} bytes`;
+ return [` file ${file.relative}`, ` ${priorLabel}: ${prior}`,
+ ...(file.withdrawn ? [` withdrawn: sha256 ${file.withdrawn.sha256.slice(0, 16)}… size ${file.withdrawn.size}`] : []),
+ ` disk: ${disk}`, ` recovery sees: ${seen}`,
- ...(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}`] : [])];
}
+function headerLines(found: StuckRecovery): string[] {
+ if (found.target === 'withdrawal_mirror') return [` effect ${found.effect_id} (withdrawal mirror of request ${found.request_id}, ${found.source_id}:${found.slug}, ${found.state}${found.blocked_reason ? `, ${found.blocked_reason}` : ''}; page revision ${found.page_revision ?? 'none'})`,
+ ' the withdrawal is committed: --keep withdrawn is the only choice (keeping the edit would keep the forgotten fact on disk)'];
+ const what = found.target === 'skill_bundle' ? `skill bundle ${found.files.length} file(s)` : `page revision ${found.page_revision ?? 'none'}`;
+ return [` request ${found.request_id} (${found.operation} ${found.source_id}:${found.slug}, ${found.state}${found.blocked_reason ? `, ${found.blocked_reason}` : ''}; ${what})`,
+ ` ${found.recorded_error ? `recorded failure ${found.recorded_error}: either choice ends the request with it` : 'no recorded failure: --keep prior requeues the write, --keep disk abandons it'}`
+ + (found.target === 'skill_bundle' ? '; either choice applies to every file of the bundle' : '')];
+}
+
export const stuckRecoveryRepair: RepairHandler = {
kind: 'stuck-recovery',
publication: 'projection',
@@@ -97,9 -88,6 +106,9 @@@
approved = done.map(entry => ({ id: entry.id, request_id: entry.request_id, source_id: entry.source_id, slug: entry.slug, selection } as ApprovedRecovery));
}
if (approved.some(entry => JSON.stringify(entry.selection) !== JSON.stringify(selection))) throw previewChangedError(expect, command);
+ const unavailable = approved.filter(entry => entry.choices && !entry.choices[keep]);
- if (unavailable.length) throw catalogueError('recovery_choice_refused', `--keep ${keep} is not available for ${unavailable.map(entry => `${entry.source_id}:${entry.slug} (${entry.target === 'withdrawal_mirror' ? `withdrawal-mirror effect ${entry.effect_id}` : `request ${entry.request_id}`})`).join(', ')}.`,
++ if (unavailable.length) throw unavailable.map(entry => priorStageUnavailable(entry, keep, expect)).find(Boolean) ?? catalogueError('recovery_choice_refused', `--keep ${keep} is not available for ${unavailable.map(entry => `${entry.source_id}:${entry.slug} (${entry.target === 'withdrawal_mirror' ? `withdrawal-mirror effect ${entry.effect_id}` : `request ${entry.request_id}`})`).join(', ')}.`,
+ `Nothing was changed. The preview lists the choices every record offers; run it again (${command}) and apply one of those, or narrow it to one record with --request-id.`);
const started = new Set((await readResolutions(engine, expect)).map(entry => entry.id));
const fresh = approved.filter(entry => !started.has(entry.id));
if (fresh.length) {
diff --cc test/fixtures/goldens/exports/types.json
index e0e99052ff,bf594ee2fd..e3fdff129f
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@@ -6394,7 -6393,7 +6394,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\" | \"item_failures_systemic\" | \"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\" | \"origin_twin_mass_merge_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\" | \"legacy_lock_removal_refused\" | \"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\" | \"pull_blocked_local_changes\" | \"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\" | \"content_receipt_stale\" | \"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_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"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\" | \"write_interrupted\" | \"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\" | \"item_failures_systemic\" | \"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\" | \"origin_twin_mass_merge_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\" | \"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\" | \"write_interrupted\" | \"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\" | \"item_failures_systemic\" | \"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\" | \"origin_twin_mass_merge_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\" | \"legacy_lock_removal_refused\" | \"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\" | \"pull_blocked_local_changes\" | \"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\" | \"content_receipt_stale\" | \"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_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"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",