Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-130 PR 2: re-arm targets withheld behind a mirror when it commits; Git commits a passed page only on its raw bytes
garrytan477290f2acd2
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex e3b7bca716..0563152d15 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -38,7 +38,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`. `pollCommand` (#6255) renders the envelope's receipt `fix.argv` (`gbrain write-request --brain <id> -- <request_id>`), else pins that argv to the CLI routing; each argument is shell-quoted (`src/core/shell-quote.ts`, fix wave 13 P1.15).- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits), transient database failures and raw errors `classifyItemFailure` calls run-scoped (a lost connection, a failed transaction, an abort, a full disk) do not count). A `links` or `facts-backstop` effect counts its failures the same way (`data.target_failures`, no target; run-scoped failures, including run-scoped refusal codes, never count, and a 57014 counts as `statement_timeout`): at five a links effect completes as skipped with the code (`outcome: { links: 'skipped', reason }`; the edges are derived and `gbrain extract --stale` recovers them) and a facts-backstop effect fails with it; a pass's counted failures settle when the pass ends under an `ItemRun` (`effects.derived_retry_budget`), and a pass where most of them failed counts none (each retries as `item_failures_systemic`) (GBRA-130 A-11, `test/pathological/a11-effect-retry-budget.test.ts`). An embedding scan (a withdrawal's exact targets or a source scan) parks the page whose provider call keeps failing once its per-page budget (`MAX_RATE_LIMIT_RETRIES`) is spent, with the failure's code, and moves on with a fresh budget; provider throttling (`isEmbedRetriableError`), configuration, budget and disabled errors and run-scoped failures stay effect-wide (A-13, `a13-embedding-target-park.test.ts`): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Both claim queries hold a request's Git and embedding effects only while its withdrawal mirror is queued or running; each Git or embedding attempt rereads its mirror (`mirrorGates`, every mirror not committed plus a committed one that recorded its publications): a mirror queued or running again (retry-effects after the claim) makes the attempt wait (`withdrawal_mirror_pending`); otherwise the attempt touches only the pages whose file the mirror's recovery recorded rewriting (`data.published`, never its cursor), Git skips a page the mirror passed without rewriting (`withdrawal_not_mirrored`: a drifted, missing or segmented file is never committed), and behind a failed mirror every other page, including a single-file Git effect's page in a coalesced group, is parked with `withdrawal_mirror_failed`, so Git never commits a file that may still hold withdrawn text. Lifecycle settlement (`topology-locks.ts`) waits on a queued mirror, not a failed one (A-12, `a12-withdrawal-mirror-gate.test.ts`). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); it also covers parked embedding targets, failed Git, withdrawal-mirror, links and facts-backstop effects without parked targets (one more attempt; a mirror that failed `source_changed` reruns from its cursor once the source is back) and an embedding effect that failed `source_changed`, so one call reruns a failed mirror and re-arms the pages it withheld; `parkedOnly` keeps the credential-change retry (`retryParkedPushes`) to parked Git and withdrawal effects; tests: `persistence-effect-parking.test.ts`. `repair embedding-effects` skips failed embedding effects with parked targets and zero-norm refusals. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated. Only the writer, holding its writer lock, removes a lock `index-lock-reclaim.ts` proves abandoned (its header lists the proof), with a receipt doctor `parked_effects` reports, then retries the step and the effects that lock parked; otherwise `git_index_stale` carries an `ask_user` fix. Steps run with `GIT_OPTIONAL_LOCKS=0`, an index-scaled deadline (`gitStepTimeoutMs`) and a 10 s SIGTERM grace (#6932).+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits), transient database failures and raw errors `classifyItemFailure` calls run-scoped (a lost connection, a failed transaction, an abort, a full disk) do not count). A `links` or `facts-backstop` effect counts its failures the same way (`data.target_failures`, no target; run-scoped failures, including run-scoped refusal codes, never count, and a 57014 counts as `statement_timeout`): at five a links effect completes as skipped with the code (`outcome: { links: 'skipped', reason }`; the edges are derived and `gbrain extract --stale` recovers them) and a facts-backstop effect fails with it; a pass's counted failures settle when the pass ends under an `ItemRun` (`effects.derived_retry_budget`), and a pass where most of them failed counts none (each retries as `item_failures_systemic`) (GBRA-130 A-11, `test/pathological/a11-effect-retry-budget.test.ts`). An embedding scan (a withdrawal's exact targets or a source scan) parks the page whose provider call keeps failing once its per-page budget (`MAX_RATE_LIMIT_RETRIES`) is spent, with the failure's code, and moves on with a fresh budget; provider throttling (`isEmbedRetriableError`), configuration, budget and disabled errors and run-scoped failures stay effect-wide (A-13, `a13-embedding-target-park.test.ts`): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Both claim queries hold a request's Git and embedding effects only while its withdrawal mirror is queued or running; each Git or embedding attempt rereads its mirror (`mirrorGates`, every mirror not committed plus a committed one that recorded its publications): a mirror queued or running again (retry-effects after the claim) makes the attempt wait (`withdrawal_mirror_pending`); otherwise the mirror's recovery records each page whose file it rewrote (`data.published`) and its cursor is never proof: a Git page walk commits a page the mirror passed only when the file's raw bytes hash-equal the mirror rendering of the current snapshot (the serialization `mirrorPage` writes; this also covers a mirror from before publications were recorded and a published file later reverted by hand) and otherwise skips it (`withdrawal_not_mirrored`), a single-file Git effect needs the recorded publication, embedding behind a failed mirror needs the recorded publication, and behind a failed mirror every other page, including a single-file Git effect's page in a coalesced group, is parked with `withdrawal_mirror_failed`, so Git never commits a file that may still hold withdrawn text. When the mirror commits, the same transaction re-arms its request's Git and embedding targets parked `withdrawal_mirror_failed` (`rearmWithheldTargets`: a scan revisits them through `data.retry_slugs`; other parks stay), and each effect pass repeats it for the requests it touched, so no second retry-effects is needed. Lifecycle settlement (`topology-locks.ts`) waits on a queued mirror, not a failed one (A-12, `a12-withdrawal-mirror-gate.test.ts`). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); it also covers parked embedding targets, failed Git, withdrawal-mirror, links and facts-backstop effects without parked targets (one more attempt; a mirror that failed `source_changed` reruns from its cursor once the source is back) and an embedding effect that failed `source_changed`, so one call reruns a failed mirror and re-arms the pages it withheld; `parkedOnly` keeps the credential-change retry (`retryParkedPushes`) to parked Git and withdrawal effects; tests: `persistence-effect-parking.test.ts`. `repair embedding-effects` skips failed embedding effects with parked targets and zero-norm refusals. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated. Only the writer, holding its writer lock, removes a lock `index-lock-reclaim.ts` proves abandoned (its header lists the proof), with a receipt doctor `parked_effects` reports, then retries the step and the effects that lock parked; otherwise `git_index_stale` carries an `ask_user` fix. Steps run with `GIT_OPTIONAL_LOCKS=0`, an index-scaled deadline (`gitStepTimeoutMs`) and a 10 s SIGTERM grace (#6932).- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as do `takes_remove` and `takes_rebuild` (`LOCAL_CLI_LOCAL_ONLY_OPS`) for the `local_cli` principal (write scope still checked; `gbrain takes remove` and `gbrain takes rebuild` defer their engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 1cb88da5b7..86d4e0ff02 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3884,7 +3884,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A page's Git or embedding work is withheld because its withdrawal mirror failed before rewriting the page's file; the file may still hold the withdrawn text. | A withdrawal's Git and embedding effects touch only the pages whose file its mirror recorded rewriting (GBRA-130 A-12); Git never commits a page the mirror passed without rewriting its file. Retrying the request's effects reruns the mirror for this page and re-arms the withheld work once the mirror commits it. | Read the parked effects with gbrain doctor --only parked_effects, fix the cause the mirror recorded, then preview gbrain sources writer retry-effects <source> --request-id <id> --dry-run and run it without --dry-run. | agent | `gbrain doctor --json` | 1 | no |+| A page's Git or embedding work is withheld because its withdrawal mirror failed before rewriting the page's file; the file may still hold the withdrawn text. | A withdrawal's Git and embedding effects touch only the pages whose file its mirror recorded rewriting (GBRA-130 A-12); Git never commits a page the mirror passed without rewriting its file. Retrying the request's effects reruns the mirror for this page; once the mirror commits, the withheld work is re-armed automatically. | Read the parked effects with gbrain doctor --only parked_effects, fix the cause the mirror recorded, then preview gbrain sources writer retry-effects <source> --request-id <id> --dry-run and run it without --dry-run. | agent | `gbrain doctor --json` | 1 | no |### withdrawal_mirror_pendingdiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 687829366d..1842b4b3d7 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -653,7 +653,7 @@ export const CODES = {upstream: { class: 'retryable', summary: "Google connect credential error: upstream.", docs: 'docs/guides/google-connect.md#troubleshooting' },verification_failed: { class: 'server', summary: "Source content or relationships changed during verification." },withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },- withdrawal_mirror_failed: { class: 'unavailable', summary: "A page's Git or embedding work is withheld because its withdrawal mirror failed before rewriting the page's file; the file may still hold the withdrawn text.", why: "A withdrawal's Git and embedding effects touch only the pages whose file its mirror recorded rewriting (GBRA-130 A-12); Git never commits a page the mirror passed without rewriting its file. Retrying the request's effects reruns the mirror for this page and re-arms the withheld work once the mirror commits it.", suggestion: 'Read the parked effects with gbrain doctor --only parked_effects, fix the cause the mirror recorded, then preview gbrain sources writer retry-effects <source> --request-id <id> --dry-run and run it without --dry-run.' },+ withdrawal_mirror_failed: { class: 'unavailable', summary: "A page's Git or embedding work is withheld because its withdrawal mirror failed before rewriting the page's file; the file may still hold the withdrawn text.", why: "A withdrawal's Git and embedding effects touch only the pages whose file its mirror recorded rewriting (GBRA-130 A-12); Git never commits a page the mirror passed without rewriting its file. Retrying the request's effects reruns the mirror for this page; once the mirror commits, the withheld work is re-armed automatically.", suggestion: 'Read the parked effects with gbrain doctor --only parked_effects, fix the cause the mirror recorded, then preview gbrain sources writer retry-effects <source> --request-id <id> --dry-run and run it without --dry-run.' },withdrawal_mirror_pending: { class: 'retryable', summary: "A page's Git or embedding work is waiting because its withdrawal mirror is queued or running again (for example after retry-effects).", why: "Git and embedding work behind a withdrawal mirror touches only the pages the mirror recorded rewriting (GBRA-130 A-12); while the mirror runs, the effect worker releases the work and picks it up once the mirror settles.", suggestion: 'Nothing needs resubmitting; read the effects with gbrain sources writer status <source> --json and wait for the mirror to finish.' },withdrawal_provenance: { class: 'server', summary: "The withdrawal target manifest is invalid." },write_capacity_backpressure: { class: 'host_only', retryable: false, summary: "A background producer (maintenance, conversation facts, an autopilot phase or an autopilot catch-up sync) stopped admitting writes because a cumulative write cap is past `persistence.capacity.background_pause_pct` (default 80); interactive writes keep the rest. Nothing was submitted and no receipt was written.", why: "Near a cumulative cap the remaining request ids and receipt bytes are kept for the user's own writes (remember, put_page, edit_page, operator sync, approved repair). Request ids are never freed, so past the line on ids only the brain host's config raise resumes background work; receipt bytes also free as receipts compact.", docs: 'docs/guides/write-refusals.md#write_capacity_backpressure', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Names the cap past the pause line, its days left and the reversible config raise, read-only.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } }, exit: 12 },diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex 04e33efe7c..e5088401ad 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -6,7 +6,7 @@ import { opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { PreparedMutation } from './coordinator.ts';import { fileContentHash } from './large-file.ts';-import { PARK_AFTER_FAILURES, REMOTE_AUTO_LINKS_KEY, REMOTE_MENTION_OPERATIONS, type EffectKind, type PersistenceEffect, type EffectRequest } from './effect-model.ts';+import { PARK_AFTER_FAILURES, REMOTE_AUTO_LINKS_KEY, REMOTE_MENTION_OPERATIONS, WITHHELD_BY_MIRROR, type EffectKind, type PersistenceEffect, type EffectRequest } from './effect-model.ts';import type { SqlEngine, WriteRequest } from './model.ts';import { recordChronicleDecision } from '../chronicle/ledger.ts';import { isFactsExtractionEnabled } from '../facts/extract.ts';@@ -179,6 +179,36 @@ export async function mirrorGates(engine: SqlEngine, requestIds: readonly string}));}+/**+ * GBRA-130 A-12: once a request's withdrawal mirror has committed, the Git and+ * embedding targets parked behind it (`withdrawal_mirror_failed`) get another+ * attempt with no operator retry: a scan revisits them first+ * (`data.retry_slugs`), a single-target effect runs again. Other parked targets+ * stay parked, and a claimed effect is left to its claim. The mirror's commit+ * calls this in its own transaction; each effect pass calls it again for the+ * requests it touched, for a park that settled after a concurrent mirror commit.+ */+export async function rearmWithheldTargets(engine: SqlEngine, requestIds: readonly string[]): Promise<number> {+ if (!requestIds.length) return 0;+ const rows = await engine.executeRaw<PersistenceEffect>(`SELECT e.* FROM persistence_effects e WHERE e.request_id=ANY($1::uuid[])+ AND e.kind IN ('git','embedding') AND e.state IN ('queued','failed') AND e.execution_token IS NULL AND e.recovery IS NULL+ AND EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(e.data->'parked','[]'::jsonb)) AS p(target) WHERE p.target->>'error_code'=$2)+ AND EXISTS (SELECT 1 FROM persistence_effects m WHERE m.request_id=e.request_id AND m.kind='withdrawal-mirror' AND m.state='committed')+ ORDER BY e.id FOR UPDATE OF e SKIP LOCKED`, [[...new Set(requestIds)], WITHHELD_BY_MIRROR]);+ for (const effect of rows) {+ const { parked = [], ...data } = effect.data;+ const kept = parked.filter(entry => entry.error_code !== WITHHELD_BY_MIRROR);+ const scanning = data.targets !== undefined || data.source_scan === true;+ const slugs = scanning ? parked.flatMap(entry => entry.error_code === WITHHELD_BY_MIRROR && entry.slug ? [entry.slug] : []) : [];+ const retrying = [...new Set([...(data.retry_slugs ?? []), ...slugs])];+ await engine.executeRaw(`UPDATE persistence_effects SET state='queued',data=$2::text::jsonb,error_code=NULL,claim_expires_at=NULL,+ next_attempt_at=now(),updated_at=now() WHERE id=$1 AND execution_token IS NULL AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE}`,+ [effect.id, JSON.stringify({ ...data, ...(kept.length ? { parked: kept } : {}), ...(retrying.length ? { retry_slugs: retrying } : {}),+ ...(effect.kind === 'embedding' ? { embedding_attempt_base: effect.attempts } : {}) })]);+ }+ return rows.length;+}+/*** #5530: claim up to `limit` more ready single-file Git effects for one* worktree, under the same readiness, recovery and withdrawal-mirror orderingdiff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.tsindex 6a9e7f1a91..6e006bb609 100644--- a/src/core/persistence/effect-model.ts+++ b/src/core/persistence/effect-model.ts@@ -30,6 +30,8 @@ export function contentRepairCommit(path: string, receipt: Pick<ContentRepairRec}export interface ParkedTarget { slug?: string; error_code: string }export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' | 'page_body_segmented' | 'withdrawal_not_mirrored' }+/** The code a page behind a failed withdrawal mirror is parked with: its file may still hold the withdrawn text. */+export const WITHHELD_BY_MIRROR = 'withdrawal_mirror_failed';/** A Git or withdrawal target parks after this many consecutive execution failures. */export const PARK_AFTER_FAILURES = 5;export interface EffectRecovery {diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex 289cd06e22..22d08d1cd4 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -34,7 +34,7 @@ import { persistenceFileHash, transientDatabaseFailure } from './coordinator.ts'import { sha256 } from './digest.ts';import { prepareFileTarget } from './page-prepare.ts';import { isSourceDbOnlySlug } from './source-storage.ts';-import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, failEffect, mirrorGates, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect, type MirrorGate } from './effect-journal.ts';+import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, failEffect, mirrorGates, parkEffect, rearmWithheldTargets, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect, type MirrorGate } from './effect-journal.ts';import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';import { commitGitTargets, DURABILITY_NOT_ENABLED, publishGitEffect, pushGitRoot, type GitEffectOwner } from './effect-git.ts';import { retryIndexLockParks } from './effect-retry.ts';@@ -42,7 +42,8 @@ import { gitDurabilityPolicy } from './git-durability-policy.ts';import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';import { dispatchFactsBackstopEffect } from './effect-facts.ts';import { runLinksEffect } from './effect-links.ts';-import { PARK_AFTER_FAILURES, type EffectRecovery, type GitCommitNote, type PersistenceEffect, type SkippedTarget } from './effect-model.ts';+import { PARK_AFTER_FAILURES, WITHHELD_BY_MIRROR, type EffectRecovery, type GitCommitNote, type PersistenceEffect, type SkippedTarget } from './effect-model.ts';+import { fileContentHash } from './large-file.ts';import { isSyncMetafile } from '../sync.ts';import { recoveryStagingFile } from './staging.ts';import { selectEffectRecoveries } from './effect-recovery-scan.ts';@@ -176,31 +177,40 @@ interface EffectAttempt {gate?: MirrorGate;}-/** The code a page behind a failed withdrawal mirror is parked with: its file may still hold the withdrawn text. */-export const WITHHELD_BY_MIRROR = 'withdrawal_mirror_failed';+export { WITHHELD_BY_MIRROR };/** The code a Git or embedding attempt waits with while its request's withdrawal mirror is queued or running again. */export const MIRROR_PENDING = 'withdrawal_mirror_pending';/**- * GBRA-130 A-12: Git and embedding work behind a withdrawal mirror touches only- * pages the mirror published. While the mirror runs again the attempt waits; a- * page the mirror passed without rewriting its file is never committed to Git- * (`skip`), since the mirror will not revisit it; behind a failed mirror any- * other page is parked. True when the page was not worked on.+ * GBRA-130 A-12: whether Git or embedding work may touch a page behind its+ * request's withdrawal mirror. `handled`: the attempt waited (the mirror is+ * queued or running again) or the page was parked behind a failed mirror.+ * `evidence`: a page the mirror passed, which a Git page walk commits only when+ * the file's raw bytes are the mirror's rendering of the current snapshot (the+ * same serialization mirrorPage writes; a recorded publication is not enough:+ * the file may since have been reverted, and a mirror from before publications+ * were recorded has none); a single-file effect, whose file already holds+ * exactly the bytes its request published, needs the recorded publication. Embedding needs a recorded+ * publication behind a failed mirror.*/-async function withheldByMirror(engine: BrainEngine, effect: PersistenceEffect, attempt: EffectAttempt, slug: string, skip?: () => Promise<void>): Promise<boolean> {+async function mirrorVerdict(engine: BrainEngine, effect: PersistenceEffect, attempt: EffectAttempt, slug: string): Promise<'go' | 'evidence' | 'handled'> {const gate = attempt.gate;- if (!gate || gate.published.has(slug)) return false;- if (gate.state === 'pending') { await retryEffect(engine, effect, MIRROR_PENDING); return true; }- if (skip && gate.passed.has(slug)) { await skip(); return true; }- if (gate.state === 'committed') return false;+ if (!gate) return 'go';+ if (gate.state === 'pending') { await retryEffect(engine, effect, MIRROR_PENDING); return 'handled'; }+ if (effect.kind === 'git' && (gate.published.has(slug) || gate.passed.has(slug))) return 'evidence';+ if (gate.published.has(slug) || gate.state === 'committed') return 'go';await parkEffectTarget(engine, effect, WITHHELD_BY_MIRROR, slug);- return true;+ return 'handled';}++async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions, attempt: EffectAttempt): Promise<void> {const snapshot = await selectedEffectPage(engine, effect);- if (!snapshot) { await completeEffect(engine, effect); return; }+ if (!snapshot) {+ await engine.transaction(async tx => { await completeEffect(tx, effect); await rearmWithheldTargets(tx, [effect.request_id]); });+ return;+ }attempt.target = snapshot.page.slug;if (snapshot.sourceIncarnation !== effect.source_incarnation) throw opError('source_changed', 'The mirror source was replaced.',`Source ${effect.source_id} was replaced after this withdrawal mirror was queued, so the effect ends without writing; the new source has its own effects. Check the owner if files still look stale.`,@@ -243,13 +253,18 @@ async function singleFileGitTarget(engine: BrainEngine, effect: PersistenceEffec`The Git effect queued by request ${effect.request_id} in source ${effect.source_id} has no recorded file path, so nothing was committed to Git; the page write itself is committed. Inspect the owner's effects before resubmitting anything.`,{ fix: effectStatusFix(effect) });attempt.target = effect.data.slug ?? effect.data.relative_path;- if (await withheldByMirror(engine, effect, attempt, attempt.target,- () => completeEffect(engine, effect, { git: 'skipped', reason: 'withdrawal_not_mirrored' }))) return null;+ const verdict = await mirrorVerdict(engine, effect, attempt, attempt.target);+ if (verdict === 'handled') return null;const sourceRoot = join(binding.local_path, binding.relative_path);let path = join(binding.local_path, effect.data.relative_path);if (!isWriteTargetContained(path, sourceRoot)) throw gitTargetEscaped(effect);path = nativeFileTarget(binding.local_path, path, 'git_target_unsafe');if (persistenceFileHash(path) !== effect.data.expected_hash) { await completeEffect(engine, effect, { git: 'superseded' }); return null; }+ // The file holds exactly the bytes this request published; behind its mirror they also need the mirror's record of rewriting the page.+ if (verdict === 'evidence' && !attempt.gate!.published.has(attempt.target)) {+ await completeEffect(engine, effect, { git: 'skipped', reason: 'withdrawal_not_mirrored' });+ return null;+ }if (!isWriteTargetContained(path, sourceRoot)) throw gitTargetEscaped(effect);// Declared db_only content stays out of Git. Its gitignored local cache file// is invisible to `git status`, so publishing it would be refused as unsafe.@@ -291,13 +306,14 @@ async function publishGitPage(engine: BrainEngine, effect: PersistenceEffect, biconst snapshot = await selectedEffectPage(engine, effect);if (!snapshot) { await completeEffect(engine, effect); return; }attempt.target = snapshot.page.slug;- if (await withheldByMirror(engine, effect, attempt, snapshot.page.slug, () => skipTarget(engine, effect, snapshot, 'withdrawal_not_mirrored'))) return;+ const verdict = await mirrorVerdict(engine, effect, attempt, snapshot.page.slug);+ if (verdict === 'handled') return;if (isMetafilePage(snapshot)) { await skipTarget(engine, effect, snapshot, 'metafile'); return; }if (isSegmentedPage(snapshot.page)) { await skipTarget(engine, effect, snapshot, 'page_body_segmented'); return; }+ const content = snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags);let file: Awaited<ReturnType<typeof prepareFileTarget>>;try {- file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,- snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true });+ file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true });} catch (error) {if (!isFileDatabaseDrift(error)) throw error;await skipTarget(engine, effect, snapshot, 'file_database_drift');@@ -314,6 +330,11 @@ async function publishGitPage(engine: BrainEngine, effect: PersistenceEffect, biawait finishPage(engine, effect, snapshot, { git: 'skipped', reason: 'db_only' });return;}+ // A page the mirror passed is committed only when its raw bytes are the mirror's rendering of the page as it is now.+ if (verdict === 'evidence' && (content === null || persistenceFileHash(path) !== fileContentHash(content))) {+ await skipTarget(engine, effect, snapshot, 'withdrawal_not_mirrored');+ return;+ }const result = await publishGitEffect(root, relative(root, path).split(sep).join('/'), opts.signal, hardened, gitCommitNote(effect), undefined, owner);if (result.reason === 'durability_not_enabled') await completeEffect(engine, effect, result);else await finishPage(engine, effect, snapshot, result);@@ -354,7 +375,7 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Persconst snapshot = await selectedEffectPage(engine, effect);if (!snapshot || snapshot.page.deleted_at) { await finishPage(engine, effect, snapshot); return; }attempt.target = snapshot.page.slug;- if (await withheldByMirror(engine, effect, attempt, snapshot.page.slug)) return;+ if (await mirrorVerdict(engine, effect, attempt, snapshot.page.slug) === 'handled') return;if (!targetedWithdrawalEffect(effect) && !effect.data.source_scan && (snapshot.revision !== effect.revision || snapshot.page.id !== effect.data.page_id)) {await completeEffect(engine, effect, { embedding: 'superseded', reason: 'revision_changed' }); return;}@@ -684,6 +705,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainCtry { return await runEffectPass(engine, config, opts, touched, derived); }finally {await settleDerivedFailures(engine, derived).catch(() => { /* an unsettled claim expires and the effect is claimed again */ });+ await engine.transaction(tx => rearmWithheldTargets(tx, [...touched])).catch(() => { /* idempotent; the next pass touching the request retries it */ });await trueUpRequests(engine, touched).catch(() => { /* idempotent; the next settlement of the request retries it */ });}}diff --git a/test/pathological/a12-withdrawal-mirror-gate.test.ts b/test/pathological/a12-withdrawal-mirror-gate.test.tsindex 3e11b344e6..996c64ec2c 100644--- a/test/pathological/a12-withdrawal-mirror-gate.test.ts+++ b/test/pathological/a12-withdrawal-mirror-gate.test.ts@@ -47,6 +47,13 @@ const breakFile = (root: string, slug = W2) => { rmSync(join(root, `${slug}.md`)const fixFile = (root: string, slug = W2) => { rmSync(join(root, `${slug}.md`), { recursive: true }); git(root, 'checkout', '--', `${slug}.md`); };const actions = (result: Record<string, unknown>) => Object.fromEntries((result.effects as Array<{ kind: string; action: string }>).map(e => [e.kind, e.action]));+/** One claim per pass: only the mirror runs (Git and embedding wait on it) until it ends `state`. */+async function mirrorOnly(engine: BrainEngine, requestId: string, state: 'failed' | 'committed'): Promise<void> {+ for (let pass = 0; pass < 20 && (await effectsOf(engine, requestId))['withdrawal-mirror'].state !== state; pass++) {+ await expectUnitNotAborted(() => drain(engine, 1, { limit: 1 }));+ }+}+async function settleLifecycle(engine: BrainEngine): Promise<number> {const binding = (await getWorktreeBinding(engine, SOURCE, localHostId()))!;const principal = await topologyPrincipal(engine);@@ -144,10 +151,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) {const raw = readFileSync(join(root, `${W1}.md`));writeFileSync(join(root, `${W1}.md`), `${raw}\nAn uncoordinated local edit.\n`);breakFile(root, W3);- // One claim per pass: only the mirror runs (Git and embedding wait on it) until it ends failed.- for (let pass = 0; pass < 20 && (await effectsOf(engine, request.id))['withdrawal-mirror'].state !== 'failed'; pass++) {- await expectUnitNotAborted(() => drain(engine, 1, { limit: 1 }));- }+ await mirrorOnly(engine, request.id, 'failed');const mirror = (await effectsOf(engine, request.id))['withdrawal-mirror'];expect({ state: mirror.state, skipped: mirror.data.skipped, parked: mirror.data.parked?.map((p: { slug: string }) => p.slug) }).toEqual({ state: 'failed', skipped: [{ slug: W1, reason: 'file_database_drift' }], parked: [W3] });@@ -172,6 +176,71 @@ for (const { backend, databaseUrl } of pathologicalArms()) {}, { untracked: [W1] });}, 180_000);+ test('A-12 item: a Git page parked behind the mirror is re-armed when the mirror commits, with no second retry-effects', async () => {+ await withdrawalBrain(databaseUrl, async ({ engine, root, request, ctx }) => {+ const raw = readFileSync(join(root, `${W2}.md`));+ breakFile(root);+ // The other order of the race: the Git attempt reads the failed mirror first, then retry-effects requeues+ // the mirror, so the attempt parks W2 behind it; the mirror then publishes W2 and commits.+ const original = engine.executeRaw;+ const retries: Record<string, string>[] = [];+ engine.executeRaw = (async function (this: BrainEngine, sql: string, params?: unknown[]) {+ const result = await original.call(this, sql, params);+ if (!retries.length && /FROM persistence_effects WHERE kind='withdrawal-mirror'/.test(sql)) {+ const states = Object.fromEntries((await original.call(engine, `SELECT kind,state,data->>'after_slug' AS after FROM persistence_effects WHERE request_id=$1::uuid`,+ [request.id]) as Array<{ kind: string; state: string; after: string | null }>).map(row => [row.kind, `${row.state}:${row.after}`]));+ if (states.git === `running:${W1}` && !states.embedding?.startsWith('running')) {+ rmSync(join(root, `${W2}.md`), { recursive: true }); writeFileSync(join(root, `${W2}.md`), raw);+ retries.push(actions(await retryRequestEffects(engine, SOURCE, request.request_id, false, ctx.config)));+ }+ }+ return result;+ }) as BrainEngine['executeRaw'];+ try { await expectUnitNotAborted(() => drain(engine, 16)); } finally { engine.executeRaw = original; }+ expect(retries.map(retry => retry['withdrawal-mirror'])).toEqual(['retry_queued']);+ expect(committedActiveClaim(root)).toEqual([]);+ const after = await effectsOf(engine, request.id);+ for (const kind of ['withdrawal-mirror', 'git', 'embedding']) expect({ kind, state: after[kind].state, parked: after[kind].data.parked ?? null }).toEqual({ kind, state: 'committed', parked: null });+ expect(committedSinceSeed(root).sort()).toEqual(TARGETS.map(slug => `${slug}.md`));+ expect(await embeddedPages(engine)).toEqual(TARGETS);+ }, { untracked: [W2] });+ }, 180_000);++ test('A-12 item: behind a mirror without a published list, Git commits a passed page whose file holds the mirror rendering and skips one that holds pre-withdrawal bytes', async () => {+ await withdrawalBrain(databaseUrl, async ({ engine, root, request }) => {+ const raw = readFileSync(join(root, `${W3}.md`));+ breakFile(root);+ await mirrorOnly(engine, request.id, 'failed');+ expect((await effectsOf(engine, request.id))['withdrawal-mirror'].data.published).toEqual([W1, W3]);+ // A mirror that failed before it recorded its publications.+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`UPDATE persistence_effects SET data=data-'published' WHERE request_id=$1::uuid AND kind='withdrawal-mirror'`, [request.id]);+ });+ writeFileSync(join(root, `${W3}.md`), raw);+ await expectUnitNotAborted(() => drain(engine, 12));+ expect(committedActiveClaim(root)).toEqual([]);+ expect(committedSinceSeed(root)).toEqual([`${W1}.md`]);+ const git = (await effectsOf(engine, request.id)).git;+ expect({ state: git.state, skipped: git.data.skipped, parked: git.data.parked })+ .toEqual({ state: 'failed', skipped: [{ slug: W3, reason: 'withdrawal_not_mirrored' }], parked: [{ slug: W2, error_code: WITHHELD }] });+ }, { untracked: [W3] });+ }, 180_000);++ test('A-12 item: Git skips a page the mirror published whose file was reverted to its pre-withdrawal bytes', async () => {+ await withdrawalBrain(databaseUrl, async ({ engine, root, request }) => {+ const raw = readFileSync(join(root, `${W1}.md`));+ await mirrorOnly(engine, request.id, 'committed');+ expect((await effectsOf(engine, request.id))['withdrawal-mirror'].data.published).toEqual(TARGETS);+ writeFileSync(join(root, `${W1}.md`), raw);+ await expectUnitNotAborted(() => drain(engine, 12));+ expect(committedActiveClaim(root)).toEqual([]);+ expect(committedSinceSeed(root).sort()).toEqual([`${W2}.md`, `${W3}.md`]);+ const git = (await effectsOf(engine, request.id)).git;+ expect({ state: git.state, skipped: git.data.skipped }).toEqual({ state: 'committed', skipped: [{ slug: W1, reason: 'withdrawal_not_mirrored' }] });+ }, { untracked: [W1] });+ }, 180_000);+test('A-12 item: the coalesced single-file Git claim commits a page behind a failed mirror only when the mirror committed it', async () => {await managedBrain(async ({ engine, ctx, root }) => {const put = (slug: string) => submitPageMutation(ctx, { operation: 'put_page',