Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-130 PR 2 fix F1: rebase a stale withdrawal-mirror record before --keep withdrawn publishes it
garrytana3747a1ec76d
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.mdindex 0456c3fb98..711ea6c3c3 100644--- a/docs/architecture/key-files/core-persistence-request-indexes.md+++ b/docs/architecture/key-files/core-persistence-request-indexes.md@@ -6,7 +6,7 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `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` (`upgradeRecoveryStaging` `forward`, then the recorded `after` bytes published at the record's 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/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/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).diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 79c501e37e..45dbd70641 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -376,8 +376,8 @@ src/core/persistence/connector-sync.ts prepareConnectorMutation field SEGWsrc/core/persistence/core-guard.ts prepareCoreGuard field INLINEsrc/core/persistence/effect-facts.ts bodyAlreadyOffered field METAsrc/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 2src/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 2src/core/persistence/embedding-settlement.ts listEmbeddingCandidates sql METAsrc/core/persistence/facts-maintenance.ts prepareManagedFactsSession field METAsrc/core/persistence/facts-prepare.ts prepareManagedFactsMutation call:serializePageToMarkdown SEGW assertInlineBody firstdiff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.tsindex 7df3982df9..4437723a75 100644--- a/src/core/persistence/effect-recovery.ts+++ b/src/core/persistence/effect-recovery.ts@@ -6,6 +6,9 @@ import { readFix } from '../ops/op-fix.ts';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 { lockCounters } from './journal.ts';@@ -15,7 +18,7 @@ import { withFilesystemPublication } from './filesystem-guard.ts';import { persistenceFileHash, publishPersistenceFile } from './coordinator.ts';import type { EffectRecovery, PersistenceEffect } from './effect-model.ts';import { tryAcquirePublicationCapacity } from './pool-capacity.ts';-import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, upgradeRecoveryStaging } from './staging.ts';+import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFile, upgradeRecoveryStaging } from './staging.ts';import { declarePersistenceProtocol } from './protocol.ts';import { advanceEffectCursor } from './effect-journal.ts';import { faultPoint } from './fault-points.ts';@@ -97,6 +100,53 @@ async function clearRecovery(tx: BrainEngine, effect: PersistenceEffect): Promisawait 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,+ 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;+ });+}+/** 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> {diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex a587c9a92e..e4fb8ccf37 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -35,7 +35,7 @@ import { sha256 } from './digest.ts';import { prepareFileTarget } from './page-prepare.ts';import { isSourceDbOnlySlug } from './source-storage.ts';import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, failEffect, failedMirrorAllowlists, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect } from './effect-journal.ts';-import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';+import { guardEffectSource, mirrorContent, 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';@@ -196,7 +196,7 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindinif (isMetafilePage(snapshot)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'metafile'); return; }// Wave B PR 1: a segmented body has no whole-body mirror yet (per-segment mirror in PR 2).if (isSegmentedPage(snapshot.page)) { await skipTarget(engine, effect, snapshot, 'page_body_segmented'); return; }- const content = serializePageToMarkdown(snapshot.page, snapshot.tags);+ const content = mirrorContent(snapshot);let file: Awaited<ReturnType<typeof prepareFileTarget>>;try {file = binding?.local_path ? await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true }) : undefined;diff --git a/src/core/persistence/recovery-resolve.ts b/src/core/persistence/recovery-resolve.tsindex e0f64bff99..9f4f3a6b92 100644--- a/src/core/persistence/recovery-resolve.ts+++ b/src/core/persistence/recovery-resolve.ts@@ -29,7 +29,11 @@* 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. A record without+ * 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.*@@ -64,6 +68,7 @@ import { isTerminal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecordimport 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';@@ -120,6 +125,8 @@ export interface StuckRecoveryScan { items: StuckRecovery[]; residuals: Record<sinterface Journal {id: string; request_id: string; source_id: string; slug: string; preview_hash: string; keep: KeepChoice;phase: 'backed_up' | 'written' | 'abandoned' | 'done'; backup_dir: string; original: { state: string; blocked_reason: string | null; prior_hashes: Array<string | null>; disk_hashes: Array<string | null> };+ /** A withdrawal-mirror record rebased on a later page revision: the identity it now has (the preview bound the original). */+ identity?: RecoveryIdentity;result?: ResolutionResult;}export interface ResolutionResult {@@ -584,7 +591,7 @@ Promise<ResolutionResult & { replayed: boolean }> {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(item.identity);+ 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);@@ -602,6 +609,13 @@ Promise<ResolutionResult & { replayed: boolean }> {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!;await withFilesystemPublication([record.root], async () => {diff --git a/test/pathological/c1-effect-stuck-recovery.test.ts b/test/pathological/c1-effect-stuck-recovery.test.tsindex 9e544e7ab5..5774ba7ec0 100644--- a/test/pathological/c1-effect-stuck-recovery.test.ts+++ b/test/pathological/c1-effect-stuck-recovery.test.ts@@ -39,12 +39,14 @@ import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedconst SOURCE = 'default';const CLAIM = 'Door code is 4417';+const CLAIM_B = 'Gate code is 5521';const EDITED = beliefPage({ facts: [CLAIM], prose: 'Draft, edited by hand while the withdrawal was being mirrored.' });const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });afterEach(() => installFaultHook(undefined));-interface StuckEffect { b: BeliefBrain; engine: BrainEngine; root: string; file: string; effectId: string; requestId: string; record: { after: string; afterHash: string; beforeHash: string } }+interface StuckEffect { b: BeliefBrain; engine: BrainEngine; root: string; file: string; effectId: string; requestId: string; edited: string;+ record: { after: string; afterHash: string; beforeHash: string } }const mirror = (engine: BrainEngine) => engine.executeRaw<{ id: string; error_code: string | null; recovery: StuckEffect['record'] | null; request_id: string }>("SELECT e.id::text AS id, e.error_code, e.recovery, r.request_id::text AS request_id FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='withdrawal-mirror' ORDER BY e.id");@@ -62,14 +64,15 @@ function commitAll(root: string, message: string): void {const sync = (engine: BrainEngine) => performSync(engine, { sourceId: SOURCE, noPull: true, noEmbed: true, noExtract: true, drain: true, deadlineAtMs: Date.now() + 60_000 } as never);/**- * A managed brain (git checkout) with `affected` (one fact) and `sibling`, synced; a `forget` of the fact whose mirror- * dies after writing the file (before its commit), then a hand edit of the file, and the owner's next recovery pass- * refusing it unexpected_file_bytes.+ * A managed brain (git checkout) with `affected` (`facts`, default one) and `sibling`, synced; a `forget` of the first+ * fact whose mirror dies after writing the file (before its commit), then a hand edit of the file (`edit` of the mirrored+ * bytes, default EDITED), and the owner's next recovery pass refusing it unexpected_file_bytes.*/-async function stuckEffect(databaseUrl: string | undefined, run: (s: StuckEffect) => Promise<void>): Promise<void> {+async function stuckEffect(databaseUrl: string | undefined, run: (s: StuckEffect) => Promise<void>,+ opts: { facts?: string[]; edit?: (mirrored: string) => string } = {}): Promise<void> {await managedBrain(async ({ engine, ctx, root }) => {const b = brainApi(engine, ctx, root, SOURCE);- await b.put('affected', beliefPage({ facts: [CLAIM] }));+ await b.put('affected', beliefPage({ facts: opts.facts ?? [CLAIM] }));await b.put('sibling', beliefPage({ title: 'Sibling Example', prose: 'Sibling.' }));commitAll(root, 'seed');await sync(engine);@@ -81,12 +84,14 @@ async function stuckEffect(databaseUrl: string | undefined, run: (s: StuckEffectinstallFaultHook(undefined);const file = join(root, 'affected.md');const [crashed] = await mirror(engine);- expect(readFileSync(file, 'utf8')).toBe(Buffer.from(crashed!.recovery!.after, 'base64').toString('utf8'));- writeFileSync(file, EDITED);+ const mirrored = Buffer.from(crashed!.recovery!.after, 'base64').toString('utf8');+ expect(readFileSync(file, 'utf8')).toBe(mirrored);+ const edited = opts.edit?.(mirrored) ?? EDITED;+ writeFileSync(file, edited);await retryNow(engine);await waitFor(async () => (await mirror(engine))[0]?.error_code === 'unexpected_file_bytes', { timeoutMs: 60_000, intervalMs: 100, label: 'mirror recovery refused' });const [stuck] = await mirror(engine);- await run({ b, engine, root, file, effectId: stuck!.id, requestId: stuck!.request_id, record: stuck!.recovery! });+ await run({ b, engine, root, file, effectId: stuck!.id, requestId: stuck!.request_id, edited, record: stuck!.recovery! });}, { databaseUrl, setup: ({ root }) => {git(root, 'init', '-q'); git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');git(root, 'commit', '-q', '--allow-empty', '-m', 'init');@@ -189,5 +194,35 @@ for (const { backend, databaseUrl } of pathologicalArms()) {expect(readFileSync(s.file, 'utf8')).toBe(Buffer.from(s.record.after, 'base64').toString('utf8'));expectOthersUnchanged(before, await snapshotItems(s.engine, SOURCE), { changed: ['affected'] });}), 240_000);++ test('C-1 stale: a later withdrawal on the same page makes the stuck record stale; no interruption of --keep withdrawn publishes a withdrawn fact, and the same apply resumes to resolved', () => stuckEffect(databaseUrl, async s => {+ const [second] = await s.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL', [SOURCE, CLAIM_B]);+ await operations.find(o => o.name === 'forget')!.handler(s.b.ctx, { id: Number(second!.id) });+ const active = async () => (await s.engine.executeRaw<{ fact: string }>('SELECT fact FROM facts WHERE source_id=$1 AND fact = ANY($2::text[]) AND expired_at IS NULL',+ [SOURCE, [CLAIM, CLAIM_B]])).map(row => row.fact);+ expect(await active()).toEqual([]);+ const leaked = () => parseFactsFence(readFileSync(s.file, 'utf8')).facts.filter(f => [CLAIM, CLAIM_B].includes(f.claim) && !f.forgotten).map(f => f.claim);++ const preview = await expectUnitNotAborted(() => repair(s.engine));+ expect((preview.details as Record<string, any>).recoveries).toHaveLength(1);+ const apply = () => repair(s.engine, { apply: true, expect: preview.preview_hash!, keep: 'withdrawn' });+ for (const point of ['stuck_recovery:backed_up', 'stuck_recovery:written', 'stuck_recovery:recovered']) {+ installFaultHook(async at => { if (at === point) throw new Error(`process ended at ${point}`); });+ const interrupted = await apply().then(result => result.outcomes, error => ({ thrown: String(error) }));+ installFaultHook(undefined);+ expect({ point, resolved: (interrupted as Record<string, unknown>).resolved ?? null }).toEqual({ point, resolved: null });+ if (point === 'stuck_recovery:backed_up') expect(readFileSync(s.file, 'utf8')).toBe(s.edited);+ else expect({ point, leaked: leaked() }).toEqual({ point, leaked: [] });+ }+ const applied = await expectUnitNotAborted(apply);+ expect(applied.outcomes).toEqual({ resolved: 1 });+ expect(leaked()).toEqual([]);+ expect((await mirror(s.engine))[0]!.recovery).toBeNull();++ commitAll(s.root, 'after recovery');+ await sync(s.engine);+ expect(await active()).toEqual([]);+ expect(leaked()).toEqual([]);+ }, { facts: [CLAIM, CLAIM_B], edit: mirrored => mirrored.replace('Draft.', 'Draft, edited by hand while the withdrawal was being mirrored.') }), 240_000);});}