Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

LPH (d): resume gated mirrors past #6987's withheld siblings; refuse newer recovery records in --keep withdrawn and the stuck-recovery preview

garrytandda6f90ce545
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index 18bf64377e..1584deb5b1 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -11,4 +11,4 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa
- `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. v0.60.290.0 reads a version 2 record as version 1 (`Buffer.from(null)`, untyped `effect_unavailable` on every attempt, never parks) but never deletes it or its stage, so `mirrorPage` writes none while that binary could claim it (next entry). Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).
-- `src/core/persistence/{recovery-version,segmented-mirror-gate,segmented-gate-hold}.ts` — forward compatibility of recovery records. `recovery-version.ts` lists the record versions this binary reads (`EFFECT_RECOVERY_VERSIONS`, `REQUEST_RECOVERY_VERSIONS`); `assertRecoveryVersion` refuses any other `recovery_version_unsupported` (fix `gbrain upgrade`, `host_admin`) before a reader touches the record: `recoverEffectPublication`, `reserveEffectRecovery`, `upgradeRecoveryStaging` (both tables) and `model.ts` `recoveryFiles` (request recovery, clearing, stuck-recovery); `head-blocker.ts` reports such a record as an intervention with the same fix. `segmented-mirror-gate.ts`: `mirrorPage` calls `assertSegmentedMirrorGate` before streaming a segmented page's file; while `mirrorGateBlockers` sees a live writer below SEGMENTED_WRITER_FLOOR (the switch's TTL-cached `segmentedWriterBlockers`, filtered by `segmented-gate-hold.ts` `liveSegmentedBlockers`, the classification doctor `segmented_storage` uses: this host's own pre-upgrade writes superseded by the same kind of write from this build are not live; cached per gate read and host) it refuses `segmented_mirror_writer_gate` without reserving a record, and the target retries and parks as usual. `resumeGatedMirrors` (each effect pass, at most once per gate TTL per engine) requeues, via `retryParkedEffects`, requests whose parked targets all carry that code once the gate is clear. No version 1 fallback: it would hold the file whole, and v0.60.290.0's recovery of it refuses to materialize a segmented page forever. Tests: `test/pathological/lp-d-recovery-version.test.ts`, `test/pathological/lp-d-segmented-mirror-gate.test.ts` (both engines).
+- `src/core/persistence/{recovery-version,segmented-mirror-gate,segmented-gate-hold}.ts` — forward compatibility of recovery records. `recovery-version.ts` lists the record versions this binary reads (`EFFECT_RECOVERY_VERSIONS`, `REQUEST_RECOVERY_VERSIONS`); `assertRecoveryVersion` refuses any other `recovery_version_unsupported` (fix `gbrain upgrade`, `host_admin`) before a reader touches the record: `recoverEffectPublication`, `reserveEffectRecovery`, `rebaseStaleEffectRecovery` (the `--keep withdrawn` rebase), `upgradeRecoveryStaging` (both tables) and `model.ts` `recoveryFiles` (request recovery, clearing, stuck-recovery); the stuck-recovery preview (`recovery-resolve.ts` `scanStuckRecoveries`) lists such a record refused with that code and fix; `head-blocker.ts` reports such a record as an intervention with the same fix. `segmented-mirror-gate.ts`: `mirrorPage` calls `assertSegmentedMirrorGate` before streaming a segmented page's file; while `mirrorGateBlockers` sees a live writer below SEGMENTED_WRITER_FLOOR (the switch's TTL-cached `segmentedWriterBlockers`, filtered by `segmented-gate-hold.ts` `liveSegmentedBlockers`, the classification doctor `segmented_storage` uses: this host's own pre-upgrade writes superseded by the same kind of write from this build are not live; cached per gate read and host) it refuses `segmented_mirror_writer_gate` without reserving a record, and the target retries and parks as usual. `resumeGatedMirrors` (each effect pass, at most once per gate TTL per engine) requeues, via `retryParkedEffects`, requests whose parked targets all carry that code, or `withdrawal_mirror_failed` for the Git/embedding siblings parked behind the mirror (re-armed once it commits), once the gate is clear. No version 1 fallback: it would hold the file whole, and v0.60.290.0's recovery of it refuses to materialize a segmented page forever. Tests: `test/pathological/lp-d-recovery-version.test.ts`, `test/pathological/lp-d-segmented-mirror-gate.test.ts` (both engines).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 179a8a0402..8d3595501c 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -136,7 +136,7 @@ work behind exits 0, so scripts should also check `results[].complete`.
| `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). |
| `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. 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). |
+| `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), a record a newer gbrain wrote (listed as refused, [`recovery_version_unsupported`](write-refusals.md#recovery_version_unsupported), fix `gbrain upgrade`), `--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. |
@@ -933,7 +933,10 @@ request; it never changes a terminal one). A bundle record this binary cannot
read is listed as refused with
[`recovery_bundle_unsupported`](#recovery-bundle-unsupported), and an effect
record without usable withdrawn bytes with
-[`recovery_effect_unsupported`](#recovery-effect-unsupported). The apply waits
+[`recovery_effect_unsupported`](#recovery-effect-unsupported). A record of
+either kind that a newer gbrain wrote is listed as refused with
+[`recovery_version_unsupported`](write-refusals.md#recovery_version_unsupported)
+and the `gbrain upgrade` fix. The apply waits
at most 10 seconds for the worktree lock, then refuses `writer_lock_unavailable`
with nothing changed; `--keep prior` on a record that predates reserved staging
first reserves it and refuses `queue_capacity` when the recovery budget is full,
diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.ts
index 83e528d209..cfc9f282cd 100644
--- a/src/core/persistence/effect-recovery.ts
+++ b/src/core/persistence/effect-recovery.ts
@@ -130,6 +130,7 @@ export async function rebaseStaleEffectRecovery(engine: BrainEngine, effectId: s
const [current] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [effectId]);
const record = current?.recovery;
if (!record) return null;
+ assertRecoveryVersion('persistence_effects', record, current.source_id);
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;
diff --git a/src/core/persistence/recovery-resolve.ts b/src/core/persistence/recovery-resolve.ts
index 39f0f0e6cb..93cae0a3a8 100644
--- a/src/core/persistence/recovery-resolve.ts
+++ b/src/core/persistence/recovery-resolve.ts
@@ -84,6 +84,7 @@ import { FileBytes, hashDescriptor, hashFile, LARGE_FILE_MIN_BYTES, largeFileWor
import { SEGMENT_MAX_BYTES } from '../page-body/limits.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
import { readHeadBlockers } from './head-blocker.ts';
+import { recoveryVersionKnown, recoveryVersionUnsupported, type RecoveryTable } from './recovery-version.ts';
import { previewChangedError } from './preview-approval.ts';
import { faultPoint } from './fault-points.ts';
import { KEEP_DISK_ABANDONED_PREFIX } from './verb-errors.ts';
@@ -128,7 +129,7 @@ export interface StuckRecovery {
digest: 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';
+export interface RefusedRecovery { code: 'recovery_choice_refused' | 'recovery_effect_unsupported' | 'recovery_bundle_unsupported' | 'recovery_version_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 }
@@ -414,6 +415,7 @@ Promise<{ item: StuckRecovery; sources: Array<{ prior: Bytes; disk: Bytes }> } |
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 (!recoveryVersionKnown('persistence_effects', record)) return newerRefusal('persistence_effects', record, refused);
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');
@@ -497,6 +499,14 @@ export async function scanStuckRecoveries(engine: BrainEngine, sourceIds: string
continue;
}
if (row.blocked_reason === 'unexpected_staging_bytes') { residual('unexpected_staging_bytes'); continue; }
+ if (!recoveryVersionKnown('persistence_requests', row.recovery)) {
+ const refused = newerRefusal('persistence_requests', row.recovery, { request_id: row.request_id, source_id: row.source_id, slug: row.slug, state: row.state,
+ blocked_reason: row.blocked_reason ?? null });
+ if (opts.requestId) throw refusalError(refused);
+ scan.refused.push(refused);
+ residual('newer_recovery_record');
+ continue;
+ }
if (row.recovery?.version === 2 && !filesOf(row.recovery)) {
const refused = bundleRefusal(row);
if (opts.requestId) throw refusalError(refused);
@@ -544,6 +554,12 @@ function bundleRefusal(row: WriteRequest): RefusedRecovery {
+ '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. */
+/** A record a newer gbrain wrote (recovery-version.ts): refused with the upgrade fix before any of its fields is read. */
+function newerRefusal(table: RecoveryTable, record: unknown, base: Omit<RefusedRecovery, 'code' | 'reason' | 'fix'>): RefusedRecovery {
+ const error = recoveryVersionUnsupported(table, record, base.source_id);
+ return { request_id: base.request_id, source_id: base.source_id, slug: base.slug, state: base.state, blocked_reason: base.blocked_reason,
+ ...(base.effect_id ? { effect_id: base.effect_id } : {}), code: 'recovery_version_unsupported', reason: error.message, fix: error.fix };
+}
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;
diff --git a/src/core/persistence/segmented-mirror-gate.ts b/src/core/persistence/segmented-mirror-gate.ts
index d7c983199c..5b6b4d2fa5 100644
--- a/src/core/persistence/segmented-mirror-gate.ts
+++ b/src/core/persistence/segmented-mirror-gate.ts
@@ -19,7 +19,7 @@ import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { opError, type OperationError } from '../ops/contract.ts';
import { SEGMENTED_WRITER_GATE_TTL_MS, SEGMENTED_WRITER_WINDOW_DAYS, segmentedWriterBlockers } from '../page-body/limits.ts';
-import type { PersistenceEffect } from './effect-model.ts';
+import { WITHHELD_BY_MIRROR, type PersistenceEffect } from './effect-model.ts';
import type { SegmentedGateWriter } from './writer-versions.ts';
import { liveSegmentedBlockers } from './segmented-gate-hold.ts';
@@ -76,7 +76,8 @@ export function _resetGatedMirrorResumeForTests(): void { lastResume = new WeakM
/**
* Once the writer gate is clear, requeues (through `retryParkedEffects`, with its authority, claim and recovery checks)
- * up to 100 requests on worktrees this host owns whose every parked target was parked by the gate. Looked for at most
+ * up to 100 requests on worktrees this host owns whose every parked target was parked by the gate, or is a Git or embedding
+ * target parked behind that mirror (`WITHHELD_BY_MIRROR`, re-armed once the mirror commits). Looked for at most
* once per SEGMENTED_WRITER_GATE_TTL_MS per engine; never throws, so an effect pass is never stopped by it.
*/
export async function resumeGatedMirrors(engine: BrainEngine, hostId: string): Promise<number> {
@@ -91,8 +92,8 @@ export async function resumeGatedMirrors(engine: BrainEngine, hostId: string): P
WHERE e.kind='withdrawal-mirror' AND e.state='failed' AND e.error_code='targets_parked' AND w.owner_host_id=$1::uuid
AND e.data->'parked' @> $2::text::jsonb
AND NOT EXISTS (SELECT 1 FROM persistence_effects o CROSS JOIN LATERAL jsonb_array_elements(COALESCE(o.data->'parked','[]'::jsonb)) AS p(target)
- WHERE o.request_id=e.request_id AND o.state<>'committed' AND COALESCE(p.target->>'error_code','')<>$3)
- LIMIT 100`, [hostId, JSON.stringify([{ error_code: SEGMENTED_MIRROR_GATE_CODE }]), SEGMENTED_MIRROR_GATE_CODE]);
+ WHERE o.request_id=e.request_id AND o.state<>'committed' AND COALESCE(p.target->>'error_code','')<>ALL($3::text[]))
+ LIMIT 100`, [hostId, JSON.stringify([{ error_code: SEGMENTED_MIRROR_GATE_CODE }]), [SEGMENTED_MIRROR_GATE_CODE, WITHHELD_BY_MIRROR]]);
if (!requests.length || (await mirrorGateBlockers(engine, hostId)).length) return 0;
const { retryParkedEffects } = await import('./effect-retry.ts');
for (const request of requests) {
diff --git a/test/pathological/lp-d-recovery-version.test.ts b/test/pathological/lp-d-recovery-version.test.ts
index afb64c12a2..c179fd60f5 100644
--- a/test/pathological/lp-d-recovery-version.test.ts
+++ b/test/pathological/lp-d-recovery-version.test.ts
@@ -8,8 +8,10 @@
* its bytes, the canonical file keeps its bytes, nothing is cleared and the effect keeps retrying (never parks). The
* head blocker names it as needing intervention with the same upgrade fix.
* 2. Fails when: recovery reads a version 3 record as version 1 (it embeds `after`, so the old reading removes the
- * stage, publishes the embedded bytes and clears the record) or as anything else, `upgradeRecoveryStaging` rewrites an
- * unknown request record's staging, or the refusal is untyped (`recovery_required`, `effect_unavailable`, a bare Error).
+ * stage, publishes the embedded bytes and clears the record) or as anything else, `rebaseStaleEffectRecovery` (the
+ * `--keep withdrawn` rebase) reads it, `upgradeRecoveryStaging` rewrites an unknown request record's staging, the
+ * stuck-recovery preview mislabels it (`recovery_effect_unsupported`, `recovery_bundle_unsupported`), or the refusal
+ * is untyped (`recovery_required`, `effect_unavailable`, a bare Error).
* 3. PGLite always; PostgreSQL when DATABASE_URL is set. The record is written by the real segmented mirror (crash
* modelled at the `effect_recovery:staged` seam, where the hook rewrites the record's version while this pass still
* holds the worktree lock), so the stage, the reservation and the binding are real.
@@ -19,13 +21,14 @@ import { createHash, randomUUID } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { cliRenderContext, renderAction } from '../../src/core/agent-output.ts';
import { OperationError } from '../../src/core/ops/contract.ts';
-import { recoverEffectPublication } from '../../src/core/persistence/effect-recovery.ts';
+import { rebaseStaleEffectRecovery, recoverEffectPublication } from '../../src/core/persistence/effect-recovery.ts';
import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';
import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
import { headBlockerAction } from '../../src/core/persistence/head-blocker.ts';
import { localHostId } from '../../src/core/persistence/identity.ts';
import { clearResolvedRecovery } from '../../src/core/persistence/journal.ts';
import { recoveryFiles } from '../../src/core/persistence/model.ts';
+import { scanStuckRecoveries } from '../../src/core/persistence/recovery-resolve.ts';
import { upgradeRecoveryStaging } from '../../src/core/persistence/staging.ts';
import { openTwinBrain, type TwinBrain } from '../helpers/segmented-twins.ts';
import { fileOf, settle } from '../helpers/segmented-withdrawal.ts';
@@ -118,6 +121,21 @@ for (const kind of testBackends()) {
expect(json((await brain.engine.executeRaw<{ recovery: unknown }>('SELECT recovery FROM persistence_effects WHERE id=$1', [effect!.id]))[0]!.recovery)).toEqual(written);
await brain.engine.executeRaw(`UPDATE persistence_effects SET state='queued',execution_token=NULL,claim_expires_at=NULL WHERE id=$1`, [effect!.id]);
+ // `--keep withdrawn` rebases a stale record before publishing it; an unknown version is refused there too, never respread as version 1.
+ let persisted = false;
+ const rebase = await withEnv(brain.env(), () => rebaseStaleEffectRecovery(brain.engine, effect!.id, localHostId(), async () => { persisted = true; })).then(() => null, error => error);
+ expectUpgradeRefusal(rebase);
+ expect(persisted).toBe(false);
+ expect(json((await brain.engine.executeRaw<{ recovery: unknown }>('SELECT recovery FROM persistence_effects WHERE id=$1', [effect!.id]))[0]!.recovery)).toEqual(written);
+ expect(existsSync(written.staging.publication.path)).toBe(true);
+
+ // The stuck-recovery preview lists it refused with the upgrade fix, not as an effect it cannot write back.
+ const scan = await withEnv(brain.env(), () => scanStuckRecoveries(brain.engine, [brain.sourceId]));
+ const newer = scan.refused.find(refused => String(refused.effect_id) === String(effect!.id));
+ expect(newer?.code).toBe('recovery_version_unsupported');
+ expect(newer?.fix?.argv).toEqual(['gbrain', 'upgrade']);
+ expect(json((await brain.engine.executeRaw<{ recovery: unknown }>('SELECT recovery FROM persistence_effects WHERE id=$1', [effect!.id]))[0]!.recovery)).toEqual(written);
+
// The head blocker's exit for it is the same upgrade, told to the user.
const action = headBlockerAction({ predicate: 'effect_recovery', ids: [effect!.id], state: 'recovery_version_unsupported', owner: null, intervention: true }, brain.sourceId, `gbrain sync --source ${brain.sourceId}`);
expect(action.argv).toEqual(['gbrain', 'upgrade']);
@@ -126,8 +144,8 @@ for (const kind of testBackends()) {
}, 600_000);
test('a version 3 write request recovery record is refused by staging upgrade, file listing and clearing, and left as it is', async () => {
- const [request] = await brain.engine.executeRaw<{ id: string; worktree_id: string }>(
- `SELECT id::text AS id, worktree_id::text AS worktree_id FROM persistence_requests WHERE source_id=$1 AND state='committed' AND worktree_id IS NOT NULL ORDER BY sequence DESC LIMIT 1`, [brain.sourceId]);
+ const [request] = await brain.engine.executeRaw<{ id: string; request_id: string; worktree_id: string }>(
+ `SELECT id::text AS id, request_id::text AS request_id, worktree_id::text AS worktree_id FROM persistence_requests WHERE source_id=$1 AND state='committed' AND worktree_id IS NOT NULL ORDER BY sequence DESC LIMIT 1`, [brain.sourceId]);
// No staging: a version 1 reader's upgradeRecoveryStaging would allocate a restoration stage from `before` and rewrite the record.
const record = { version: 3, path: fileOf(brain, SEGMENTED), root: brain.root, before: Buffer.from('prior bytes').toString('base64'), beforeHash: sha(Buffer.from('prior bytes')),
afterHash: sha(readFileSync(fileOf(brain, SEGMENTED))), mode: null, ownerEpoch: '1', attempt: randomUUID(), next: { layout: 'future' } };
@@ -147,8 +165,12 @@ for (const kind of testBackends()) {
expectUpgradeRefusal(listed);
expectUpgradeRefusal(await clearResolvedRecovery(brain.engine, request!.id).then(() => null, error => error));
expect(await stored()).toEqual(record);
+ // A live (recovering) request with it: the stuck-recovery preview refuses it with the upgrade fix, not as a bundle it cannot read.
+ await unguarded("UPDATE persistence_requests SET state='recovering' WHERE id=$1::uuid", [request!.id]);
+ expectUpgradeRefusal(await withEnv(brain.env(), () => scanStuckRecoveries(brain.engine, [brain.sourceId], { requestId: request!.request_id })).then(() => null, error => error));
+ expect(await stored()).toEqual(record);
} finally {
- await unguarded('UPDATE persistence_requests SET recovery=NULL WHERE id=$1::uuid', [request!.id]);
+ await unguarded("UPDATE persistence_requests SET recovery=NULL,state='committed' WHERE id=$1::uuid", [request!.id]);
}
}, 120_000);
});