Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): stop at once on a withdrawal-mirror recovery blocked by an edited file
garrytane31506dc8c8d
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 1ab0633f71..2e5c4c8a32 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2332,7 +2332,9 @@ writer status --source <id> --json` and ask the user whether the edited filemay be replaced by its withdrawn version; the resident writer finishes theeffect once the file matches one of its recorded versions. The preview liststhe effect as `refused`; naming its request with `--request-id` refuses with-this code.+this code. A sync queued behind such an effect stops at once with+[`drain_stalled`, `cause: head_blocked`](write-refusals.md#head-blocked), and+its fix names the file.### Legacy job authoritydiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 9620aa4296..7ee3a745a1 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -515,7 +515,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run| <a id="drain-write-capacity"></a>`write_capacity` | `queue_capacity` | `blocked` | The sync could not admit its next write for the whole no-progress window (30 s) because other writers' requests held the outstanding-request cap of its write principal (`persistence.limits.principal_outstanding`, default 100; the brain cap `persistence.limits.brain_outstanding`, 1000, works the same way): on one host the CLI sync and a maintenance run (fact-fence adoption, `dream`) share the `local_cli` principal, so a long adoption queue leaves no room for a sync write. Nothing failed and the cursor is intact: the drain retried the admission with backoff while they settled, printing `waiting for write capacity (N outstanding of M)`, and stopped only when the window passed. `drain.capacity` carries the counts and the wait; exit 1. A cumulative cap (permanent request IDs, receipt bytes) is a different refusal: it names its config key and stops at once. | `gbrain sources writer status --source <source> --json` lists the outstanding requests (read-only). Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync; it resumes where it stopped. || <a id="drain-connection-lost"></a>`connection_lost` | `connection_lost` | `blocked` | The database connection dropped three times in a row (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`: a pooler closing the socket mid-statement) with no page committed between the drops (#6340). Each drop was reconnected and retried after 5, 15 and 45 s; a drop that then moves data is not reported at all. Nothing is recorded against the source: the cursor and its frozen manifest stand, and `drain.connection` carries the count and the last error text (never a URL). Exit 1. | Check the database and pooler (`gbrain doctor --json`), then rerun `next.command` (`safe_to_loop` is true, `retry_after_ms` 60 s): it resumes at the stored cursor without re-freezing the manifest, with or without `--retry-failed`. Runbook: [sync unblock](sync-unblock-runbook.md#connection). || <a id="drain-capacity-paused"></a>`capacity_paused` | `capacity_paused` | `resumable` | The run passed its capacity preflight, then a cumulative write cap refused its next admission (`write_quota_exhausted`) or, for a background sync, the pause line did (`write_capacity_backpressure`): another writer used the room the preflight counted on. Nothing failed; the cursor and every accepted write stand, and `drain.capacity_pause` names the refusal and its config raise. | Run the `gbrain config set` the report names on the brain host (request ids never free; receipt bytes also free as receipts compact), then rerun the same `gbrain sync`. Verify with `gbrain doctor --only persistence_capacity --json`. |-| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock) or `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`). The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, `effect_recovery`, `request_recovery`, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. |+| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock), `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`), or `effect_recovery` with state `unexpected_file_bytes` (a fact-withdrawal mirror's page file was edited while the mirror was publishing, so its forward-only recovery refuses to overwrite it; `blocked_by.file` names the page and path). The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, an `effect_recovery` that can still finish forward, `request_recovery`, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process; `effect_recovery` asks the user to copy the edited file aside and put it back to a version gbrain recorded (undo the edit, or restore the committed version), never to delete it, and to redo the edit after the withdrawal finishes. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. || <a id="sync_drain_lease_held"></a>`drain_lease_held` | `sync_drain_lease_held` | `resumable` | Another process holds the source's drain lease (#6712): one managed drainer per source, and that holder (a serve, a `sync` job, the dream cycle, another terminal) is still committing pages. `gbrain sync` follows it within its own `--timeout` and run deadline, printing the holder (kind, pid, host, gbrain version) and the pages it commits (every 10 s on a terminal, 60 s otherwise), and takes the lease when the holder releases it. This code means the budget ended first, or the lease moved to another process mid-pass (`lost`); nothing this run admitted is lost and the cursor is intact. `--no-delegate` never skips the lease. `drain.lease_held.holder` reuses the drain's owner fields: `kind`, `id`, `host`, `pid`, `started_at`, `last_heartbeat_at`, `version` and `progress` (`committed`, `last_committed_at`, `last_progress_at`); `next.retry_after_ms` is 60 s and `next.safe_to_loop` is true. Exit 0. A cron that runs `gbrain sync` every few minutes beside a serve exits 0 here on each tick while the serve works. | Rerun `next.command` after `next.retry_after_ms`, or let the holder finish. Ctrl-C while following stops only this run; the holder keeps going. A holder that commits nothing for 5 minutes is not reported here: the run stops [`drain_stalled`](#drain-lease-stalled) instead. || <a id="drain-lease-stalled"></a>`drain_stalled` with `cause: no_progress` and `stall.lease_holder` | `drain_stalled` | `blocked` | The process holding the source's drain lease committed no page and saved no cursor for 5 minutes, so following it would exit 0 forever (#6712). `drain.stall.lease_holder` names it with the fields above; the lease itself is renewed by a live process, so a wedged holder keeps it. A holder that died lets its lease lapse within 2 minutes and the next run takes over without this stop. Exit 1, `next.safe_to_loop` false. | `gbrain sources writer status --source <source> --json` (read-only) shows what the holder is waiting on. Stop or restart the named process; when it is gone but its lock row remains, `gbrain sync --source <source> --no-pull --break-lock` releases a lock whose pid is dead (`--force-break-lock` skips the liveness check: only when you know the holder is gone). Then rerun the same sync. |diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c923743538..4c41f6763e 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -692,6 +692,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.258.0', text: 'A connector source\'s autopilot cycle now extracts facts and recomputes emotional weight only for that source\'s pages changed since its last completed cycle. Before, both phases walked every page in the brain on every connector cycle, which on a large brain ran past the 30-minute job deadline, so the cycle never finished and repeated the full walk.' },// LHF wave 2 item 0 (GBRA-94): tokenmax `query` no longer expands by default.{ since: '0.60.259.0', text: '`gbrain query` no longer runs LLM query expansion by default on `tokenmax`, so no search mode expands by default. On 300 LongMemEval-S questions with the reranker, `query` without expansion kept retrieval within noise (298 vs 299 of 300) and its p50 fell from about 2 s to about 230 ms (gbrain-evals expansion-latency report, 2026-10-14). To keep expanding: `gbrain config set search.expansion true` for the brain, or pass `--expand` / `expand: true` per call.' },+ // A sync behind a withdrawal-mirror recovery blocked on unexpected_file_bytes stops at once instead of waiting 5 minutes.+ { since: '0.60.260.0', text: 'A sync queued behind a fact-withdrawal mirror whose page file was edited while the mirror was publishing (its recovery refuses `unexpected_file_bytes` and only the user can resolve the file) now stops after one governor tick with `drain_stalled`, `cause: head_blocked` and `blocked_by=effect_recovery(unexpected_file_bytes …)`, instead of waiting out the 5-minute no-progress window. Its fix names the file and asks the user to put it back to a version gbrain recorded, then rerun the sync; `gbrain sources writer status` names the same file. A mirror recovery that can still finish forward keeps the wait.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/head-blocker.ts b/src/core/persistence/head-blocker.tsindex 535892a580..5c580714d2 100644--- a/src/core/persistence/head-blocker.ts+++ b/src/core/persistence/head-blocker.ts@@ -3,13 +3,18 @@* the stall line and `sources writer status` name what blocks it instead of a constant "claimable here: no".** Blockers are classified. Intervention-required ones stop the drain (`drain_stalled`, `cause: head_blocked`) after one- * governor tick of confirmation: a durable refresh fence no live refresh process holds, or a running row ahead whose owner- * reports `restart_required` (a zombie publication). Every other blocker is live and transient (a foreground publication,+ * governor tick of confirmation: a durable refresh fence no live refresh process holds, a running row ahead whose owner+ * reports `restart_required` (a zombie publication), or a withdrawal-mirror effect recovery its own last attempt refused+ * `unexpected_file_bytes` whose file still matches neither recorded version (an edit made while the mirror was publishing;+ * recovery only finishes forward and never overwrites it). Every other blocker is live and transient (a foreground publication,* a refresh or recovery making progress, a lapsed lease the next consumer reclaims), so the drain keeps its progress-aware wait.*/+import { existsSync, readFileSync } from 'node:fs';+import { basename, dirname } from 'node:path';import type { BrainEngine } from '../engine.ts';import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';import { claimStateOf } from './claim-phase.ts';+import { sha256 } from './digest.ts';import { claimableWriteSql, EARLIER_HEAD, foregroundPrioritySql, SYNC_KIND } from './journal.ts';export type HeadBlockerPredicate = 'worktree_owner' | 'refresh_fence' | 'effect_recovery' | 'withdrawal_mirror' | 'request_recovery'@@ -18,12 +23,14 @@ export interface HeadBlocker {predicate: HeadBlockerPredicate;/** The refresh id for a fence, the request ids of blocking requests, the effect ids of blocking effects, or the worktree id. */ids: string[];- /** The fence state, the blocking request's state, or the worktree state (`other_host` when another host owns it). */+ /** The fence state, the blocking request's state, the worktree state (`other_host` when another host owns it), or why an effect recovery cannot finish. */state: string | null;/** The process behind the blocker when one is known: a refresh process (`live` from its lock) or a claim's stamped owner. */owner: { kind: string | null; pid: number | null; live: boolean | null; restart_required: boolean } | null;/** True when only an operator clears it; the drain stops on these and keeps waiting on the rest. */intervention: boolean;+ /** The canonical file an `unexpected_file_bytes` effect recovery refuses to overwrite. */+ file?: { slug: string; path: string };}/** A blocking request this caller may cancel: not publishing, no recovery record; `cancel-write-request` is scoped to its principal. */export interface HeadBlockerCancel { request_id: string; principal_kind: string; principal_id: string }@@ -32,8 +39,22 @@ export type HeadBlockerRead = { status: 'claimable' } | { status: 'blocked'; blointerface RowRef { request_id: string; state: string; claim_phase: unknown; execution_token: string | null; claim_lapsed: boolean;publication_started: boolean; recovery: boolean; principal_kind: string; principal_id: string }interface ProbeRow { id: string; worktree_id: string | null; owner_host_id: string | null; worktree_state: string | null; claimable: boolean;- fence: { id: string; state: string } | null; effect_recovery: string[] | null; mirrors: string[] | null; request_recovery: string[] | null;+ fence: { id: string; state: string } | null; effect_recovery: EffectRecoveryRef[] | null; mirrors: string[] | null; request_recovery: string[] | null;earlier: RowRef[] | null; ahead: RowRef[] | null }+interface EffectRecoveryRef { id: string; error_code: string | null; slug: string | null; path: string | null; before: string | null; after: string | null }++/**+ * Whether an effect recovery cannot finish without the user: its last attempt refused `unexpected_file_bytes` and the file still+ * matches neither recorded hash (the check recovery itself refuses on). A file put back on a recorded version is live again before+ * the next retry clears the code; a file this process cannot read keeps the recovery's own verdict.+ */+function effectRecoveryStuck(effect: EffectRecoveryRef): boolean {+ if (effect.error_code !== 'unexpected_file_bytes' || !effect.path) return false;+ try {+ const actual = existsSync(effect.path) ? sha256(readFileSync(effect.path)) : null;+ return actual !== effect.before && actual !== effect.after;+ } catch { return true; }+}const REF = (alias: string) => `jsonb_build_object('request_id',${alias}.request_id::text,'state',${alias}.state,'claim_phase',${alias}.claim_phase,'execution_token',${alias}.execution_token::text,'claim_lapsed',COALESCE(${alias}.claim_expires_at<now(),false),'publication_started',COALESCE(${alias}.publication_started,false),@@ -52,7 +73,8 @@ export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostI(${claimableWriteSql(priority)}) AS claimable,(SELECT jsonb_build_object('id',f.id::text,'state',f.state) FROM persistence_worktree_refreshes fWHERE f.worktree_id=r.worktree_id AND f.state IN ('fenced','merged','recovery_required') LIMIT 1) AS fence,- (SELECT array_agg(e.id::text) FROM persistence_effects e WHERE e.worktree_id=r.worktree_id AND e.recovery IS NOT NULL) AS effect_recovery,+ (SELECT jsonb_agg(jsonb_build_object('id',e.id::text,'error_code',e.error_code,'slug',e.recovery->>'slug','path',e.recovery->>'path',+ 'before',e.recovery->>'beforeHash','after',e.recovery->>'afterHash') ORDER BY e.id) FROM persistence_effects e WHERE e.worktree_id=r.worktree_id AND e.recovery IS NOT NULL) AS effect_recovery,(SELECT array_agg(m.id::text) FROM persistence_effects m WHERE m.worktree_id=r.worktree_id AND m.kind='withdrawal-mirror' AND m.state IN ('queued','running')AND (NOT (m.data ? 'targets') OR m.data->'targets' @> jsonb_build_array(jsonb_build_object('slug',r.slug)))) AS mirrors,(SELECT array_agg(b.request_id::text) FROM persistence_requests b WHERE b.worktree_id=r.worktree_id AND b.recovery IS NOT NULL) AS request_recovery,@@ -77,7 +99,12 @@ export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostIintervention: row.fence.state === 'recovery_required' || live === false });continue;}- if (row.effect_recovery?.length) { blocked({ predicate: 'effect_recovery', ids: row.effect_recovery, state: null, owner: null, intervention: false }); continue; }+ if (row.effect_recovery?.length) {+ const stuck = row.effect_recovery.find(effectRecoveryStuck);+ blocked({ predicate: 'effect_recovery', ids: row.effect_recovery.map(effect => effect.id), state: stuck ? 'unexpected_file_bytes' : null, owner: null, intervention: !!stuck,+ ...(stuck ? { file: { slug: stuck.slug ?? '', path: stuck.path! } } : {}) });+ continue;+ }if (row.mirrors?.length) { blocked({ predicate: 'withdrawal_mirror', ids: row.mirrors, state: null, owner: null, intervention: false }); continue; }if (row.request_recovery?.length) { blocked({ predicate: 'request_recovery', ids: row.request_recovery, state: null, owner: null, intervention: false }); continue; }const ref = row.earlier?.[0] ?? row.ahead?.[0];@@ -132,6 +159,18 @@ export function headBlockerAction(blocker: HeadBlocker, sourceId: string, resumewhy: `Request ${blocker.ids[0]} ahead of the head is held by ${who}, which reports restart_required; its root stays held until that process exits. Status names it, read-only.`,user_message: `Restart ${who} on the brain host, then run: ${resumeCommand}`, verify: { argv: status } };}+ if (blocker.predicate === 'effect_recovery' && blocker.intervention && blocker.file) {+ const { path, slug } = blocker.file;+ return { argv: status, consent: [], actor: 'user', requires_exclusive: false,+ why: `Mirroring a fact withdrawal into ${path} (page ${slug}) stopped between writing the file and recording it, and the file was edited after that: `+ + 'it matches neither the version from before the withdrawal nor the withdrawn version gbrain wrote. Recovery only finishes forward and never overwrites '+ + `bytes it cannot account for, so every write to source ${sourceId} waits and waiting does not clear it. Status shows the effect, read-only.`,+ user_message: `${path} was edited while gbrain was removing a withdrawn fact from it, so gbrain will not touch the file and writes to source ${sourceId} are paused. `+ + `Copy the edited file somewhere safe, then put the file back to a version gbrain recorded: undo the edit, or restore the committed version `+ + `(git -C ${dirname(path)} checkout -- ${basename(path)}). Do not delete the file. Then run: ${resumeCommand}. gbrain finishes removing the withdrawn fact; `+ + 'make the edit again afterwards, leaving the withdrawn fact out.',+ verify: { argv: status } };+ }return { argv: status, consent: [], actor: 'agent', requires_exclusive: false,why: `The head waits on ${headBlockerText(blocker)}, which is making progress on its own. Rerun status (read-only) to see it clear.`, verify: { argv: status } };}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex b2b4e58080..43546802c4 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -175,6 +175,7 @@ test/source-row-diagnostics.test.tstest/stats-health-source-scope.test.tstest/sync-capacity-preflight.test.tstest/sync-drain-claims.test.ts+test/sync-drain-effect-recovery-blocked.test.tstest/sync-drain-head-blocked-6543.test.tstest/sync-drain-inpass-stall.test.tstest/sync-drain-write-capacity.test.tsdiff --git a/test/sync-drain-effect-recovery-blocked.test.ts b/test/sync-drain-effect-recovery-blocked.test.tsnew file mode 100644index 0000000000..c57b9137c2--- /dev/null+++ b/test/sync-drain-effect-recovery-blocked.test.ts@@ -0,0 +1,154 @@+/**+ * A withdrawal-mirror effect recovery whose canonical file was edited between the mirror's file write and its database commit+ * refuses `unexpected_file_bytes` and retains its record: only the user resolving the file clears it. The head probe used to+ * classify every effect recovery as live, so a sync behind it waited the whole no-progress window (5 minutes) before stopping.+ * Such a recovery is now intervention-required: the drain stops `drain_stalled` / `cause: head_blocked` after one governor tick+ * with a fix naming the file. A recovery that can still finish forward (the file holds a recorded version) keeps the wait.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWrite, completeWrite } from '../src/core/persistence/journal.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';+import { upsertFactRow } from '../src/core/facts-fence.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { headClaimability } from '../src/core/persistence/head-blocker.ts';+import { drainNext, engineStallProbe, formatDrainSummary, runDrain } from '../src/core/persistence/sync-drain.ts';+import { readWriterDiagnostics } from '../src/core/persistence/diagnostics.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import type { SyncResult } from '../src/commands/sync.ts';++const hostId = localHostId();+const config = { engine: 'pglite' as const, embedding_disabled: true };+const roots: string[] = [];+const engines: Array<[string, BrainEngine]> = [];+let closePostgres: (() => Promise<void>) | undefined;+const done: SyncResult = { status: 'synced', fromCommit: 'a', toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0,+ pagesAffected: [], managedCursor: { index: 1, total: 1 } };+const body = upsertFactRow('Stable prose', { claim: 'Withdraw this claim', kind: 'fact', visibility: 'world', confidence: 1, notability: 'medium' }).body;+const EDIT = 'An edit the user made while the withdrawal was being mirrored\n';++beforeAll(async () => {+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(['pglite', lite]); }+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(['postgres', pg.engine]); closePostgres = pg.close; }+ for (const [, engine] of engines) await registerLocalWriter(engine, 'cli');+}, 120_000);+afterAll(async () => {+ for (const [kind, engine] of engines) if (kind === 'pglite') await engine.disconnect();+ await closePostgres?.();+ for (const root of roots) rmSync(root, { recursive: true, force: true });+});++/** A source whose page carries one fact, withdrawn, with its mirror crashed between the file write and the commit, and a queued write behind it. */+async function crashedMirror(engine: BrainEngine) {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-mirror-blocked-')); roots.push(root);+ const sourceId = `mirror-${randomUUID().slice(0, 8)}`, slug = 'page';+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ const binding = await claimWorktree(engine, sourceId, root, hostId);+ await engine.putPage(slug, { type: 'note', title: 'Example', compiled_truth: body.trim(), timeline: '', frontmatter: {} }, { sourceId });+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const file = join(root, `${slug}.md`); mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));+ const ctx: OperationContext = { engine, config, remote: false, dryRun: false, sourceId, logger: { info() {}, warn() {}, error() {} } };+ const authority = await submissionAuthority(ctx, 'put_page', sourceId, binding.source_incarnation, slug);+ const admit = () => admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId, sourceIncarnation: binding.source_incarnation,+ slug, pageId: snapshot.page.id, requestId: randomUUID(), callerIntent: { content: 'After' }, intent: { content: 'After' }, worktreeId: binding.worktree_id,+ topologyGeneration: binding.topology_generation });+ const withdrawal = await admit();+ const [fact] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,entity_slug,fact,source,visibility)+ VALUES($1,$2,'Withdraw this claim','test conversation','world') RETURNING id`, [sourceId, slug]);+ await engine.transaction(async tx => {+ await recordFactWithdrawal(tx, Number(fact.id), sourceId, false, { requestId: withdrawal.id });+ await completeWrite(tx, withdrawal, 'committed', { status: 'forgotten' });+ });+ const only = async () => {+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE request_id<>$1::uuid OR kind<>'withdrawal-mirror'", [withdrawal.id]);+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE request_id=$1::uuid AND kind='withdrawal-mirror'", [withdrawal.id]);+ };+ await only();+ let crashed = false;+ await runPersistenceEffects(engine, config, { hostId, limit: 1, boundary: async name => { if (name === 'after_mirror_file') { crashed = true; throw new Error('process ended before commit'); } } });+ expect(crashed).toBe(true);+ const [effect] = await engine.executeRaw<{ id: string }>("SELECT id::text AS id FROM persistence_effects WHERE request_id=$1::uuid AND kind='withdrawal-mirror' AND recovery IS NOT NULL", [withdrawal.id]);+ expect(effect).toBeDefined();+ const published = readFileSync(file, 'utf8');+ const head = await admit();+ const [row] = await engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE request_id=$1::uuid', [head.request_id]);+ return { sourceId, slug, file, published, effectId: effect!.id, head: { id: row!.id, request_id: head.request_id },+ recover: async () => { await only(); await runPersistenceEffects(engine, config, { hostId, limit: 1 }); },+ /** Runs the mirror until it settles (after its recovery it requeues to finish its scan). */+ settle: async () => {+ for (let pass = 0; pass < 5; pass++) {+ await only(); await runPersistenceEffects(engine, config, { hostId, limit: 1 });+ const [left] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_effects WHERE id=$1 AND (recovery IS NOT NULL OR state IN ('queued','running'))", [effect!.id]);+ if (!Number(left!.n)) return;+ }+ } };+}++describe('withdrawal-mirror effect recovery blocking a sync', () => {+ test('a recovery that can finish forward is live: not intervention-required, and the drain keeps waiting', async () => {+ for (const [kind, engine] of engines) {+ const f = await crashedMirror(engine);+ expect(await headClaimability(engine, { id: f.head.id, state: 'queued' }, hostId), kind)+ .toMatchObject({ claimable_here: false, blocked_by: { predicate: 'effect_recovery', ids: [f.effectId], intervention: false } });+ let reads = 0;+ const probe = engineStallProbe(engine, f.sourceId), head = probe.head!;+ const result = await runDrain({ governMs: 10, noProgressMs: 60_000, publicationCeilingMs: 60_000, probe: { ...probe, head: async () => { reads++; return head(); } },+ pass: () => new Promise<SyncResult>(resolve => setTimeout(() => resolve(done), 400)) });+ expect(reads, kind).toBeGreaterThanOrEqual(3);+ expect(result.drain, kind).toMatchObject({ outcome: 'synced' });+ await f.settle();+ expect(await headClaimability(engine, { id: f.head.id, state: 'queued' }, hostId), kind).toEqual({ claimable_here: true, blocked_by: null });+ }+ }, 60_000);++ test('a file edited during the mirror stops the sync at once with a coded fix naming the file; restoring the file clears it', async () => {+ for (const [kind, engine] of engines) {+ const f = await crashedMirror(engine);+ writeFileSync(f.file, EDIT);+ await f.recover();+ expect(readFileSync(f.file, 'utf8'), kind).toBe(EDIT);+ const [effect] = await engine.executeRaw<{ error_code: string | null; recovering: boolean }>('SELECT error_code, recovery IS NOT NULL AS recovering FROM persistence_effects WHERE id=$1', [f.effectId]);+ expect(effect, kind).toMatchObject({ error_code: 'unexpected_file_bytes', recovering: true });++ const started = Date.now();+ const result = await runDrain({ governMs: 20, noProgressMs: 10_000, publicationCeilingMs: 60_000, probe: engineStallProbe(engine, f.sourceId),+ pass: () => new Promise<SyncResult>(() => undefined) });+ const elapsed = Date.now() - started;+ expect(result.drain, kind).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'head_blocked', in_pass: true, head_request_id: f.head.id,+ claimable_here: false, blocked_by: { predicate: 'effect_recovery', ids: [f.effectId], state: 'unexpected_file_bytes', intervention: true, file: { slug: f.slug, path: f.file } } } });+ expect(elapsed, kind).toBeLessThan(5_000);+ const resume = `gbrain sync --source ${f.sourceId}`;+ const next = drainNext(result, resume, f.sourceId)!;+ expect(next, kind).toMatchObject({ code: 'drain_stalled', cause: 'head_blocked', safe_to_loop: false, docs: 'docs/guides/write-refusals.md#head-blocked',+ fix: { actor: 'user', next: 'tell_user_to_run', argv: ['gbrain', 'sources', 'writer', 'status', '--source', f.sourceId, '--json'] } });+ expect(next.why, kind).toContain(f.file);+ expect(next.fix!.user_message, kind).toContain(f.file);+ expect(next.fix!.user_message, kind).toContain(resume);+ expect(formatDrainSummary(result, resume, f.sourceId).join('\n'), kind).toContain(`blocked_by=effect_recovery(unexpected_file_bytes ${f.effectId})`);+ const status = await readWriterDiagnostics(engine);+ const row = (status.blockers as Array<Record<string, unknown>>).find(b => b.request_id === f.head.request_id)!;+ expect(row, kind).toMatchObject({ claimable_here: false, blocked_by: { predicate: 'effect_recovery', intervention: true } });+ expect(String(row.next_action), kind).toContain(f.file);++ // The file back on a recorded version: the recovery can finish forward again, so the head is live before the next retry runs.+ writeFileSync(f.file, f.published);+ expect(await headClaimability(engine, { id: f.head.id, state: 'queued' }, hostId), kind)+ .toMatchObject({ claimable_here: false, blocked_by: { predicate: 'effect_recovery', intervention: false } });+ await f.settle();+ expect(readFileSync(f.file, 'utf8'), kind).toBe(f.published);+ expect(await headClaimability(engine, { id: f.head.id, state: 'queued' }, hostId), kind).toEqual({ claimable_here: true, blocked_by: null });+ }+ }, 120_000);+});