Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a checkpoint whose source checkpoint moved no longer blocks a managed source forever (#6834)
garrytan53fde693be90
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dc34bad465..75fc57a6ab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,41 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.263.0] - 2026-10-16++**A managed source no longer stays blocked forever on a "conflict" with a page that does not exist.** On a managed brain, a sync could end `BLOCKED` with `revision_conflict` on `__managed_sync_checkpoint__`, and every sync after it ended the same way: doctor's `sync_freshness` failed for good, `gbrain sources refresh` refused with `sync_in_progress`, and the printed fix said to read a page that `gbrain get` cannot find (#6834). That slug is the sync's own bookkeeping, not a page. The refusal meant another run (in practice an older gbrain, which kept one cursor per writer and option set, so two cursors of one source could race) had already moved the source's commit checkpoint, so this run's checkpoint could never publish. Now a run whose source already stands at its target finishes on the next plain sync, and one whose source moved anywhere else is named by doctor with a preview-first repair. No page content was ever at risk.++### What you'd see++| Situation | Before | Now |+|---|---|---|+| The source's `last_commit` already equals the stuck run's target (the usual case: two cursors raced to the same commit) | every sync: `Sync BLOCKED ... revision_conflict ... slug: "__managed_sync_checkpoint__"` | the next plain sync finishes the run (`synced`) and clears the failure |+| `last_commit` moved to some other commit | blocked forever; every repair channel reported nothing to repair | still blocked, but `gbrain repair managed-sync-orphans --source <id>` lists the cursor as `checkpoint_moved`; after its apply the next sync discovers from the recorded commit. Doctor `sync_failures` and `sync_freshness` name that repair as their fix |+| The receipt's fix (`gbrain sync` output, `gbrain write-request`) | "Read the current page and review the intended change" | reason `sync_checkpoint_moved`: bookkeeping, not a page, and the step that finishes or retires the run |+| The terminal-failure action for the refused checkpoint receipt | `gbrain get --source <id> -- __managed_sync_checkpoint__` (page_not_found) | `gbrain sync status --source <id> --json`; a later committed checkpoint of the source supersedes the receipt |+| A fact-extraction batch refused on `__managed_facts_complete__` ("Some extracted facts have not committed.") | "Read the current page ..." | reason `facts_batch_incomplete`: the batch's completion record, not a page; the facts that committed stay, and the action inspects the receipt |++### If a source is stuck now++On this release: run `gbrain sync --source <id> --no-pull`. If it still ends blocked on `__managed_sync_checkpoint__`, preview and apply the repair doctor names:++```bash+gbrain repair managed-sync-orphans --source <id> # preview: lists the cursor as checkpoint_moved; writes nothing+gbrain repair managed-sync-orphans --source <id> --apply --expect <hash>+gbrain sync --source <id> --no-pull # discovers from the source's recorded commit+```++On v0.60.255.0 through v0.60.262.0 (one cursor per source): `gbrain sync --source <id> --no-pull --retry-failed`, with the options the stuck run used (`resume_argv` in `gbrain sync status --source <id> --json`), rediscovers from the recorded commit and unblocks the source. On older releases, where a writer's sync reads only its own cursor, upgrade first.++### Itemized changes++- **Checkpoint at its target (#6834).** A managed-sync checkpoint refused "The source checkpoint changed during this sync." whose source now records exactly the run's target is revived marked overtaken (the #5522 rule the publication already applies), within the existing per-invocation revival bound. A checkpoint moved to any other commit stays refused: publishing it would move the source's commit backwards or past work nobody imported.+- **`checkpoint_moved` orphans (#6834).** `classifyManagedSyncOrphans` lists an unfinished cursor whose checkpoint is that refusal, whose pages all committed, whose source records a commit other than the run's start and target, and with no open or recovering request under its key. `retireManagedSyncOrphan` re-checks the same rule in the delete, so a cursor whose source reached its target after the preview is kept (`no_longer_orphaned`) and the next sync finishes it. Bookkeeping rows only (`op_checkpoints`); no page or file changes, nothing at upgrade.+- **Doctor (#6834).** `sync_failures` sets `fix` to `gbrain repair managed-sync-orphans [--source <id>]` whenever it lists orphans. `sync_freshness` sets the same `fix` (and names it in the message) for a stale managed source with a `checkpoint_moved` cursor, instead of a plain sync that would block again.+- **Diagnostics (#6834).** `writeFailureDiagnostic` gives the moved-checkpoint and incomplete-fact-batch refusals their own reasons and suggestions. `classifyTerminal` keeps both in `caller_conflict` but with class `systemic` and an action that reads sync status (checkpoint) or the receipt (fact batch), never `gbrain get` on a bookkeeping slug. The supersession rule counts a later committed checkpoint of the source as superseding a refused one. Ordinary page conflicts are unchanged.+- Tests: `test/sync-checkpoint-moved-6834.test.ts` (PGLite and Postgres) builds the race with two older cursor keys, a brain that already carries the refused receipt and failure row, and a checkpoint moved elsewhere; it fails on v0.60.262.0 (every plain sync blocked, no orphan listed, the page fix printed) and passes here.+- No schema change.+## [0.60.262.0] - 2026-10-16**One purged item no longer stops a whole Google sync, a source whose syncs keep dying now says so, and Claude refusals through `claude-cli` stop being retried forever.** If you purged a page that a connector keeps listing (a recurring calendar event whose future occurrences you deleted with `--purge`, while the series stays on the calendar), the next sync that reached it ended there. Every sync after it died the same way, so nothing more from that account was imported: no new mail, contacts or events. And every status surface said the source was fine. Now the purged item is skipped and recorded, as the purge intends, and the rest of the sync goes through. Separately, when Claude refused a prompt under its usage policy through the `claude-cli` model provider, atom extraction counted it as an ordinary error and sent the same page back to the model on every run; it now takes the same bounded give-up path as other providers' refusals.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 1ab0633f71..cb481284db 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -134,7 +134,7 @@ work behind exits 0, so scripts should also check `results[].complete`.| `accepted-takes` | none | Explicit-only, preview-bound. Restores takes that accepting a held strike-through or kind change removed on v0.60.253.0 (`gbrain trust confirm tp<id>` ran a `takes_remove` instead of applying the change). It restores only what the records prove: the accepted proposal, the `takes_remove` receipt bound to it, the page version that receipt archived (the row the accept should have applied) and the reservation row still holding its number. `--apply --expect <hash>` republishes each page with that row through a revision-bound `put_page`. See [accepted takes](#accepted-takes). | `version_missing` (the archived version was pruned), `row_number_in_use` (the number holds a take again), `page_missing`, `fence_unreadable`. A grade or resolution the database alone held is not in any record and is not restored. || `connector-checkpoints` | `connector_checkpoints` | Deletes managed connector checkpoint rows and retry pointers that no registered connector source can load and that are older than 7 days. They accumulate after a content setting such as `g_history_days` changes, or when a connector host older than v0.60.11.0 runs during an upgrade. Cleanup only: it never copies or re-keys a checkpoint, takes no journal admission and runs brain-wide (`--source` does not narrow it). | Rows a queued or running connector write, or a connector's recorded pending set, still references. || `orphan-bindings` | `orphan_persistence_bindings` | Deletes persistence source bindings whose source was removed, or that belong to an earlier incarnation of a source re-added under the same id. `gbrain sources remove` and `gbrain sources purge` delete the binding; one an older gbrain left behind makes the re-added source read as claimed, so every `gbrain sync --source <id>` fails with `writer_coordinator_required`. Bookkeeping only: no journal admission, no page or file changes, and it runs brain-wide (`--source` does not narrow it). See [orphan bindings](#orphan-bindings). | A binding that a queued, running or recovering write request of the same source incarnation still references. |-| `managed-sync-orphans` | `sync_failures` | Explicit-only, preview-bound. Retires managed sync bookkeeping nothing current can resume or clear: a `managed-sync-failure` row whose cursor key has no cursor, and an unfinished `managed-sync` cursor recorded by a principal that is no longer an active local writer (or a pre-options cursor a later run superseded) whose pending request is terminal. `op_checkpoints` rows only; no journal admission, no page or file changes. The preview prints a hash; `--apply --expect <hash>` retires exactly that set. See [managed sync orphans](#managed-sync-orphans). | An unfinished cursor whose pending request is still queued, running or recovering, or one the live writer can resume with its recorded options (doctor prints that sync command). |+| `managed-sync-orphans` | `sync_failures` | Explicit-only, preview-bound. Retires managed sync bookkeeping nothing current can resume or clear: a `managed-sync-failure` row whose cursor key has no cursor, and an unfinished `managed-sync` cursor recorded by a principal that is no longer an active local writer (or a pre-options cursor a later run superseded) whose pending request is terminal, or (#6834) a cursor whose checkpoint can never publish because the source's `last_commit` moved elsewhere (`checkpoint_moved`). `op_checkpoints` rows only; no journal admission, no page or file changes. The preview prints a hash; `--apply --expect <hash>` retires exactly that set. See [managed sync orphans](#managed-sync-orphans). | An unfinished cursor whose pending request is still queued, running or recovering, or one the live writer can resume with its recorded options (doctor prints that sync command). || `stuck-recovery` | none (`gbrain sources writer status` shows the request `recovering` with `unexpected_file_bytes`) | Explicit-only, preview-bound, destructive consent. Resolves a live page publication recovery whose file matches neither its recorded prior nor its published bytes, which stops every write on its worktree. The preview lists each blocked file with both fingerprints and writes a private diff; `--apply --expect <hash> --keep prior\|disk --yes` backs up both versions, then restores the prior (the write publishes again) or keeps the edit and abandons the write. See [stuck recovery](#stuck-recovery). | A terminal request with its recovery still set (listed as refused, `recovery_choice_refused`), a withdrawal-mirror effect recovery (listed as refused, `recovery_effect_unsupported`), a shared-skill bundle recovery (`recovery_bundle_unsupported`), a recovery blocked on staging bytes, and a recovery whose file already matches a recorded version (the resident writer finishes those). || `frontmatter-keys` | `stale_frontmatter_keys` | Explicit-only, preview-bound. Strips the parser's reserved top-level keys (`type`, `title`, `tags`, `slug`) that an older import stored inside `pages.frontmatter`. Since v0.60.176.0 those keys are not file/database drift and never render (#6454), so this is hygiene: database rows only, in source-scoped coordinated batches of up to 1,000 pages, no file, body or embedding change. Each swept page advances its `knowledge_revision` once, so a client holding an older revision of a swept page gets one `revision_conflict` and re-reads. See [frontmatter keys](#frontmatter-keys). | A page whose keys were cleared by a write between preview and apply (`already_clean`). || `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). |@@ -509,6 +509,7 @@ Classes in the preview:| `principal_unadoptable` | an unfinished cursor recorded by a principal that is not an active local writer | the live writer never reads that key, and the pending request is invisible to it || `superseded` | an unfinished cursor from before sync options were recorded, with a later completed run for the same source and incarnation | its exact options are unknown, so no command resumes it || `incarnation_retired` | an unfinished cursor, or a failure row, recorded under a source incarnation the source no longer has (it was re-pointed at a new checkout, or removed and added again) | the cursor key digests the incarnation, so no current sync selects it, and every incarnation-joined reader (doctor's durable read, `--retry-failed`, `--acknowledge-managed`) drops it; only the local ledger mirror still shows it. `gbrain sync status` reports it as `cursor: null` with `last_error.code: cursor_incarnation_retired` |+| `checkpoint_moved` | an unfinished cursor whose pages all committed and whose checkpoint was refused `revision_conflict` "The source checkpoint changed during this sync." because `sources.last_commit` moved to a commit that is neither the run's start nor its target (another run, or an older gbrain sharing the database, checkpointed the source elsewhere) | the checkpoint's compare-and-swap can never succeed, so every plain sync resumes the cursor into the same refusal; its slug `__managed_sync_checkpoint__` is bookkeeping, not a page, so there is nothing to read. After the apply the next sync discovers from the commit the source records. A cursor whose source already stands at its target is not listed: the next plain sync finishes it. The apply keeps the cursor when the rule no longer holds || `mirror_only` | a row of the local ledger (`~/.gbrain/sync-failures.jsonl`) carrying a `managed_cursor_key` with no durable failure row under that key in any incarnation | the mirror is pruned only after a durable delete, so one whose durable row is already gone keeps `gbrain doctor --fast` warning. The apply removes the ledger row after reading the durable rows again; a successful sync of the source prunes its own mirror-only rows too |Kept and counted, never retired: a cursor whose pending request is stilldiff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex 2e9a0d6fa2..e1972eea2e 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -34,7 +34,8 @@ import { isOwnedContentSchemaMissing, ownedContentFreshness } from '../../../corimport { readOnlyCatalogPackSourceIds } from '../../../core/shared-skills/adopted-packs.ts';import { connectorAuthorities } from '../../../core/persistence/connector-authority.ts';import { parseSourceConfig } from '../../../core/sources-load.ts';-import { checkError } from '../check-fix.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { classifyManagedSyncOrphans } from '../../../core/persistence/managed-sync-orphans.ts';import { firstSyncRunning, noSuccessfulSync, stoppedConnectorIssues, type SyncOutcomeEntry } from '../sync-outcome.ts';import { haltReasonsWithUnknown, readRecordedHaltReasons7d, topHaltReason } from '../../../core/extract/rollup-writer.ts';@@ -1311,6 +1312,7 @@ export async function checkSyncFreshness(let managed = false;try { managed = await persistenceEnabledForHealth(engine); } catch { /* pre-persistence brain */ }let upstream_unknown_count = 0, upstream_behind_count = 0;+ const staleIds: string[] = [];const stoppedConnectors = await stoppedConnectorIssues(engine, sources, now - failMs).catch(() => new Map());for (const source of sources) {if (ownedContent.has(source.id)) { writer_owned_count++; continue; }@@ -1467,11 +1469,11 @@ export async function checkSyncFreshness(if (thresholdAgeMs > failMs) {issues.push(`Source ${display} last synced ${ageDays}d ago — brain search is stale!`);hasFailures = true;- stale_count++;+ stale_count++; staleIds.push(source.id);} else if (thresholdAgeMs > warnMs) {issues.push(`Source ${display} last synced ${ageHours}h ago`);hasWarnings = true;- stale_count++;+ stale_count++; staleIds.push(source.id);} else {synced_recently_count++;}@@ -1489,12 +1491,19 @@ export async function checkSyncFreshness(+ (read_only_pack_count ? `. ${read_only_pack_count} read-only skill-pack source(s): no commits to sync` : '') + (catalogPacks.note ? `. ${catalogPacks.note}` : '');const remedy = issues.length > outcomes.length;- const outcomeFix = outcomes.find(o => o.code === 'sync_no_successful_sync')?.fix ?? outcomes[0]?.fix;+ // #6834: a stale managed source whose unfinished cursor no sync can publish (its checkpoint moved elsewhere) is retired, not re-synced.+ const moved = managed && localOnly && staleIds.length ? (await classifyManagedSyncOrphans(engine, staleIds).catch(() => ({ orphans: [] }))).orphans+ .filter(orphan => orphan.reason === 'checkpoint_moved') : [];+ const movedFix = moved.length ? agentFix(['gbrain', 'repair', 'managed-sync-orphans', ...(new Set(moved.map(o => o.source_id)).size === 1 ? ['--source', moved[0]!.source_id] : [])],+ `The unfinished sync of ${[...new Set(moved.map(o => o.source_id))].join(', ')} can never checkpoint (its source's last_commit moved outside the run), so a plain sync stays blocked. The preview lists the cursor and prints the apply command with its hash; writes nothing.`,+ 'sync_freshness', { docs: 'docs/guides/repair.md#managed-sync-orphans' }) : undefined;+ const outcomeFix = outcomes.find(o => o.code === 'sync_no_successful_sync')?.fix ?? outcomes[0]?.fix ?? movedFix;+ const movedNote = movedFix ? `. ${movedFix.why} Run \`${movedFix.argv!.join(' ')}\`` : '';if (hasFailures) {return {name: 'sync_freshness',status: 'fail',- message: `${issues.join('; ')}${remedy ? `. Run \`gbrain sync --source <id>${managed ? ' --no-pull' : ''}\` for each stale source` : ''}${inProgressNote}`,+ message: `${issues.join('; ')}${remedy ? `. Run \`gbrain sync --source <id>${managed ? ' --no-pull' : ''}\` for each stale source` : ''}${movedNote}${inProgressNote}`,details, ...(outcomeFix ? { fix: outcomeFix } : {}),};}@@ -1502,7 +1511,7 @@ export async function checkSyncFreshness(return {name: 'sync_freshness',status: 'warn',- message: `${issues.join('; ')}${remedy ? `. Run \`gbrain sync --source <id>${managed ? ' --no-pull' : ''}\` to refresh` : ''}${inProgressNote}`,+ message: `${issues.join('; ')}${remedy ? `. Run \`gbrain sync --source <id>${managed ? ' --no-pull' : ''}\` to refresh` : ''}${movedNote}${inProgressNote}`,details, ...(outcomeFix ? { fix: outcomeFix } : {}),};}diff --git a/src/commands/doctor/checks/sync-failures.ts b/src/commands/doctor/checks/sync-failures.tsindex 4ee1496a1f..d1d679a769 100644--- a/src/commands/doctor/checks/sync-failures.ts+++ b/src/commands/doctor/checks/sync-failures.ts@@ -7,6 +7,7 @@ import { makeRemediationStep } from '../../../core/remediation-step.ts';import { classifyManagedSyncOrphans, type ManagedSyncOrphan } from '../../../core/persistence/managed-sync-orphans.ts';import { readManagedMode } from '../../../core/persistence/ownership.ts';import { legacyLedgerNote } from '../../../core/persistence/legacy-sync-failures.ts';+import { agentFix } from '../check-fix.ts';/** #6518 [R18 vi]: the fast check cannot verify a mirror row; a warning there is uncertainty, never recovery. */const MIRROR_UNVERIFIED = (count: number) => `${count} mirrored managed sync failure(s) could not be verified without a database connection: `@@ -38,17 +39,20 @@ export async function checkSyncFailures(engine: BrainEngine | null, opts: { sourcatch (error) { orphanReadError = (error as { code?: string })?.code ?? (error instanceof Error ? error.message : String(error)); }}const orphanSources = new Set(orphans.map(orphan => orphan.source_id));- const repairPreview = `gbrain repair managed-sync-orphans${orphanSources.size === 1 ? ` --source ${orphans[0]!.source_id}` : ''}`;+ const repairArgv = ['gbrain', 'repair', 'managed-sync-orphans', ...(orphanSources.size === 1 ? ['--source', orphans[0]!.source_id] : [])];+ const repairPreview = repairArgv.join(' ');const orphanNoteFor = (lead: string) => orphans.length ? ` ${lead} (${orphans.map(orphan => `${orphan.source_id}:${orphan.cursor_key.slice(0, 12)} ${orphan.reason}`).join(', ')}) cannot be resumed or cleared by any sync: `+ `preview ${repairPreview} and apply with the hash it prints (docs/guides/repair.md#managed-sync-orphans). Retiring them says nothing about whether the current source's files are imported; gbrain sync status --source <id> --json does.` : '';const orphanNote = orphanNoteFor(`${orphans.length} of these`);+ const orphanFix = orphans.length && opts.remote === false ? { fix: agentFix(repairArgv, 'Previews the sync bookkeeping no sync can resume or clear (with each row\'s class) and prints the apply command with its hash; writes nothing.', 'sync_failures',+ { docs: 'docs/guides/repair.md#managed-sync-orphans' }) } : {};const remoteOrphanNote = orphans.length ? ` ${orphans.length} managed sync bookkeeping row(s) cannot be resumed or cleared by any sync; ask the host operator to preview gbrain repair managed-sync-orphans.` : '';const unreadNote = orphanReadError ? ` The managed sync bookkeeping could not be classified (${orphanReadError}); this is not proof that none is orphaned. Run gbrain doctor --only sync_failures again with the brain reachable.` : '';if (!severity.unresolved) {if (orphans.length || orphanReadError) {const base = `${entries.length ? 'All historical sync failures are acknowledged.' : 'No current sync failures on active sources.'}`;return { name: 'sync_failures', status: 'warn', message: base + (opts.remote !== false ? remoteOrphanNote + unreadNote : orphanNoteFor(`${orphans.length} managed sync bookkeeping row(s)`) + unreadNote) + archivedNote,- ...(opts.remote === false && orphans.length ? { details: { orphans } } : {}) };+ ...(opts.remote === false && orphans.length ? { details: { orphans } } : {}), ...orphanFix };}if (mirrorRows.length) return { name: 'sync_failures', status: 'warn', message: `No unresolved unmanaged sync failures.${mirrorNote}${archivedNote}` };return entries.length || archivedCount ? { name: 'sync_failures', status: 'ok', message: `${entries.length ? 'All historical sync failures are acknowledged.' : 'No sync failures on active sources.'}${archivedNote}` } : null;@@ -75,6 +79,6 @@ export async function checkSyncFailures(engine: BrainEngine | null, opts: { sour: `Fix the file(s) and re-run 'gbrain sync', or use 'gbrain sync --skip-failed' to acknowledge legacy file failures.${orphanNote}${unreadNote}`;const legacyNote = managedBrain ? legacyLedgerNote(unresolvedLegacy) : '';return { name: 'sync_failures', status: severity.status, message: `${summary} ${details.join('; ')} ${recovery}${legacyNote}`,- remediation, remediation_status: remediation ? 'remediable' : 'blocked', ...(orphans.length ? { details: { orphans } } : {}),+ remediation, remediation_status: remediation ? 'remediable' : 'blocked', ...(orphans.length ? { details: { orphans } } : {}), ...orphanFix,...(engine ? {} : { message: `${summary} Durable sync state is unavailable without a database connection; the local ledger is only a compatibility mirror.${mirrorNote}` }) };}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f650b33340..f80fbccfe8 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -700,6 +700,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.262.0', text: 'A managed Google or GitHub connector item whose content matches a page purge tombstone is now skipped, and the rest of the sync continues (#6831). Before, the pages guard\'s `purged_content` refusal of that one item ended the whole sync job, and every later sync of the source died the same way. Skipped items are listed in `gbrain sources status` ("skipped as purged content"), and `gbrain pages unpurge <slug>` lets one back in. Every other failed connector write still ends the run.' },{ since: '0.60.262.0', text: 'A connector source whose syncs keep ending on an error now says so (#6831): `gbrain sources status` names the error, the item and a read-only next step, and reads STOPPED after 3 failed runs in a row; `gbrain sync status --json` adds `connector_last_error` with that read-only fix; doctor `sync_freshness` warns about a STOPPED source even when its last good sync was recent (fails past the fail age). `last_error`, `state` and `next` are unchanged for connector sources.' },{ since: '0.60.262.0', text: 'A `claude-cli` usage-policy refusal ("API Error: <model> can\'t help with this ... https://www.anthropic.com/legal/aup", and the older "violate our Usage Policy" and "safeguards flagged this" wordings) is now a provider content block (`claude_cli_usage_policy`, #6816): `extract_atoms` tombstones the item after its consecutive-failure limit instead of re-sending it every run, and with `chat_fallback_on_refusal: false` the prompt is not sent on to the next model in `chat_fallback_chain`. Other `claude-cli` errors are unchanged.' },+ // #6834 hotfix. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.262.0', text: 'A managed sync whose checkpoint was refused `revision_conflict` on `__managed_sync_checkpoint__` because the source\'s `last_commit` moved under it (#6834) no longer blocks forever: when the source already records the run\'s target, the next plain `gbrain sync` finishes the run; when it records any other commit, `gbrain repair managed-sync-orphans --source <id>` lists the cursor as `checkpoint_moved` (preview, then `--apply --expect <hash>`) and the next sync discovers from that commit. Doctor `sync_failures` and `sync_freshness` name that repair as their fix, the receipt reason is `sync_checkpoint_moved` (fact batches: `facts_batch_incomplete`) instead of "read the current page", the terminal-failure action reads `gbrain sync status` instead of `gbrain get` on the bookkeeping slug, and a later committed checkpoint supersedes the refused receipt.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex 3d04d7f3d7..dd42eca61d 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -17,6 +17,7 @@ import { authorizePageVisibility } from './page-visibility.ts';import { authorizeFactsBackstop } from './effect-facts.ts';import { getWriteRequestById } from './journal.ts';import { preparePageMutation } from './page-prepare.ts';+import { FACTS_BATCH_INCOMPLETE_MESSAGE } from './verb-errors.ts';import type { PreparedMutation } from './coordinator.ts';import type { WriteRequest } from './model.ts';import type { ManagedFactIntent, FrozenExtractedFact } from './facts-maintenance.ts';@@ -121,7 +122,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writconst children = p.children ?? [];const done = await tx.executeRaw<{ outcome: { inserted?: number; duplicate?: number; fact_ids?: number[]; withdrawn_skipped?: number; would_dedup_same_page?: number } }>(`SELECT outcome FROM persistence_requests WHERE id=ANY($1::uuid[]) AND source_incarnation=$2::uuidAND state='committed' AND COALESCE(intent->>'batchKey',outcome->>'batch_key')=$3 AND operation='extract_facts'`, [children, row.source_incarnation, p.batchKey]);- if (done.length !== children.length) throw factsRefusal('revision_conflict', 'Some extracted facts have not committed.', row,+ if (done.length !== children.length) throw factsRefusal('revision_conflict', FACTS_BATCH_INCOMPLETE_MESSAGE, row,`${children.length - done.length} of the batch's ${children.length} per-entity fact requests have not committed, so the extraction cannot be recorded as complete.`,'once the entity requests are final, run extract_facts again for the same turn with a new request_id only if facts are still missing.');const withdrawnSkipped = done.reduce((sum, item) => sum + Number(item.outcome.withdrawn_skipped ?? 0), 0);diff --git a/src/core/persistence/managed-sync-orphans.ts b/src/core/persistence/managed-sync-orphans.tsindex 1d1d2a3d73..419c8c7371 100644--- a/src/core/persistence/managed-sync-orphans.ts+++ b/src/core/persistence/managed-sync-orphans.ts@@ -21,6 +21,11 @@* incarnation-joined reader (`readManagedSyncFailures`, the two passes above,* the clear paths) drops it; only the local ledger mirror still shows it.* Archived sources are excluded; a live pending request still retains it.+ * - `checkpoint_moved` (#6834): an unfinished cursor whose every page committed and whose checkpoint was refused+ * because `sources.last_commit` moved to a commit that is neither the cursor's start nor its target (another run,+ * or an older binary, checkpointed the source elsewhere). The checkpoint can never publish and no resume clears it;+ * retiring the cursor lets the next sync discover from the commit the source now records. A cursor whose source+ * already stands at its target is not one: the next sync finishes it (sync-slug-mode.ts `checkpointMovedToTarget`).* - `mirror_only` (#6518): a row of the local compatibility ledger* (`~/.gbrain/sync-failures.jsonl`) carrying a `managed_cursor_key` with no* durable `managed-sync-failure` row under that key in any incarnation. The@@ -37,9 +42,10 @@import type { BrainEngine } from '../engine.ts';import type { SqlEngine } from './model.ts';import { clearManagedSyncFailure, loadSyncFailures } from '../sync-failure-ledger.ts';+import { CHECKPOINT_MOVED_MESSAGE } from './sync-slug-mode.ts';/** `superseded_by_adoption` (#6712 PR 1): an unfinished cursor of the incarnation that the drain's fan-in did not adopt (sync-cursor-key.ts). */-export type ManagedSyncOrphanReason = 'no_cursor' | 'principal_unadoptable' | 'superseded' | 'incarnation_retired' | 'mirror_only' | 'superseded_by_adoption';+export type ManagedSyncOrphanReason = 'no_cursor' | 'principal_unadoptable' | 'superseded' | 'incarnation_retired' | 'mirror_only' | 'superseded_by_adoption' | 'checkpoint_moved';export type ManagedSyncOrphanRetained = 'pending_request_live' | 'resumable';export interface ManagedSyncOrphan {@@ -69,9 +75,22 @@ interface CursorRow {cursor_key: string; source_id: string; source_incarnation: string; run_id: string | null;principal_kind: string | null; principal_id: string | null; has_sync_options: boolean;pending_request_id: string | null; pending_state: string | null;- principal_live: boolean; superseded: boolean; updated_at: string;+ principal_live: boolean; superseded: boolean; checkpoint_moved: boolean; updated_at: string;}+/**+ * #6834: the cursor `c` (of source `s`) stands at its checkpoint, which ended refused because `last_commit` moved, and the+ * source now records a commit that is neither the cursor's start nor its target. Shared by the classification and the+ * retirement's re-check, so both read the same rule. `$msg` is the moved-checkpoint message parameter.+ */+const checkpointMovedSql = (msg: string) => `(c.completed_keys->0->'pending'->'intent'->>'kind'='managed_sync_checkpoint'+ AND (c.completed_keys->0->>'index')::int>=(c.completed_keys->0->>'total')::int+ AND s.last_commit IS DISTINCT FROM c.completed_keys->0->>'from' AND s.last_commit IS DISTINCT FROM c.completed_keys->0->>'target'+ AND EXISTS(SELECT 1 FROM persistence_requests m WHERE m.source_id=s.id AND m.request_id=(c.completed_keys->0->'pending'->>'requestId')::uuid+ AND m.state IN ('failed','conflict') AND m.recovery IS NULL AND m.error_code='revision_conflict' AND m.error_message=${msg})+ AND NOT EXISTS(SELECT 1 FROM persistence_requests o WHERE o.source_id=s.id AND o.intent->>'cursorKey'=c.fingerprint+ AND (o.state IN ('queued','running','recovering') OR o.recovery IS NOT NULL)))`;+/** Read-only. `sourceIds` narrows to those sources; null reads every active source. */export async function classifyManagedSyncOrphans(engine: SqlEngine, sourceIds: string[] | null = null): Promise<ManagedSyncOrphanClassification> {const cursors = await engine.executeRaw<CursorRow>(`@@ -86,6 +105,7 @@ export async function classifyManagedSyncOrphans(engine: SqlEngine, sourceIds: sEXISTS(SELECT 1 FROM op_checkpoints n WHERE n.op='managed-sync' AND n.fingerprint<>c.fingerprintAND n.completed_keys->0->>'sourceId'=s.id AND n.completed_keys->0->>'incarnation'=s.incarnation::textAND COALESCE(n.completed_keys->0->>'done','false')='true' AND n.updated_at>c.updated_at) AS superseded,+ ${checkpointMovedSql('$2')} AS checkpoint_moved,to_char(c.updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS updated_atFROM op_checkpoints cJOIN sources s ON s.id=c.completed_keys->0->>'sourceId' AND s.incarnation::text=c.completed_keys->0->>'incarnation' AND NOT COALESCE(s.archived,false)@@ -95,13 +115,14 @@ export async function classifyManagedSyncOrphans(engine: SqlEngine, sourceIds: sAND r.principal_kind=c.completed_keys->0->'authority'->'writer'->'principal'->>'kind'WHERE c.op='managed-sync' AND COALESCE(c.completed_keys->0->>'done','false')<>'true'AND ($1::text[] IS NULL OR s.id=ANY($1::text[]))- ORDER BY s.id,c.updated_at,c.fingerprint`, [sourceIds]);+ ORDER BY s.id,c.updated_at,c.fingerprint`, [sourceIds, CHECKPOINT_MOVED_MESSAGE]);const orphans: ManagedSyncOrphan[] = [];const retained: ManagedSyncOrphanClassification['retained'] = [];for (const row of cursors) {const principal = row.principal_kind && row.principal_id ? { kind: row.principal_kind, id: row.principal_id } : null;if (row.pending_request_id && row.pending_state && !TERMINAL.includes(row.pending_state)) { retained.push({ cursor_key: row.cursor_key, source_id: row.source_id, why: 'pending_request_live' }); continue; }- const reason: ManagedSyncOrphanReason | null = !row.principal_live ? 'principal_unadoptable' : !row.has_sync_options && row.superseded ? 'superseded' : null;+ const reason: ManagedSyncOrphanReason | null = !row.principal_live ? 'principal_unadoptable' : !row.has_sync_options && row.superseded ? 'superseded'+ : row.checkpoint_moved ? 'checkpoint_moved' : null;if (!reason) { retained.push({ cursor_key: row.cursor_key, source_id: row.source_id, why: 'resumable' }); continue; }orphans.push({ kind: 'unfinished_cursor', cursor_key: row.cursor_key, source_id: row.source_id, source_incarnation: row.source_incarnation, run_id: row.run_id,principal, pending_request_id: row.pending_request_id, pending_state: row.pending_state, reason, updated_at: row.updated_at });@@ -206,11 +227,15 @@ export async function pruneMirrorOnlyManagedFailures(engine: SqlEngine, sourceId* #6712 PR 1: a `superseded_by_adoption` cursor is one the drain's fan-in passed over for the incarnation's adopted* cursor; it is deleted only while no request admitted under its key is still open or carries recovery, and `inTx`* (the drain lease's fence) runs first in the same transaction.+ *+ * #6834: a `checkpoint_moved` cursor is deleted only while the classification's rule still holds (`checkpointMovedSql`):+ * its checkpoint is still the refused one, the source still records a commit other than its start and target, and no+ * request under its key is open or carries recovery.*/export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<ManagedSyncOrphan, 'kind' | 'cursor_key' | 'run_id' | 'source_id' | 'source_incarnation' | 'reason'>,inTx?: (tx: BrainEngine) => Promise<void>): Promise<{ cursor: boolean; failure: boolean; manifest: boolean; mirror: boolean }> {const retired = orphan.reason === 'incarnation_retired';- const mode = retired ? 'retired' : orphan.reason === 'superseded_by_adoption' ? 'adoption' : 'orphan';+ const mode = retired ? 'retired' : orphan.reason === 'superseded_by_adoption' ? 'adoption' : orphan.reason === 'checkpoint_moved' ? 'checkpoint_moved' : 'orphan';if (orphan.kind === 'mirror_row') {const durable = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1", [orphan.cursor_key]);if (durable.length) return { cursor: false, failure: false, manifest: false, mirror: false };@@ -230,11 +255,12 @@ export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<AND ($4::text='retired' AND EXISTS(SELECT 1 FROM sources s WHERE s.id=$2 AND NOT COALESCE(s.archived,false) AND s.incarnation::text<>$3)OR $4::text='adoption' AND NOT EXISTS(SELECT 1 FROM persistence_requests r WHERE r.source_id=$2 AND r.intent->>'cursorKey'=$1AND (r.state IN ('queued','running','recovering') OR r.recovery IS NOT NULL))+ OR $4::text='checkpoint_moved' AND EXISTS(SELECT 1 FROM sources s WHERE s.id=$2 AND s.incarnation::text=$3 AND NOT COALESCE(s.archived,false) AND ${checkpointMovedSql('$5')})OR $4::text='orphan' AND NOT EXISTS(SELECT 1 FROM persistence_local_writers w WHERE w.revoked_at IS NULLAND w.id::text=c.completed_keys->0->'authority'->'writer'->'principal'->>'id'AND c.completed_keys->0->'authority'->'writer'->'principal'->>'kind' IN ('local_cli','local_stdio')AND (c.completed_keys->0 ? 'syncOptions')))- RETURNING fingerprint`, [orphan.cursor_key, orphan.source_id, orphan.source_incarnation, mode]);+ RETURNING fingerprint`, [orphan.cursor_key, orphan.source_id, orphan.source_incarnation, mode, CHECKPOINT_MOVED_MESSAGE]);cursor = rows.length > 0;if (!cursor) return { cursor: false, failure: false, manifest: false, mirror: false };}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 069d75bb67..b1dc2c185f 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -15,7 +15,7 @@ import { preparationConfigView } from './config-snapshot.ts';import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';-import { slugModeCheckpointRevivable } from './sync-slug-mode.ts';+import { checkpointMovedToTarget, slugModeCheckpointRevivable } from './sync-slug-mode.ts';import { managedCursorKey, resolveManagedCursor } from './sync-cursor-key.ts';import { isImageFilePath, isMultimodalEnabled } from '../sync.ts';import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';@@ -800,13 +800,16 @@ const revivableCheckpointRefusal = (done: Pick<WriteRequest, 'state' | 'error_co* publication validates everything again. The completed manifest and the old receipt stay as they are. Null when it* still blocks, or after `CHECKPOINT_REVIVAL_LIMIT` revivals in this invocation (the next invocation re-assesses).* #6694: a checkpoint refused for its slug-root mode is revived the same way once the source admits it (sync-slug-mode.ts).+ * #6834: a checkpoint refused because `last_commit` moved to exactly this run's target is revived marked overtaken.*/async function reviveCheckpoint(engine: BrainEngine, input: SettleInput): Promise<Cursor | null> {const { cursor, key, pending, done } = input;- const refused = revivableCheckpointRefusal(done) || (pending.intent.kind === 'managed_sync_checkpoint' && await slugModeCheckpointRevivable(engine, cursor, pending.intent, done));+ const checkpoint = pending.intent.kind === 'managed_sync_checkpoint';+ const atTarget = checkpoint && await checkpointMovedToTarget(engine, cursor, pending.intent, done);+ const refused = revivableCheckpointRefusal(done) || atTarget || (checkpoint && await slugModeCheckpointRevivable(engine, cursor, pending.intent, done));const revivals = checkpointRevivalsByRun.get(input.run) ?? 0;- if (pending.intent.kind !== 'managed_sync_checkpoint' || !refused || done.recovery || cursor.index !== cursor.entries.length || revivals >= CHECKPOINT_REVIVAL_LIMIT) return null;- const base = withoutPending(cursor);+ if (!checkpoint || !refused || done.recovery || cursor.index !== cursor.entries.length || revivals >= CHECKPOINT_REVIVAL_LIMIT) return null;+ const base: Cursor = { ...withoutPending(cursor), ...(atTarget ? { overtaken: true as const } : {}) };const fresh = await freezeEntry(engine, base, key, input.assertActive, input.run);if (!('requestId' in fresh)) return null;const blocker = await findIncompleteSyncReceipt(engine, cursor.binding.worktree_id, cursor.runId, fresh.intent.supersededRequests ?? [], fresh.intent.settled ?? null);diff --git a/src/core/persistence/sync-slug-mode.ts b/src/core/persistence/sync-slug-mode.tsindex 9801cf4560..ba4c4bf0f0 100644--- a/src/core/persistence/sync-slug-mode.ts+++ b/src/core/persistence/sync-slug-mode.ts@@ -35,6 +35,22 @@ export function slugModeMismatchCause(sourceId: string, pinned: string, slugMode+ `or keep ${pinned} and run gbrain sync --no-pull --source ${sourceId} --retry-failed, which discovers the source again under ${pinned} (pages this run wrote keep their ${slugMode} slugs beside the new ones).`;}+/**+ * #6834: whether a checkpoint was refused because `last_commit` moved, and it now stands at exactly this run's target:+ * another run of the source (an older gbrain's cursor under another key, or an older binary) checkpointed the same+ * commit. The run's pages all committed and the source is where the checkpoint would put it, so a fresh checkpoint marked+ * overtaken (#5522) finishes the cursor. A checkpoint moved anywhere else stays refused; `gbrain repair+ * managed-sync-orphans` retires that cursor (`checkpoint_moved`).+ */+export async function checkpointMovedToTarget(engine: Pick<BrainEngine, 'executeRaw'>, cursor: { sourceId: string; incarnation: string },+ intent: { from: string | null; target: string; slice?: { done?: boolean } },+ done: Pick<WriteRequest, 'state' | 'error_code' | 'error_message' | 'recovery'>): Promise<boolean> {+ if (done.recovery || !['failed', 'conflict'].includes(done.state) || done.error_code !== 'revision_conflict' || done.error_message !== CHECKPOINT_MOVED_MESSAGE) return false;+ if (intent.slice && !intent.slice.done) return false;+ const [row] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1 AND incarnation=$2::uuid', [cursor.sourceId, cursor.incarnation]);+ return !!row && row.last_commit === intent.target && row.last_commit !== intent.from;+}+/*** Whether a failed checkpoint was refused for its slug mode and the source now admits it: its `last_commit` is still* where the run started, and the pin is unset, equal to the run's mode, or the scope is empty. A legacydiff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.tsindex f8cc46b1d7..42df787d04 100644--- a/src/core/persistence/terminal-classify.ts+++ b/src/core/persistence/terminal-classify.ts@@ -248,6 +248,19 @@ function route(input: TerminalInput): Partial_ {if (known === 'source_binding_changed' || known === 'unsafe_file_target') return diagnosis(input, code, known, `The write was refused source_changed (${known}).`);return fromTable('sync_fault', code, origin ?? known, syncRetry(source, `The file changed under the write (${known}); a sync imports the current bytes.`), known === 'pinned_git_worktree_conflict' ? known : 'source_changed');}+ // #6834: a checkpoint or fact-batch completion receipt names a bookkeeping slug, never a page; reading it finds nothing.+ if (code === 'revision_conflict' && input.slug === '__managed_sync_checkpoint__') {+ return { category: 'caller_conflict', code, origin, class: 'systemic', safe_actions: ['retry'], needs_human: false, escalate: escalateOf(code),+ action: { argv: ['gbrain', 'sync', 'status', '--source', source, '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'A sync checkpoint was refused (__managed_sync_checkpoint__ is bookkeeping, not a page). Sync status names the step that finishes or retires its run, read-only; a later checkpoint of the source supersedes this receipt.',+ verify: { argv: failuresArgv(source) }, docs: 'docs/guides/repair.md#managed-sync-orphans' } };+ }+ if (code === 'revision_conflict' && input.slug === '__managed_facts_complete__') {+ return { category: 'caller_conflict', code, origin, class: 'systemic', safe_actions: ['none'], needs_human: false, escalate: 'never: the batch\'s committed facts stay',+ action: { argv: terminalInspectArgv(input.request_id ?? '<request_id>'), consent: [], actor: 'agent', requires_exclusive: false,+ why: 'A fact-extraction batch was not recorded complete because some of its per-entity requests did not commit (__managed_facts_complete__ is bookkeeping, not a page). The receipt is read-only history; run the extraction again only if facts are still missing.',+ verify: { argv: failuresArgv(source) } } };+ }if (code === 'revision_conflict' || code === 'page_identity_changed') {return { category: 'caller_conflict', code, origin, class: 'page', safe_actions: ['retry'], needs_human: false, escalate: escalateOf(code),action: { argv: ['gbrain', 'get', '--source', source, '--', input.slug], consent: [], actor: 'agent', requires_exclusive: false,@@ -303,13 +316,15 @@ export const PAGE_REMOVAL_OPERATIONS: readonly string[] = ['delete_page', 'purge* The supersession rule of `gbrain repair failed-writes`, as a predicate over a candidate later request `c` of the* failed request `r` (both `persistence_requests` aliases): the same intent committed, failed or still pending; a later* page removal committed or pending; for a `put_page`, any later write committed or pending, or a later caller- * `put_page` that failed (the newer content). Literal strings only; NULL-safe for a compacted `c` (no intent).+ * `put_page` that failed (the newer content); #6834: for a refused sync checkpoint, any later committed checkpoint of the+ * source. Literal strings only; NULL-safe for a compacted `c` (no intent).*/export function supersessionSql(r: string, c: string): string {const removals = PAGE_REMOVAL_OPERATIONS.map(op => `'${op}'`).join(',');return `(${c}.source_id=${r}.source_id AND ${c}.slug=${r}.slug AND ${c}.sequence>${r}.sequence AND ((${c}.digest=${r}.digest AND ${c}.state IN ('committed','failed','queued','running','recovering'))OR (${c}.state IN ('committed','queued','running','recovering') AND (${c}.operation IN (${removals}) OR ${r}.operation='put_page'))+ OR (${r}.slug='__managed_sync_checkpoint__' AND ${c}.state='committed')OR (${r}.operation='put_page' AND ${c}.state='failed' AND ${c}.operation='put_page' AND COALESCE(NOT (${c}.intent ? 'kind'), false))))`;}diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 4e7c34da10..4edd52a196 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -5,6 +5,10 @@ import { UNBOUND_COLLISION_MESSAGE, UNBOUND_PUBLICATION_MESSAGE } from './unbounimport { isFrontmatterHoldMessage } from '../markdown.ts';import { fenceLocationFromMessage, fenceWhere } from '../fence-repair/refusal.ts';import { FACT_WITHDRAWN_SUGGESTION } from '../facts/withdrawal.ts';+import { CHECKPOINT_MOVED_MESSAGE } from './sync-slug-mode.ts';++/** The refusal of a fact-batch completion request whose per-entity requests did not all commit (facts-prepare.ts). */+export const FACTS_BATCH_INCOMPLETE_MESSAGE = 'Some extracted facts have not committed.';const FRONTMATTER_SLUG_CONFLICT = /^The frontmatter slug "[^"\n]{1,300}" in [^/"\n][^"\n]{0,1000} conflicts with its path, which expects slug "[^"\n]{1,300}"\. Remove `slug:` or make it match the path\.$/;@@ -98,6 +102,11 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {suggestion: 'Check the existing owner and its availability. Do not claim, transfer, or activate a source to repair content.' };if (code === 'permission_denied' || code === 'scope_denied') return { reason: code, message: 'The caller is not authorized for this write.',suggestion: 'Check the current caller grant for this source and operation. Content reconciliation does not grant permissions.' };+ // #6834: the checkpoint and fact-batch completion requests name bookkeeping slugs, not pages; there is nothing to read.+ if (code === 'revision_conflict' && message === CHECKPOINT_MOVED_MESSAGE) return { reason: 'sync_checkpoint_moved', message: 'The source\'s sync checkpoint moved while this run published; no page is in conflict.',+ suggestion: '__managed_sync_checkpoint__ is sync bookkeeping, not a page, so there is nothing to read or edit. gbrain sync status --source <source> --json names the next step: when the source already stands at this run\'s target the next sync finishes the run; otherwise preview gbrain repair managed-sync-orphans --source <source> and apply it with the hash it prints, and the next sync discovers from the commit the source records.' };+ if (code === 'revision_conflict' && message === FACTS_BATCH_INCOMPLETE_MESSAGE) return { reason: 'facts_batch_incomplete', message: 'Not every per-entity fact request of this extraction batch committed, so the batch was not recorded complete.',+ suggestion: '__managed_facts_complete__ is the batch\'s completion record, not a page, so there is nothing to read or edit. The facts that did commit stay; inspect the batch\'s entity requests with gbrain write-request <request_id>, and run the extraction again with a new request_id only if facts are still missing.' };if (code === 'revision_conflict' || code === 'page_identity_changed') return { reason: code, message: 'The accepted page identity or revision no longer matches.',suggestion: 'Read the current page and review the intended change before submitting a corrected write.' };if (code === 'invalid_params' && message && FRONTMATTER_SLUG_CONFLICT.test(message)) return { reason: code, message,diff --git a/src/core/repair/managed-sync-orphans.ts b/src/core/repair/managed-sync-orphans.tsindex 6067ae2054..a6b72504ba 100644--- a/src/core/repair/managed-sync-orphans.ts+++ b/src/core/repair/managed-sync-orphans.ts@@ -8,6 +8,9 @@* durable failure row is gone (`mirror_only`); no journal admission, no page* or file changes. A cursor whose pending request is still live, or that the* live writer can resume with its recorded options, is kept and counted.+ * #6834: a cursor whose checkpoint was refused because the source's+ * `last_commit` moved elsewhere (`checkpoint_moved`) is retirable too; it+ * never resumes, and the next sync discovers from the recorded commit.* Retiring an old incarnation's bookkeeping says nothing about whether the* current source's files were imported; `gbrain sync status` does.*/@@ -32,6 +35,7 @@ const describe = (orphan: ManagedSyncOrphan) => orphan.reason === 'no_cursor' ?: orphan.reason === 'principal_unadoptable' ? `cursor recorded by ${orphan.principal ? `${orphan.principal.kind} ${orphan.principal.id.slice(0, 8)}` : 'an unknown principal'}, not an active local writer${orphan.pending_request_id ? `; pending request ${orphan.pending_state ?? 'not found'}` : ''}`: orphan.reason === 'incarnation_retired' ? `${orphan.kind === 'unfinished_cursor' ? 'cursor' : 'failure row'} recorded under source incarnation ${orphan.source_incarnation?.slice(0, 8) ?? '?'}, which the source no longer has; no current sync selects it`: orphan.reason === 'mirror_only' ? 'local ledger mirror row with no durable failure row under its key'+ : orphan.reason === 'checkpoint_moved' ? `cursor whose pages all committed and whose checkpoint (request ${orphan.pending_request_id ?? '?'}) was refused because the source's last_commit moved to a commit outside this run; no resume can publish it, and the next sync discovers from the commit the source records`: 'cursor from before recorded sync options, superseded by a completed run';export const managedSyncOrphansRepair: RepairHandler = {diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex b2b4e58080..cd5278d884 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -174,6 +174,7 @@ test/source-retire-missing-checkout.test.tstest/source-row-diagnostics.test.tstest/stats-health-source-scope.test.tstest/sync-capacity-preflight.test.ts+test/sync-checkpoint-moved-6834.test.tstest/sync-drain-claims.test.tstest/sync-drain-head-blocked-6543.test.tstest/sync-drain-inpass-stall.test.tsdiff --git a/test/sync-checkpoint-moved-6834.test.ts b/test/sync-checkpoint-moved-6834.test.tsnew file mode 100644index 0000000000..b57f542b2c--- /dev/null+++ b/test/sync-checkpoint-moved-6834.test.ts@@ -0,0 +1,245 @@+/**+ * #6834: a managed-sync checkpoint refused because `sources.last_commit` moved under its cursor.+ *+ * The checkpoint request names the bookkeeping slug `__managed_sync_checkpoint__`; its publication is a compare-and-swap+ * on `last_commit` (sync-prepare.ts `applyManagedSyncCheckpoint`). When another run of the source checkpointed first (an+ * older gbrain kept one cursor per writer and option set, so two cursors of one source raced to the same target), the+ * refusal was `revision_conflict` "The source checkpoint changed during this sync." against a page that does not exist,+ * every plain sync resumed the same cursor into the same refusal, and no repair listed it.+ *+ * Protects:+ * - the source already stands at the run's target: the next plain sync finishes the run (a checkpoint marked overtaken),+ * both for a fresh race and for a brain that already carries the refused receipt and failure row;+ * - the source moved anywhere else: the plain sync stays blocked, but the receipt, doctor (sync_failures and+ * sync_freshness) and the terminal-failure action name no page; `gbrain repair managed-sync-orphans` lists the cursor+ * as `checkpoint_moved`, keeps it when the rule no longer holds at apply time, retires it otherwise, and the next+ * plain sync discovers from the recorded commit;+ * - ordinary page revision conflicts keep their diagnosis and action.+ * Synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { __setManagedCursorKeyForTests } from '../src/core/persistence/sync-cursor-key.ts';+import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';+import { classifyManagedSyncOrphans } from '../src/core/persistence/managed-sync-orphans.ts';+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';+import { classifyTerminal, supersessionSql } from '../src/core/persistence/terminal-classify.ts';+import { writeFailureDiagnostic } from '../src/core/persistence/verb-errors.ts';+import { checkSyncFailures } from '../src/commands/doctor/checks/sync-failures.ts';+import { checkSyncFreshness } from '../src/commands/doctor/checks/extraction-sync.ts';+import { managedSyncOrphansRepair } from '../src/core/repair/managed-sync-orphans.ts';+import { runRepair } from '../src/core/repair/core.ts';+import { repairSpec } from '../src/core/repair/registry.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const MOVED = 'The source checkpoint changed during this sync.';+const home = mkdtempSync(join(tmpdir(), 'gbrain-checkpoint-moved-6834-'));+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (repo: string, message: string) => { git(repo, 'add', '-A'); git(repo, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(repo, 'rev-parse', 'HEAD'); };+const note = (title: string, body = 'A synthetic observation') => `---\ntitle: ${title}\n---\n${body} about ${title}.\n`;+type Outcome = Record<string, any>;+const outcome = (run: Promise<unknown>): Promise<Outcome> => run.then(value => value as Outcome, error => ({ thrown: error as { code?: string; message?: string } }));++describe('#6834 a managed-sync checkpoint whose source checkpoint moved', () => {+ const engines: BrainEngine[] = [];+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, 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({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined,+ OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined }, async () => { for (const engine of engines) await fn(engine); });++ /** A subdirectory source (`brain/`) synced once, then one more commit: `entries` edits a page, `zero` edits only a file outside the source. */+ async function fixture(engine: BrainEngine, variant: 'entries' | 'zero') {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const id = `moved-${randomUUID().slice(0, 12)}`, repo = join(home, id), root = join(repo, 'brain');+ mkdirSync(root, { recursive: true }); git(repo, 'init', '-q');+ writeFileSync(join(repo, 'README.md'), 'Repository text outside the source.\n');+ for (const name of ['alpha', 'beta']) { const file = join(root, 'notes', `${name}.md`); mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, note(name)); }+ const seed = commit(repo, 'seed');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, root, '{}']);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };+ expect((await outcome(performManagedSync(engine, opts))).status).toBe('first_sync');+ writeFileSync(join(repo, 'SIDE.md'), 'A side commit outside the source.\n');+ const side = commit(repo, 'side');+ if (variant === 'entries') writeFileSync(join(root, 'notes', 'alpha.md'), note('alpha', 'A revised observation'));+ else writeFileSync(join(repo, 'README.md'), 'Repository text outside the source, revised.\n');+ const target = commit(repo, 'next');+ return { id, repo, root, seed, side, target, opts };+ }+ type Fixture = Awaited<ReturnType<typeof fixture>>;+ /** Runs `fn` as an older gbrain whose cursor key for the source is `key`. */+ async function legacy<T>(key: string, fn: () => Promise<T>): Promise<T> {+ __setManagedCursorKeyForTests(() => key);+ try { return await fn(); } finally { __setManagedCursorKeyForTests(null); }+ }+ /** Stops the run after its page writes and before its checkpoint publishes. */+ async function beforeCheckpoint(engine: BrainEngine, f: Fixture, variant: 'entries' | 'zero') {+ const abort = new AbortController();+ const partial = await outcome(performManagedSync(engine, { ...f.opts, signal: abort.signal, onProgress: p => { if (variant === 'zero' || p.bankedFiles === 1) abort.abort(); } }));+ expect(partial.status).toBe('partial');+ }+ /** The checkpoint column only the owner publishes; another writer moving it is simulated with managed persistence off. */+ async function moveCheckpoint(engine: BrainEngine, f: Fixture, commitId: string) {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try { await engine.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, commitId]); }+ finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+ }+ const lastCommit = async (engine: BrainEngine, f: Fixture) => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0]!.last_commit;+ const checkpoints = async (engine: BrainEngine, f: Fixture) => engine.executeRaw<{ id: string; request_id: string; slug: string; operation: string; state: string; error_code: string | null; error_message: string | null; error_detail: object | null }>(+ `SELECT id::text AS id, request_id::text AS request_id, slug, operation, state, error_code, error_message, error_detail FROM persistence_requests+ WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint' ORDER BY sequence`, [f.id]);+ const unfinished = (engine: BrainEngine, f: Fixture) => (engine.executeRaw<{ n: number | string }>(+ "SELECT count(*) AS n FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND COALESCE(completed_keys->0->>'done','false')<>'true'", [f.id]).then(rows => Number(rows[0]!.n)));+ const superseded = async (engine: BrainEngine, id: string) => (await engine.executeRaw(+ `SELECT 1 FROM persistence_requests r WHERE r.id=$1::uuid AND EXISTS(SELECT 1 FROM persistence_requests c WHERE ${supersessionSql('r', 'c')})`, [id])).length > 0;+ const ctx = (engine: BrainEngine) => ({ engine, config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false } as unknown as OperationContext);+ const repair = (engine: BrainEngine, f: Fixture, expectHash?: string) => runRepair(ctx(engine), managedSyncOrphansRepair, { brain_id: 'host', source_ids: [f.id] },+ { apply: !!expectHash, explicit: true, ...(expectHash ? { expect: expectHash } : {}), spec: repairSpec('managed-sync-orphans') });++ for (const variant of ['entries', 'zero'] as const) {+ test(`two older-key cursors race to one target (${variant}): the losing checkpoint finishes instead of blocking`, () => each(async engine => {+ const f = await fixture(engine, variant);+ const loser = `older-loser-${f.id}`, winner = `older-winner-${f.id}`;+ await legacy(loser, () => beforeCheckpoint(engine, f, variant));+ // The winner never saw the loser's cursor (an older gbrain keyed it apart): it is parked while the winner runs.+ await engine.executeRaw("UPDATE op_checkpoints SET op='managed-sync-parked' WHERE op='managed-sync' AND fingerprint=$1", [loser]);+ expect((await legacy(winner, () => outcome(performManagedSync(engine, f.opts)))).status).toBe('synced');+ await engine.executeRaw("UPDATE op_checkpoints SET op='managed-sync' WHERE op='managed-sync-parked' AND fingerprint=$1", [loser]);+ expect(await lastCommit(engine, f)).toBe(f.target);+ // The loser resumes: its checkpoint is refused (last_commit moved), and the same run revives it as overtaken.+ const resumed = await legacy(loser, () => outcome(performManagedSync(engine, f.opts)));+ expect(resumed.status).toBe('synced');+ const rows = await checkpoints(engine, f);+ expect(rows.filter(row => row.state !== 'committed').map(row => [row.state, row.error_code, row.error_message])).toEqual([['conflict', 'revision_conflict', MOVED]]);+ expect(rows.at(-1)!.state).toBe('committed');+ expect(await lastCommit(engine, f)).toBe(f.target);+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ // The refused receipt is history: a later committed checkpoint of the source supersedes it.+ expect(await superseded(engine, rows.find(row => row.state === 'conflict')!.id)).toBe(true);+ expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('up_to_date');+ expect(await unfinished(engine, f)).toBe(0);+ }), 180_000);+ }++ test('a brain that already carries the refused checkpoint and its failure row, with the source now at the target, finishes on a plain sync', () => each(async engine => {+ const f = await fixture(engine, 'entries');+ await beforeCheckpoint(engine, f, 'entries');+ // An older release recorded the refusal: the checkpoint moved elsewhere first, so its run blocked and wrote the failure row.+ await moveCheckpoint(engine, f, f.side);+ const blocked = await outcome(performManagedSync(engine, f.opts));+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'revision_conflict', count: 1 }] });+ expect((await readManagedSyncFailures(engine, [f.id])).map(row => [row.code, row.phase])).toEqual([['revision_conflict', 'checkpoint']]);+ // Another run then checkpointed this run's target.+ await moveCheckpoint(engine, f, f.target);+ expect((await classifyManagedSyncOrphans(engine, [f.id])).orphans).toEqual([]);+ const finished = await outcome(performManagedSync(engine, f.opts));+ expect(finished.status).toBe('synced');+ expect(await lastCommit(engine, f)).toBe(f.target);+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ expect(await unfinished(engine, f)).toBe(0);+ expect((await readSyncStatus(engine, f.id)).last_error).toBeNull();+ }), 180_000);++ test('a checkpoint moved elsewhere names no page, is listed as checkpoint_moved, and retiring it lets a plain sync converge', () => each(async engine => {+ const f = await fixture(engine, 'entries');+ await beforeCheckpoint(engine, f, 'entries');+ await moveCheckpoint(engine, f, f.side);+ for (let attempt = 0; attempt < 2; attempt++) {+ const blocked = await outcome(performManagedSync(engine, f.opts));+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'revision_conflict', count: 1 }] });+ expect(blocked.managedWrite).toMatchObject({ slug: '__managed_sync_checkpoint__', reason: 'sync_checkpoint_moved' });+ expect(blocked.managedWrite.suggestion).toContain('gbrain repair managed-sync-orphans --source <source>');+ expect(blocked.managedWrite.suggestion).not.toContain('Read the current page');+ }+ // The terminal-failure action reads sync status, never gbrain get on the bookkeeping slug.+ const refused = (await checkpoints(engine, f)).filter(row => row.state === 'conflict');+ expect(refused.length).toBeGreaterThan(0);+ for (const row of refused) {+ const verdict = classifyTerminal({ ...row, source_id: f.id, recovery: null, blocked_reason: null, compacted: false, intent_kind: 'managed_sync_checkpoint' })!;+ expect(verdict.action.argv).toEqual(['gbrain', 'sync', 'status', '--source', f.id, '--json']);+ expect(verdict.class).toBe('systemic');+ }+ const classified = await classifyManagedSyncOrphans(engine, [f.id]);+ expect(classified.orphans.map(orphan => [orphan.kind, orphan.reason])).toEqual([['unfinished_cursor', 'checkpoint_moved']]);+ expect(classified.retained).toEqual([]);+ // Doctor names the repair as its fix: sync_failures, and sync_freshness once the source is stale.+ const failures = (await checkSyncFailures(engine, { remote: false, sourceIds: [f.id] }))!;+ expect(failures.message).toContain('checkpoint_moved');+ expect((failures.fix as { argv: string[] }).argv).toEqual(['gbrain', 'repair', 'managed-sync-orphans', '--source', f.id]);+ const freshness = await checkSyncFreshness(engine, { localOnly: true, nowMs: Date.now() + 5 * 24 * 3600_000 });+ expect(freshness.status).toBe('fail');+ expect((freshness.fix as { argv: string[] }).argv).toEqual(['gbrain', 'repair', 'managed-sync-orphans', '--source', f.id]);+ expect(freshness.message).toContain(`gbrain repair managed-sync-orphans --source ${f.id}`);++ // Preview-first: the apply retires exactly the previewed cursor while its rule still holds.+ const preview = await repair(engine, f);+ expect(preview.affected).toBe(1);+ expect(await unfinished(engine, f)).toBe(1);+ const applied = await repair(engine, f, preview.preview_hash);+ expect(applied.applied).toBe(1);+ expect(await unfinished(engine, f)).toBe(0);+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ expect(await lastCommit(engine, f)).toBe(f.side);+ // The next plain sync discovers from the commit the source records and checkpoints HEAD.+ const converged = await outcome(performManagedSync(engine, f.opts));+ expect(converged.status).toBe('synced');+ expect(await lastCommit(engine, f)).toBe(f.target);+ expect((await engine.getPage('notes/alpha', { sourceId: f.id }))?.compiled_truth).toContain('A revised observation');+ for (const row of refused) expect(await superseded(engine, row.id)).toBe(true);+ expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('up_to_date');+ }), 180_000);++ test('the apply keeps a previewed cursor whose source has since reached its target, and the plain sync finishes it', () => each(async engine => {+ const f = await fixture(engine, 'zero');+ await beforeCheckpoint(engine, f, 'zero');+ await moveCheckpoint(engine, f, f.side);+ expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('blocked_by_failures');+ const preview = await repair(engine, f);+ expect(preview.affected).toBe(1);+ await moveCheckpoint(engine, f, f.target);+ const applied = await repair(engine, f, preview.preview_hash);+ expect(applied.applied).toBe(0);+ expect(await unfinished(engine, f)).toBe(1);+ expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('synced');+ expect(await unfinished(engine, f)).toBe(0);+ }), 180_000);++ test('ordinary page revision conflicts keep their diagnosis and action', () => each(async engine => {+ const page = writeFailureDiagnostic('revision_conflict', 'The page changed during sync preparation.');+ expect(page).toMatchObject({ reason: 'revision_conflict', suggestion: 'Read the current page and review the intended change before submitting a corrected write.' });+ expect(writeFailureDiagnostic('revision_conflict', MOVED).reason).toBe('sync_checkpoint_moved');+ expect(writeFailureDiagnostic('revision_conflict', 'Some extracted facts have not committed.').reason).toBe('facts_batch_incomplete');+ const base = { source_id: 'example-source', operation: 'submit_job', state: 'conflict', error_code: 'revision_conflict', recovery: null, blocked_reason: null, compacted: false, request_id: randomUUID() };+ expect(classifyTerminal({ ...base, slug: 'notes/alpha' })).toMatchObject({ category: 'caller_conflict', class: 'page',+ action: { argv: ['gbrain', 'get', '--source', 'example-source', '--', 'notes/alpha'] } });+ expect(classifyTerminal({ ...base, slug: '__managed_facts_complete__', operation: 'extract_facts' })).toMatchObject({ class: 'systemic', safe_actions: ['none'],+ action: { argv: ['gbrain', 'write-request', base.request_id, '--json'] } });+ // An unfinished run whose checkpoint has not published is the run's to finish, never an orphan.+ const f = await fixture(engine, 'entries');+ await beforeCheckpoint(engine, f, 'entries');+ expect((await classifyManagedSyncOrphans(engine, [f.id])).orphans).toEqual([]);+ expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('synced');+ }), 180_000);+});