Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a checkpoint whose cursor another run replaced is superseded, not failed (#6513)
garrytan1be9234ff212
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex a9c4f758aa..4b908d30f7 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -38,7 +38,8 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks with `identity: 'reservation'` (#5914: it publishes nothing, so a recreated directory whose reservation names the worktree and whose stamp carries the same token releases; a token mismatch refuses), then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.- `src/core/persistence/sync-page-fault.ts` — #6340: a page that moved under a managed catch-up holds the page, not the run. `headCommittedBytes` returns the working-tree bytes of a path when their blob id equals `HEAD:<path>` (sha1 or sha256 by HEAD's id length), so `freezeEntry` imports bytes committed past the pinned target as HEAD has them (the later pin..HEAD diff re-imports them as a no-op; idea and first test from PR #6323, which this supersedes) and `prepareManagedSyncMutation`'s `newerWorkingTree` screen never sees them. `pageChangeProof` is #6194's revision-linked proof usable at freeze time; `pageChangedHold` builds the `concurrent_write` hold for a database page that was edited, deleted or re-bound after enumeration (with the competing request when proven, else `page_revision` + `expected_revision`), `worktreeDirtyHold` the new `worktree_dirty` hold (pinned `blob_oid`, `working_hash`) for uncommitted bytes that match neither the pin nor the page, `pinnedWorktreeConflict` recognizes that receipt and `pageMovedSinceAdmission` a `revision_conflict` receipt whose page really moved (a run-level conflict with the page where it was still blocks). In `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws (`page_identity_changed`, `revision_conflict`, the renamed-source conflict) into holds when holds are on (a page that still holds exactly what the import carries is re-bound to its new revision and passed by the waiver screen; `sync.holds=fail` and company-brain cursors keep the refusals), `holdFailedFenceRequest` converts the two receipts (imports and deletes) through `receiptPageFaultHold`, re-freezes an entry once under a fresh request when its file changed between admission and publication (`fileChangedAfterAdmission`, the `raw_file_changed` receipt: committed bytes then import as HEAD has them, a second change under the re-frozen request is held `worktree_dirty`; `holdUnderGate` takes `refrozen` in place of `hold` and records the conversion as `refrozen`), `convertBlockedCursor` converts a cursor an older release left blocked (re-freezing a dirty file that is committed now), `originFaultHold` holds an entry whose recorded origin no longer identifies the enumerated page (`assertSyncPageOrigin` at freeze), every page-fault hold marks the cursor `overtaken` (#5522: another cursor may have checkpointed this target), and the `--retry-failed` start tries that conversion before rediscovering, so the frozen manifest survives. `writeGitHold` counts `meta.attempts` per re-hold with the same code; `HOLD_ATTEMPTS_NEEDS_HUMAN` (3) turns a page hold into `needs_human`. The run's catch skips the failure ledger for `isRetryableConnError` / statement timeouts. Tests: `test/managed-sync-page-fault-holds.test.ts` (freeze-time DB edit → hold, same content → re-bind, dirty → `worktree_dirty` → commit → import, committed past pin → HEAD bytes, old blocked cursor → in-place conversion with attempts, connection death → no ledger row, same run on relaunch, one extra pass), the updated expectations in `test/persistence-managed-sync.test.ts` and `test/managed-sync-concurrent-write-hold.test.ts`.-- `src/core/persistence/sync-write-diagnostic.ts` — `managedSyncWriteDiagnostic`, the `managedWrite` block of a managed sync result (terminal receipt reason, suggestion with the retry command, the CRLF-only note), moved unchanged out of `sync-run.ts` by #6340.+- `src/core/persistence/sync-write-diagnostic.ts` — `managedSyncWriteDiagnostic`, the `managedWrite` block of a managed sync result (terminal receipt reason, suggestion with the retry command, the CRLF-only note), moved unchanged out of `sync-run.ts` by #6340; `writeWaitOf` / `ManagedSyncWriteWait` (the `writeWait` block) followed in wave 16.+- `src/core/persistence/sync-checkpoint-replaced.ts` — wave 16 (GBRA-79, #6513 comments): a managed-sync checkpoint whose cursor another run of the source replaced is superseded, not failed. `checkpointCursorReplaced` is the classification the shared validator (`sync-prepare.ts` `sourceSyncChecks` consumer) and the checkpoint's final locked compare-and-swap both apply before their own checks: a checkpoint intent whose durable cursor names another `runId` refuses `sync_cursor_replaced` (receipt state `conflict`, through `coordinator.ts` `conflictCode`); a page request whose cursor moved keeps `revision_conflict` (its run re-admits from the current cursor), a same-run index lag keeps `revision_conflict`, a missing manifest keeps `storage_error`. `checkpointSuperseded` recognizes that receipt in `sync-run.ts`: `settleFailedRequest` records no managed-sync failure for it and continues with the winning cursor as it stands (`currentCursor`, the same move the ENG-A7 admission guard makes when the cursor moves under it; the winner's run id, index and manifest are kept, nothing of it is cleared or advanced), and `retryFailedStart` never treats a checkpoint receipt as a page fault. Before, the loser's run recorded the conflict as a `managed-sync-failure` row, doctor reported it, and `--retry-failed` rediscovered from HEAD. Test: `test/managed-sync-checkpoint-replaced.test.ts` (replacement before validation on both engines; replacement from a second Postgres session between validation and the CAS; `--retry-failed` afterwards converts nothing; controls: index lag, missing manifest).- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate; #6518: the newest cursor recorded under the source's *current* incarnation, the only one a current sync can select), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). When no current-incarnation cursor or failure exists but an unfinished cursor stands under an older incarnation, the status is `cursor: null` with `last_error.code: cursor_incarnation_retired` (table row: systemic, `repair`, no human) and `next` is the `gbrain repair managed-sync-orphans --source <id>` preview, never a sync that selects nothing. `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`).- `src/core/persistence/sync-drain.ts` (#6340 additions) — `isConnectionDrop` (a retryable connection error that is not #6329's `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` settle discard; `retry-matcher.ts` now matches `ECONNABORTED`, `ETIMEDOUT` and `EPIPE` beside `ECONNRESET`); `runDrain` reconnects (`DrainInput.reconnect`, `engine.reconnect` from `drainManagedSync`) and retries a dropped pass on `CONNECTION_RETRY_MS` (5/15/45 s), resets the count on every committed page, and after `CONNECTION_STRIKES` drops with no commit between them ends `blocked` / `connection_lost` with `drain.connection { drops, last_error }` (URLs stripped) and the resume command as a loopable `next` (`sync_drain_connection_lost` in the catalogue, `connection_lost` in the registry). `drainManagedSync` takes exactly one extra pass (`drain.extra_pass { from, to }`, counts merged by `mergeExtraPass`) when HEAD moved past the pinned target during a `synced` run, so a live checkout ends at HEAD without looping. Tests: `test/sync-drain-connection.test.ts`. In-pass governor: `src/core/persistence/drain-step.ts` — `runDrain` races every pass against a governor that runs with or without `announce`: the pass gets its own `AbortController`, the governor's head read is bounded (`GOVERN_PROBE_MS`, or the window when shorter), and on a stop the pass signal is aborted with `DrainPassAbandoned` (the pass's `assertActive` / `stampDrainStep` boundaries throw it, so it admits and writes nothing more; `stampDrainStep` does not throw the caller's own cancel, which still banks admitted work) and its late result or rejection is dropped. A head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; `PUBLICATION_CEILING_DEFAULT_MS`) stops `blocked` / `drain_stalled` / `publication_overdue` with `stall.in_pass` and a `next` that says restart (never a promised reclaim); a pass with no commit, no unfinished request and nothing changing for `IN_PASS_NO_PROGRESS_MS` (5 min) stops `no_admission`, an unchanged non-empty head `no_progress` / `owner_missing`; a live preparation is left to its own budget and ceiling. `drain-step.ts` holds the process-local step (`freeze`, `waiver_run`, `admission`, `await_receipt`, stamped in `sync-run.ts`) and the last statement label (`noteDrainSql`, from `waiveNoopRun`). `enterClaimPhase(clock, 'publishing')` stamps `waiting_on: 'publication'`. `drainManagedSync` prints one line when the sync's own pool is a transaction-mode pooler. `sync-waivers.ts` `waiveNoopRun` pipelines at most `WAIVER_PIPELINE_MAX` (64) calls per round trip and sends the next chunk only while the prefix holds. `commands/sync-delegate.ts`: a serve-delegated `no_admission` stop continues once with the CLI's own consumer (`serve_no_admission`); a `publication_overdue` stop is reported as it is. Tests: `test/sync-drain-inpass-stall.test.ts`, `test/sync-drain-no-admission.test.ts`, `test/sync-waivers-chunk.test.ts`.- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). Tests: `test/persistence-manifest-git-scope.test.ts`, `test/hardened-git-filters.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex e6331522b5..ea6578872f 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2813,6 +2813,14 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| Reading or writing durable storage failed. | Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path. | For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json. | host_admin | `gbrain doctor --json` | 1 | no |+### sync_cursor_replaced++<a id="sync_cursor_replaced"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish. | The replacing run (a --retry-failed rediscovery or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict. | Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source. | agent | `repeat the read that failed` | 1 | no |+### sync_in_progress<a id="sync_in_progress"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 22f98dc7cb..75235d2d63 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -89,6 +89,7 @@ a receipt can report has a row here.| `writer_pool_capacity` | `writer_pool_capacity` | The canonical owner has no free publication slot right now; the write stays queued. | Wait and poll the receipt (`gbrain write-request <id>`). If it persists, check `gbrain sources writer status <source>`. || `revision_required` | `revision_required` | The operation must be bound to a revision you reviewed (for example `--if-version` or `expected_revision`), and none was given: a `put_page` of a page that already exists without `expected_revision` reports this since #5385 (earlier releases said `revision_conflict`). | Preview first, then repeat with the revision the preview printed. || `revision_conflict` | `revision_conflict` | The page changed after the revision this write was bound to. Nothing was overwritten. | Re-read the page, merge your change, and save with the new revision. |+| `sync_cursor_replaced` | `sync_cursor_replaced` | A managed sync checkpoint found that another sync run of the same source (a `--retry-failed` rediscovery, a newer sync) replaced the cursor it belongs to, so it had nothing left to publish. The receipt is a conflict; no managed-sync failure is recorded for it, and the run that awaited it goes on with the cursor that now covers the source. | Nothing: let the current sync finish. `gbrain sync status --source <id> --json` shows that cursor. A same-run index lag keeps reporting `revision_conflict`. || <a id="revision-backfill"></a>`revision_backfill_pending` | `revision_backfill_pending` | The page was written before page revisions existed (an upgrade from below schema v150) and the resumable revision backfill has not reached it, so it has no revision to bind to. Its revision reads as `backfill_pending`, never a UUID. Nothing was written. `gbrain doctor` reports the backfill as `revision_backfill` with the pending count and any failed rows by page. | Resume the backfill on the brain host with `gbrain apply-migrations --force-schema` (it prints its progress; `--yes` alone does not resume it once the schema is current). Rows that used all three attempts are no longer retried: run `gbrain repair orphan-children` to preview orphaned child rows and torn page bodies ([orphan children](repair.md#orphan-children)). || `idempotency_conflict` | `idempotency_conflict` | The `request_id` was already used for a different target, content or protocol. | Use a new `request_id` for a different write; reuse an ID only to replay the same write. || <a id="write_pending"></a>`write_pending` | `write_pending` (CLI exit 10) | The write was accepted but has not committed yet. It keeps its request ID and may still commit. The CLI exits 10, not 1; a lost acknowledgment with no receipt is `submission_status: "unknown"` and exits 1. See [CLI exit status for writes](../protocol/MEMORY_VERBS_v1.md#cli-exit-status-for-writes). | Poll `gbrain call get_write_request '{"request_id":"<id>"}'`, or repeat the same command with the same `--request-id` and a longer `--wait <seconds>`. Scripts that only need the write admitted pass `--accept-pending` (or `GBRAIN_ACCEPT_PENDING=1`) to exit 0. |diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 6f940dc26a..acf2392535 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -47,7 +47,7 @@ export interface SyncResult {*/malformedSkipped?: number;/** #5751: unchanged managed working-tree files skipped although a no-op publication cannot resolve their admit reason. */- legacySkips?: { contextualMode: number; canonicalBytes: number }; /** #5984: managed entries advanced without a write (DX-A7), and how a still-unfinished managed write's wait ended (DX-A3). */ waived?: { imports: number; deletes: number }; writeWait?: import('../core/persistence/sync-run.ts').ManagedSyncWriteWait;+ legacySkips?: { contextualMode: number; canonicalBytes: number }; /** #5984: managed entries advanced without a write (DX-A7), and how a still-unfinished managed write's wait ended (DX-A3). */ waived?: { imports: number; deletes: number }; writeWait?: import('../core/persistence/sync-write-diagnostic.ts').ManagedSyncWriteWait;/** Managed sync: files skipped because another origin keeps their slug, and links derived after the checkpoint. */slugCollisions?: import('../core/persistence/sync-discovery.ts').SyncSlugCollision[];fileRefusals?: import('../core/persistence/sync-discovery.ts').SyncFileRefusal[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c8e636ba1e..d26a37d5d4 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -474,6 +474,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.182.0', text: 'With `GBRAIN_EMBEDDING_MULTIMODAL=true`, managed sync now imports image files through the coordinated image importer (OCR text, image vector and `source_path` at import) instead of holding them as `managed_image_sync_unsupported`; existing image holds are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. With it off, images stay held as before.' },{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },// wave 16 (GBRA-79). `since` is provisional at the branch VERSION; the integrator restamps it at the merge slot.+ { since: '0.60.183.0', text: 'A managed sync checkpoint whose cursor another run of the same source replaced (a `--retry-failed` rediscovery or a newer sync) now refuses `sync_cursor_replaced` (receipt state `conflict`) instead of `revision_conflict`, the run that awaited it records no managed-sync failure for it and goes on with the winning cursor, and `--retry-failed` no longer treats the superseded checkpoint as a page fault; `gbrain doctor` stops reporting such a checkpoint as an unresolved sync failure. A same-run index lag still reports `revision_conflict` and a missing manifest `storage_error`.' },{ since: '0.60.183.0', text: 'Managed sync bookkeeping recorded under a source incarnation the source no longer has (a source re-pointed at a new checkout, or removed and added again) is now retirable: `gbrain repair managed-sync-orphans --source <id>` lists such cursor and failure rows as `incarnation_retired` and local ledger rows whose durable failure row is gone as `mirror_only`, and a successful sync prunes a source\'s stale mirror rows. `gbrain doctor` names them with the repair even when no current failure is visible; `gbrain doctor --fast` (no database) now reports mirrored managed rows as `warn` "could not be verified" instead of `fail` (a better fast score is less certainty, not recovery; the engine-backed check stays authoritative), while old unmanaged file failures keep their severity. `gbrain sync status` reports only a cursor a current sync can select: an old-incarnation cursor is `cursor: null` with `last_error.code: cursor_incarnation_retired` and the repair preview as `next`, instead of a resumable cursor whose `next` selected nothing.' },];diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 15c429f44c..a184ee31a8 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -420,6 +420,10 @@ export const CODES = {why: "A repair that changed a file the running sync admits later would make that entry refuse on its raw hash, and a file a write in flight names would be written twice; so the one candidate waits while the rest of the source is repaired. `candidate_in_flight`: the file is named; `busy_set_unreadable`: the busy set could not be read, so every candidate waited.",reasons: ['candidate_in_flight', 'busy_set_unreadable'],suggestion: 'Nothing to do for the repair: the next run reads the file again. To finish the sync now: gbrain sync --source <id> --no-pull.' },+ // wave 16 (GBRA-79) #6513: a managed-sync checkpoint whose cursor another run of the source replaced.+ sync_cursor_replaced: { class: 'caller', summary: "Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish.",+ why: "The replacing run (a --retry-failed rediscovery or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict.",+ suggestion: 'Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source.' },sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull --retry-failed.' },tail_exposure_approval: { class: 'caller', summary: "A fence on a world-visible page has no end marker and prose follows its table; closing it after the last row is safe for the table but makes those lines visible to remote readers, so the content-repair lane previews the close and waits for a hash-bound approval instead of applying it unattended.", why: "Everything after an unpaired begin marker is hidden by the privacy boundary. The repair model read the tail as prose (not rows), so the only judgment left is whether those exact lines may become visible, and that is the user's: the preview prints them and the hash binds them. On a private page nothing new is disclosed and the lane closes the fence by itself.", actor: 'user', docs: 'docs/guides/write-refusals.md#tail_exposure_approval', suggestion: 'Show the user the preview\'s exposed lines (gbrain repair content --source <id> --only <path>, read-only), then run the printed gbrain repair content --source <id> --only <path> --apply --expect <hash> only after they agree; a changed tail invalidates the hash. By hand: add the end marker directly after the last table row and move the trailing text where it belongs, commit, then gbrain sync --source <id> --no-pull.' },take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 3b2e658462..3ecd1b6f1b 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -37,6 +37,7 @@ import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, pubimport { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';+import { SYNC_CURSOR_REPLACED } from './sync-checkpoint-replaced.ts';import { fenceFailureDetail } from '../fence-repair/refusal.ts';import { withdrawalFailureDetail } from '../facts/withdrawal.ts';import { faultPoint, withFaultPoints } from './fault-points.ts';@@ -140,7 +141,7 @@ function requestError(error: unknown): PublicationFailure {if (code === 'revision_backfill_pending' && error instanceof Error) return { code, message: error.message };return ownerExceptionFailure(error);}-function conflictCode(code: string): boolean { return ['revision_required','revision_conflict','revision_backfill_pending','source_changed','page_identity_changed'].includes(code); }+function conflictCode(code: string): boolean { return ['revision_required','revision_conflict','revision_backfill_pending','source_changed','page_identity_changed',SYNC_CURSOR_REPLACED].includes(code); }export function transientDatabaseFailure(error: unknown): boolean {return ['40001','40P01','55P03','57014','53300','57P01','57P02','57P03','08000','08003','08006','08001','08004','ECONNRESET','ECONNREFUSED','ETIMEDOUT','CONNECTION_CLOSED','CONNECTION_ENDED'].includes(String((error as {code?:string})?.code));diff --git a/src/core/persistence/sync-checkpoint-replaced.ts b/src/core/persistence/sync-checkpoint-replaced.tsnew file mode 100644index 0000000000..56730d26c7--- /dev/null+++ b/src/core/persistence/sync-checkpoint-replaced.ts@@ -0,0 +1,27 @@+/**+ * #6513 (wave 16 G3.4): a managed-sync checkpoint whose cursor another run of the same source replaced.+ *+ * The replacing run (`--retry-failed` rediscovery, a newer sync of the source) re-covers the source from its own+ * discovery, so the superseded checkpoint has nothing left to publish: its refusal is `sync_cursor_replaced` (receipt+ * state `conflict`), it records no managed-sync failure, and the run that awaited it goes on with the winning cursor.+ * A same-run index lag keeps `revision_conflict`, a missing manifest keeps `storage_error`, and a page request whose+ * cursor moved keeps its own `revision_conflict` (its run re-admits it from the current cursor).+ */+import type { WriteRequest } from './model.ts';++export const SYNC_CURSOR_REPLACED = 'sync_cursor_replaced';++/**+ * The classification of a checkpoint whose durable cursor names another run: the refusal code with its receipt message+ * and the diagnostic cause. Null when the cursor still belongs to the checkpoint's run, or the request is not a checkpoint.+ */+export function checkpointCursorReplaced(p: { kind: string; runId: string }, cursorRunId: string | null | undefined, sourceId: string): { code: typeof SYNC_CURSOR_REPLACED; message: string; cause: string } | null {+ if (p.kind !== 'managed_sync_checkpoint' || cursorRunId == null || cursorRunId === p.runId) return null;+ return { code: SYNC_CURSOR_REPLACED, message: 'Another sync run replaced the cursor before this checkpoint published.',+ cause: `Another sync run of ${sourceId} replaced the cursor this checkpoint belongs to, so the checkpoint had nothing left to publish; the replacing run covers the source.` };+}++/** The terminal receipt of a checkpoint another run superseded: nothing to record, nothing to convert. */+export function checkpointSuperseded(pending: { intent: { kind: string } }, done: Pick<WriteRequest, 'error_code'>): boolean {+ return pending.intent.kind === 'managed_sync_checkpoint' && done.error_code === SYNC_CURSOR_REPLACED;+}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex ae135fd9ea..443d84eddc 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -38,6 +38,7 @@ import { companyBrainProfile } from '../company-brain/profile.ts';import { companyBrainPolicyFingerprint } from '../company-brain/policy.ts';import { isUnboundSourcePage, UNBOUND_COLLISION_MESSAGE } from './unbound-source.ts';import { checkpointRetryCommand, findIncompleteSyncReceipt } from './checkpoint-validation.ts';+import { checkpointCursorReplaced } from './sync-checkpoint-replaced.ts';import { frontmatterSlugConflictMessage } from './verb-errors.ts';import { chunkerStamp } from '../chunkers/code.ts';import { clearGitHold, countGitHolds, recordSyncImportProvenance } from './sync-holds.ts';@@ -419,6 +420,9 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrasync () => { if (await earlierGroupMemberFailed(tx, row)) throw syncPublicationRefusal('revision_conflict', 'An earlier page of this sync did not commit.', row, p, `Request ${row.request_id} follows a page of the same bulk group that did not commit, so this page must not publish after it.`); },async () => {const cursor = await shared;+ // #6513: a checkpoint whose cursor another run replaced is superseded, not conflicted; a page keeps `revision_conflict`.+ const replaced = checkpointCursorReplaced(p, cursor?.run_id, row.source_id);+ if (replaced) throw syncPublicationRefusal(replaced.code, replaced.message, row, p, replaced.cause);if (cursor && (cursor.run_id !== p.runId || (cursor.request_id !== row.request_id && !cursor.group?.includes(row.request_id) && !(screening?.unsaved && cursor.request_id == null)))) throw syncPublicationRefusal('revision_conflict', 'The accepted sync cursor changed before publication.', row, p,`Another sync run of ${row.source_id} replaced the cursor this request belongs to.`);},@@ -450,6 +454,9 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrif (p.kind === 'managed_sync_checkpoint') return { sourceExclusive: true, observedRevision: null, validate, apply: async tx => {const [cursor] = await tx.executeRaw<{ completed_keys: [{ runId: string; index: number; total: number }] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE", [p.cursorKey]);+ // #6513: validation passed under this run; a replacement that landed since is the same supersession, not an index lag.+ const replaced = checkpointCursorReplaced(p, cursor?.completed_keys[0]?.runId, row.source_id);+ if (replaced) throw syncPublicationRefusal(replaced.code, replaced.message, row, p, replaced.cause);if (!cursor || cursor.completed_keys[0].runId !== p.runId || cursor.completed_keys[0].index !== p.total || cursor.completed_keys[0].total !== p.total) {throw syncPublicationRefusal('revision_conflict', 'The sync cursor is not fully committed.', row, p,`Not every page write of this sync run has committed, so the checkpoint of ${row.source_id} did not advance.`);diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 09d53ca377..ec7b99e29d 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -11,7 +11,7 @@ import { digest, sha256 } from './digest.ts';import { getWriteRequest, admitWriteInTransaction, foregroundPriority, intentDigest, receiptFor } from './journal.ts';import { preparationConfigView } from './config-snapshot.ts';import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';-import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer, type WriteWait } from './service.ts';+import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';import { syncCursorOptions } from './sync-slices.ts';import { isImageFilePath, isMultimodalEnabled } from '../sync.ts';@@ -46,7 +46,8 @@ import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';import { frozenImageIntent, sameImageBytes } from './sync-image.ts';import { fenceReceiptLocation } from '../fence-repair/refusal.ts';-import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';+import { managedSyncWriteDiagnostic, writeWaitOf } from './sync-write-diagnostic.ts';+import { checkpointSuperseded } from './sync-checkpoint-replaced.ts';import { fileChangedAfterAdmission, headCommittedBytes, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';import { faultPoint } from './fault-points.ts';import { pipelined } from '../page-state/transactions.ts';@@ -252,16 +253,6 @@ function waivedCursor(cursor: Cursor, waived: NoopWaiver): Cursor {}/** The rollback signal of an admission whose cursor no longer holds the frozen entry (ENG-A7). */class CursorMoved extends Error {}-/** DX-A3 / ENG-A12: how the wait for a still-unfinished sync write ended, with its request ID kept. */-export type ManagedSyncWriteWait = { status: 'pending'; request_id: string }- | { status: 'blocked'; request_id: string; cause: string; command: string }- | { status: 'read_failed'; request_id: string; reason: string; transient: boolean; sqlstate?: string; attempts: number; message: string; why: string };-function writeWaitOf(wait: WriteWait): ManagedSyncWriteWait {- if (wait.kind === 'blocked') return { status: 'blocked', request_id: wait.request_id, cause: wait.cause, command: wait.command };- if (wait.kind !== 'read_failed') return { status: 'pending', request_id: wait.row.request_id };- const { kind: _kind, row: _row, ...failure } = wait;- return { status: 'read_failed', ...failure };-}async function replaceCursor(engine: BrainEngine, key: string, before: CursorHeader, next: Cursor, assertActive: () => void): Promise<Cursor> {return engine.transaction(async tx => {assertActive();@@ -716,6 +707,8 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;if (converted === 'pending') return { result: result(cursor, 'partial', input.signal?.aborted ? 'timeout' : 'writer_pending') };if (converted && 'tripped' in converted) return { result: breakerResult(converted.tripped, pending, done, remote) };if (converted) { input.assertActive(); return { cursor: converted }; }+ // #6513: a checkpoint another run superseded records nothing; this run goes on with the winning cursor as it stands.+ if (checkpointSuperseded(pending, done)) return { cursor: await currentCursor(engine, key, cursor) };const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',code: done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'), message: done.error_message ?? 'The accepted sync request did not commit.',request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: key,@@ -1180,8 +1173,8 @@ async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: stringconst recorded = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, cursor.runId]);assertActive();if (!((failed && ['failed', 'conflict', 'cancelled'].includes(failed.state)) || (recorded.length && (failed?.state === 'committed' || !failed)))) return null;- // Only the #6340 page faults convert here (a content refusal under --retry-failed keeps its explicit rediscovery).- const pageFault = !!failed && !!cursor.pending && (pinnedWorktreeConflict(failed) || failed.error_code === 'revision_conflict');+ // Only the #6340 page faults convert here (a content refusal under --retry-failed keeps its explicit rediscovery; #6513: a checkpoint is never a page fault).+ const pageFault = !!failed && !!cursor.pending && cursor.pending.intent.kind !== 'managed_sync_checkpoint' && (pinnedWorktreeConflict(failed) || failed.error_code === 'revision_conflict');const screen = pageFault ? await loadSyncScreenRun(input.startupConfig, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote) : null;const converted = screen ? await convertBlockedCursor(engine, cursor, key, assertActive, { ...input.frozenRun, screen, observedAt: cursor.discoveredAt ?? input.runStartedAt }) : cursor;assertActive();diff --git a/src/core/persistence/sync-write-diagnostic.ts b/src/core/persistence/sync-write-diagnostic.tsindex 901390f102..5bc1734df7 100644--- a/src/core/persistence/sync-write-diagnostic.ts+++ b/src/core/persistence/sync-write-diagnostic.ts@@ -1,9 +1,10 @@/*** The `managedWrite` diagnostic of a managed sync result: what a page request's terminal receipt (or its pending state)* means for the operator, with the retry command and, for a pinned-worktree conflict, whether only line endings differ.- * Moved out of `sync-run.ts` unchanged (#6340 kept that module under its size cap).+ * Moved out of `sync-run.ts` unchanged (#6340 kept that module under its size cap; `writeWaitOf` followed for #6513).*/import type { ManagedSyncWriteDiagnostic } from './sync-run.ts';+import type { WriteWait } from './service.ts';import type { SyncCursorOptions, SyncIntent } from './sync-prepare.ts';import type { WriteRequest } from './model.ts';import type { SyncProcessingOptions } from './sync-authority.ts';@@ -44,3 +45,14 @@ export function managedSyncWriteDiagnostic(cursor: { sourceId: string; root: str}return diagnostic;}++/** DX-A3 / ENG-A12: how the wait for a still-unfinished sync write ended, with its request ID kept. */+export type ManagedSyncWriteWait = { status: 'pending'; request_id: string }+ | { status: 'blocked'; request_id: string; cause: string; command: string }+ | { status: 'read_failed'; request_id: string; reason: string; transient: boolean; sqlstate?: string; attempts: number; message: string; why: string };+export function writeWaitOf(wait: WriteWait): ManagedSyncWriteWait {+ if (wait.kind === 'blocked') return { status: 'blocked', request_id: wait.request_id, cause: wait.cause, command: wait.command };+ if (wait.kind !== 'read_failed') return { status: 'pending', request_id: wait.row.request_id };+ const { kind: _kind, row: _row, ...failure } = wait;+ return { status: 'read_failed', ...failure };+}diff --git a/test/managed-sync-checkpoint-replaced.test.ts b/test/managed-sync-checkpoint-replaced.test.tsnew file mode 100644index 0000000000..3f4d81c9b6--- /dev/null+++ b/test/managed-sync-checkpoint-replaced.test.ts@@ -0,0 +1,195 @@+/**+ * Wave 16 G3.4 (#6513 comments, [R11]): a managed sync checkpoint whose cursor+ * another run of the same source replaced is superseded, not failed.+ *+ * Before, a `runId` mismatch at the shared validator (`sync-prepare.ts`,+ * "The accepted sync cursor changed before publication.") and at the final+ * locked CAS ("The sync cursor is not fully committed.") both refused+ * `revision_conflict`; the loser's run then recorded a `managed-sync-failure`+ * row through `settleFailedRequest`, doctor reported it as unresolved, and+ * `--retry-failed` treated it as a page fault. The replacing run re-covers the+ * source from its own discovery, so the loser's checkpoint has nothing left to+ * publish.+ *+ * Contract pinned here, on PGLite and Postgres:+ * - replacement before validation, and between validation and the final CAS,+ * both refuse `sync_cursor_replaced` with receipt state `conflict`;+ * - the awaiting run settles it with no failure row and no ledger mirror+ * row, re-reads the winning cursor as it stands (its run id, index and+ * manifest kept) and finishes it in the same invocation, as the admission+ * path already does when the cursor moves under it; `--retry-failed`+ * afterwards converts nothing;+ * - controls: a same-run index lag keeps `revision_conflict` and is still+ * recorded; a missing manifest keeps `storage_error`.+ * `test/managed-sync-page-fault-holds.test.ts` keeps proving that a real page+ * fault still converts under `--retry-failed`.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { join } from 'node:path';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { loadSyncFailures } from '../src/core/sync-failure-ledger.ts';+import postgres from '#postgres';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-6513-ckpt-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+let postgresUrl: string | undefined;+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; postgresUrl = pg.databaseUrl; }+}, 120_000);+/** A second session on the Postgres arm: what another process's committed replacement looks like to the publishing transaction. */+async function withSideConnection<T>(fn: (side: (sql: string, params: unknown[]) => Promise<unknown>) => Promise<T>): Promise<T> {+ const sql = postgres(postgresUrl!, { max: 1, prepare: false });+ try { return await fn((text, params) => sql.unsafe(text, params as never[])); } finally { await sql.end(); }+}+afterAll(async () => {+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});+const each = (fn: (engine: BrainEngine) => Promise<void>) => withEnv(env, async () => { for (const engine of engines) { rmSync(join(home, 'sync-failures.jsonl'), { force: true }); await fn(engine); } });++async function fixture(engine: BrainEngine) {+ const id = `ckr-${randomUUID().slice(0, 12)}`, root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ for (const name of ['a', 'b']) writeFileSync(join(root, `${name}.md`), `---\ntitle: ${name}\n---\nObservation ${name} for the replaced checkpoint.\n`);+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content');+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true, explicitProcessing: [] } };+}++/** The sync run's admission guard (ENG-A7): the last statement of the transaction that admits the checkpoint request. */+const ADMISSION_GUARD = /pending'->'intent' = \$3::text::jsonb AS same FROM op_checkpoints WHERE op=\$1 AND fingerprint=\$2 FOR SHARE/;+/** The checkpoint apply's locked compare-and-swap, after the shared validator passed. */+const FINAL_CAS = /SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=\$1 FOR UPDATE/;++type Replaced = { key: string; winner: string; winnerRun: string } | null;+/** What `replaceCursor` writes: the same header under a new `runId`, index 0, no pending request, plus the new run's manifest. */+async function replaceCursorRow(run: (sql: string, params: unknown[]) => Promise<unknown>, key: string, oldRun: string): Promise<{ winnerRun: string }> {+ const winnerRun = randomUUID();+ await run("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) SELECT 'managed-sync-manifest',$2,completed_keys FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [oldRun, winnerRun]);+ await run(`UPDATE op_checkpoints SET completed_keys=jsonb_build_array(((completed_keys->0)-'pending'-'group'-'progress') || jsonb_build_object('runId',$2::text,'index',0)),updated_at=now()+ WHERE op='managed-sync' AND fingerprint=$1`, [key, winnerRun]);+ return { winnerRun };+}+/**+ * Another run of the source replaces the cursor under its key while the loser's checkpoint request is in flight.+ * `at: 'validator'`: the replacement commits with the admission of the checkpoint, so the coordinator's shared validator+ * reads the new run (both engines). `at: 'cas'`: the replacement commits on a second connection after validation passed+ * and before the final locked compare-and-swap (Postgres only: PGLite is one session and cannot commit a concurrent+ * write inside another transaction). `at: 'lag'` moves the index back one under the same run and `at: 'manifest'`+ * deletes the run's manifest, both inside the publishing transaction (rolled back with the refusal, which is all the+ * control observes). Each fires once, on the checkpoint only.+ */+function interfere(engine: BrainEngine, at: 'validator' | 'cas' | 'lag' | 'manifest', side?: (sql: string, params: unknown[]) => Promise<unknown>): { restore: () => void; replaced: () => Replaced } {+ const transaction = engine.transaction;+ let replaced: Replaced = null;+ let fired = false;+ const header = (target: BrainEngine, key: string) => target.executeRaw<{ kind: string | null; run_id: string; total: number; text: string }>(+ "SELECT completed_keys->0->'pending'->'intent'->>'kind' AS kind,completed_keys->0->>'runId' AS run_id,(completed_keys->0->>'total')::int AS total,completed_keys::text AS text FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [key]);+ engine.transaction = async function<T>(this: BrainEngine, run: (tx: BrainEngine) => Promise<T>): Promise<T> {+ return transaction.call(this, tx => run(new Proxy(tx, { get(target, property) {+ if (property === 'executeRaw') return async (sql: string, params?: unknown[]) => {+ if (fired) return target.executeRaw(sql, params);+ if (at === 'validator' && ADMISSION_GUARD.test(sql) && (JSON.parse(params![2] as string) as { kind: string }).kind === 'managed_sync_checkpoint') {+ const rows = await target.executeRaw(sql, params);+ fired = true;+ const key = params![1] as string;+ const [head] = await header(target, key);+ const { winnerRun } = await replaceCursorRow((q, p) => target.executeRaw(q, p), key, head!.run_id);+ replaced = { key, winner: (await header(target, key))[0]!.text, winnerRun };+ return rows;+ }+ if (at !== 'validator' && FINAL_CAS.test(sql)) {+ const key = params![0] as string;+ const [head] = await header(target, key);+ if (head?.kind === 'managed_sync_checkpoint') {+ fired = true;+ if (at === 'lag') await target.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,index}',to_jsonb($2::int)) WHERE op='managed-sync' AND fingerprint=$1", [key, head.total - 1]);+ else if (at === 'manifest') await target.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [head.run_id]);+ else {+ const { winnerRun } = await replaceCursorRow(side!, key, head.run_id);+ const [row] = await side!("SELECT completed_keys::text AS winner FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [key]) as Array<{ winner: string }>;+ replaced = { key, winner: row!.winner, winnerRun };+ }+ }+ }+ return target.executeRaw(sql, params);+ };+ const value = Reflect.get(target, property);+ return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine)) as Promise<T>;+ } as BrainEngine['transaction'];+ return { restore: () => { engine.transaction = transaction; }, replaced: () => replaced };+}++const checkpointReceipt = async (engine: BrainEngine, sourceId: string) => engine.executeRaw<{ state: string; error_code: string | null; error_message: string | null; request_id: string }>(+ "SELECT state,error_code,error_message,request_id::text AS request_id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint' ORDER BY sequence", [sourceId]);+const failureRows = async (engine: BrainEngine, key: string) => engine.executeRaw<{ code: string }>("SELECT completed_keys->0->>'code' AS code FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1", [key]);+const lastCommit = async (engine: BrainEngine, sourceId: string) => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]))[0]!.last_commit;++for (const at of ['validator', 'cas'] as const) {+ test(`a checkpoint whose cursor another run replaced ${at === 'validator' ? 'before validation' : 'between validation and the final CAS'} is superseded: conflict receipt, no failure row, winner untouched, next run finishes the winner`, async () => each(async engine => {+ if (at === 'cas' && engine.kind !== 'postgres') return;+ const f = await fixture(engine);+ const scenario = async (side?: (sql: string, params: unknown[]) => Promise<unknown>) => {+ const hook = interfere(engine, at, side);+ try { return { loser: await performManagedSync(engine, f.opts), replaced: hook.replaced() }; } finally { hook.restore(); }+ };+ const { loser, replaced } = at === 'cas' ? await withSideConnection(scenario) : await scenario();+ expect(replaced).not.toBeNull();+ // The loser's receipt: a conflict with the supersession code, never a failure; the same invocation then finished the winner.+ const receipts = await checkpointReceipt(engine, f.id);+ expect(receipts[0]).toMatchObject({ state: 'conflict', error_code: 'sync_cursor_replaced' });+ expect(receipts[0]!.error_message).toContain('replaced the cursor');+ expect(receipts.map(row => row.state)).toEqual(['conflict', 'committed']);+ // No managed-sync failure recorded (durable or mirrored), nothing converted as a page fault, and the run went on with the winning cursor as it stood.+ expect(await failureRows(engine, replaced!.key)).toEqual([]);+ expect(loadSyncFailures().filter(row => row.source_id === f.id)).toEqual([]);+ expect(loser).toMatchObject({ status: 'first_sync', runId: replaced!.winnerRun, added: 2 });+ expect(loser.failures).toBeUndefined();+ expect(loser.managedWrite).toBeUndefined();+ expect(loser.converted_from_failed).toBeUndefined();+ const [winner] = await engine.executeRaw<{ run_id: string; done: boolean | null; index: number }>(+ "SELECT completed_keys->0->>'runId' AS run_id,(completed_keys->0->>'done')::boolean AS done,(completed_keys->0->>'index')::int AS index FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [replaced!.key]);+ expect(winner).toEqual({ run_id: replaced!.winnerRun, done: true, index: 2 });+ expect(await lastCommit(engine, f.id)).toBe(git(f.root, 'rev-parse', 'HEAD'));+ // --retry-failed afterwards has nothing to retry and converts nothing.+ const next = await performManagedSync(engine, { ...f.opts, retryFailed: true });+ expect(next.status).toBe('up_to_date');+ expect(next.converted_from_failed).toBeUndefined();+ expect(await failureRows(engine, replaced!.key)).toEqual([]);+ }), 180_000);+}++test('controls: a same-run index lag keeps revision_conflict and is still recorded; a missing manifest keeps storage_error', async () => each(async engine => {+ for (const [at, code, message] of [['lag', 'revision_conflict', 'not fully committed'], ['manifest', 'storage_error', 'manifest is incomplete']] as const) {+ const f = await fixture(engine);+ const hook = interfere(engine, at);+ let result: Awaited<ReturnType<typeof performManagedSync>>;+ try { result = await performManagedSync(engine, f.opts); } finally { hook.restore(); }+ const [receipt] = await checkpointReceipt(engine, f.id);+ expect({ at, state: receipt!.state, code: receipt!.error_code }).toEqual({ at, state: code === 'revision_conflict' ? 'conflict' : 'failed', code });+ expect(receipt!.error_message).toContain(message);+ expect(result).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code, count: 1 }] });+ const [key] = await engine.executeRaw<{ fingerprint: string }>("SELECT fingerprint FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);+ expect((await failureRows(engine, key!.fingerprint)).map(row => row.code)).toEqual([code]);+ expect(await lastCommit(engine, f.id)).toBeNull();+ }+}), 240_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 9a29b8164b..7fa8b198a5 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -63,6 +63,7 @@ test/managed-sweep-corpus-windows.test.tstest/managed-sweep-refused-window-retry.test.tstest/managed-sweep-timeline.test.tstest/managed-sync-bulk.test.ts+test/managed-sync-checkpoint-replaced.test.tstest/managed-sync-chunker-version.test.tstest/managed-sync-concurrent-write-hold.test.tstest/managed-sync-drain.test.ts