Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
repair: managed-sync-orphans retires sync bookkeeping nothing current can resume; doctor names it (#5459)
garrytanbf2794212490
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex e698fbaa76..487466c031 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -8,8 +8,8 @@ can load, and Google source files other local users can read. `gbrain repair`fixes those and the other kinds listed in[What each kind fixes](#what-each-kind-fixes). Every run is a preview unlessyou pass `--apply`.-Nine explicit-only kinds, `google-file-modes`, `stale-atoms`, `extractor-facts`,-`captured-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes` and `frontmatter`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).+The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `extractor-facts`,+`captured-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter` and `managed-sync-orphans`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and`gbrain doctor --remediate --yes --include-repairs --expect <plan_hash>` runs them under a budget(see [Run repairs through doctor](#run-repairs-through-doctor)).@@ -87,9 +87,11 @@ written, and the write is bound to the revision it just read, so an edit madeafter planning is kept and repaired too. An item that no longer needs therepair, or whose page changes during the write, is counted as `skipped` andleft for the next run. No kind deletes data except `stale-atoms`, which-soft-deletes the atoms it retires (they stay recoverable through the+soft-deletes the atoms it retires, and `managed-sync-orphans`, which deletes+only sync bookkeeping rows nothing current can resume ([Managed sync+orphans](#managed-sync-orphans)). Retired atoms stay recoverable through the`restore_page` operation for 72 hours, and a later extraction that produces-a retired atom again restores it). See [Stale atoms](#stale-atoms).+a retired atom again restores it. See [Stale atoms](#stale-atoms).`extractor-facts` only restores previewed facts (it clears `expired_at` andgives each a fresh row number); it never deletes or rewrites a page.@@ -100,7 +102,7 @@ gives each a fresh row number); it never deletes or rewrites a page.| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each kind). Rerun the same command to continue. || `--no-embed` | `safe-chunks` and `contextual-mode`: skip the embedding provider. Run `gbrain embed --stale` later. `timeline` and `visibility` pages are re-embedded by their publication either way. || `--all` | Run every automatic kind in order. Explicit-only kinds are listed with their preview command, never run. |-| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `extractor-facts`, `captured-facts`, `loop-facts`, `failed-writes` and `frontmatter`. |+| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms`, `extractor-facts`, `captured-facts`, `loop-facts`, `failed-writes`, `frontmatter` and `managed-sync-orphans`. || `--include-ambiguous` | `extractor-facts` and `captured-facts`: widen the hashed set to `ambiguous` facts. `frontmatter`: add interpretive file changes. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts), [Captured facts](#captured-facts) and [Frontmatter](#frontmatter). || `--only <path>`, `--skip <path>` | `frontmatter` only: select source-relative files (repeatable). The hash covers the selection, so pass the same flags to the apply. || `--diff` | `frontmatter` only: print every per-file diff instead of one sample per class (`--json` always carries all of them). |@@ -122,6 +124,7 @@ should also check `results[].complete`.| `take-supersession` | none | Rebuilds `takes.superseded_by` for supersession chains written before the pointer moved onto the old fence row (#5886). Each struck take is linked to the row that replaced it only from evidence: a committed `takes_supersede` receipt, a stored `superseded_by`, or a row carrying the old `superseded by #<own row>` pointer with exactly one possible predecessor. The pointer is written onto the old row (`<source>; superseded by #N`) and stale self-pointers are dropped through a revision-bound `put_page`; a page whose fence is already right but whose stored pointers differ is reprojected without a page write. See [take supersession](#take-supersession). | `ambiguous_pages` / `ambiguous_rows`: pages where a new row has two or more possible predecessors, or where evidence conflicts. The preview lists each with its candidates and the manual edit; nothing on them changes. `unparsed_pages`: pages whose takes fence does not parse cleanly. || `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). || `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). || `attribution-backfill` | none | Fills write attribution (who wrote it) on pages, page versions and facts written before attribution was recorded, only where exactly one committed request in the write journal proves the writer: the page write whose recorded result is the row's revision, or the `remember` that inserted the fact. Fills NULLs only, in committed batches of 1,000 that resume after an interruption; no content, revision, page file or request ID changes. See [write attribution](../mcp/ADMIN.md#write-attribution). | `unrecorded_pages`, `unrecorded_page_versions`, `unrecorded_facts`: rows the journal cannot prove. They stay `unrecorded`; nothing is inferred. || `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |@@ -351,6 +354,51 @@ Do not delete binding rows by hand: the repair rechecks, in the samestatement, that the binding is still orphaned and that no pending writerequest uses it.+### Managed sync orphans++<a id="managed-sync-orphans"></a>++**Say to your agent:** *"doctor has reported the same two sync failures for a+week, every sync ends up to date, and `--retry-failed` changes nothing."*++A managed sync run keeps its cursor under a key derived from the source+incarnation, the writer principal and the sync options. A cursor written under+an older key, by a writer identity that no longer exists (a `legacy_token`+principal before the local-CLI cutover, a revoked local writer), can never be+resumed: the live writer reads only its own key. Doctor still reads every+unfinished cursor, so `sync_failures` reports `sync_incomplete` forever, and a+`managed-sync-failure` row whose key has no cursor at all is only cleared by a+success under that same key, which never comes. `--retry-failed` follows the+live cursor; `--skip-failed` is refused on a managed source. Nothing an+operator can run clears either.++`gbrain repair managed-sync-orphans` is the sanctioned exit. It is+explicit-only and preview-bound: the preview classifies every candidate and+prints a hash, and the apply retires exactly that set.++```bash+gbrain repair managed-sync-orphans --source default # preview: lists each orphan with its class+gbrain repair managed-sync-orphans --source default --apply --expect <hash>+gbrain doctor --only sync_failures # the orphaned rows are gone+```++Classes in the preview:++| Class | What it is | Why nothing current can clear it |+|---|---|---|+| `no_cursor` | a `managed-sync-failure` row with no `managed-sync` cursor under its key | cleared only by a success under the same key |+| `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 |++Kept and counted, never retired: a cursor whose pending request is still+queued, running or recovering (`pending_request_live`), and a cursor the live+writer can still resume with its recorded options (`resumable`; doctor prints+the exact `gbrain sync ... --retry-failed` command). The apply rechecks every+predicate in the deleting statement and removes the cursor, its same-key+failure row and its manifest (when no other cursor shares the run) in one+transaction, so a cursor the writer picked up meanwhile is left alone. Do not+delete `op_checkpoints` rows by hand.+### Orphan children**Say to your agent:** *"gbrain fails with `unexpected chunk number` ordiff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 8b639ef64f..dbae3d6714 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -179,6 +179,20 @@ When HEAD moved past the pinned target while the run drained, the drain takesexactly one more pass (an incremental pin..HEAD discovery) so the invocationends at HEAD; never a second one, so a live checkout cannot loop.+## A cursor doctor reports that no sync can reach++`sync_incomplete` in the table above resumes with the same command because the+live writer reads its own cursor key. A cursor written under a key nothing+current derives (an older writer identity such as a `legacy_token` principal,+a revoked local writer, a cursor from before sync options were recorded) is+still read by doctor, so `sync_failures` reports it after every green sync.+That is not a page fault and no rerun clears it: preview+`gbrain repair managed-sync-orphans --source <id>`, relay the listed classes+(`no_cursor`, `principal_unadoptable`, `superseded`) and the kept rows, then+apply with the printed `--apply --expect <hash>` once the user agrees. A cursor+with a live pending request is kept; the loop above owns it+([repair guide](repair.md#managed-sync-orphans)).+## See also- [`write-refusals.md`](write-refusals.md#held-files-and-content-refusals): every hold code with its recovery.diff --git a/src/commands/doctor/checks/sync-failures.ts b/src/commands/doctor/checks/sync-failures.tsindex a4564f06eb..a972da681b 100644--- a/src/commands/doctor/checks/sync-failures.ts+++ b/src/commands/doctor/checks/sync-failures.ts@@ -4,6 +4,7 @@ import { loadSyncFailures, unacknowledgedSyncFailures, decideSyncFailureSeverityimport { formatManagedSyncFailure, managedSyncRetryCommand, readManagedSyncFailures } from '../../../core/persistence/sync-failures.ts';import { resolveHoursEnv } from '../../../core/env-number.ts';import { makeRemediationStep } from '../../../core/remediation-step.ts';+import { classifyManagedSyncOrphans } from '../../../core/persistence/managed-sync-orphans.ts';export async function checkSyncFailures(engine: BrainEngine | null, opts: { sourceIds?: string[]; remote?: boolean } = {}): Promise<Check | null> {// #5452: sync refuses an archived source, so its failures cannot be cleared and are not a live health signal.@@ -31,10 +32,17 @@ export async function checkSyncFailures(engine: BrainEngine | null, opts: { souroldest_failure: unresolvedLegacy.map(row => row.ts).sort()[0] },severity: severity.status === 'fail' ? 'high' : 'medium', est_seconds: 30, est_usd_cost: 0,rationale: `Retry ${severity.unresolved} unresolved sync failure(s)` })];- const retries = [...new Set(managed.map(row => managedSyncRetryCommand(row)))];+ // #5459: a failure nothing current can resume or clear is named as an orphan with its repair, not as a retry that never clears.+ const orphans = engine && managed.length ? (await classifyManagedSyncOrphans(engine, opts.sourceIds ?? null).catch(() => ({ orphans: [] }))).orphans : [];+ const orphanKeys = new Set(orphans.map(orphan => orphan.cursor_key));+ const resumable = managed.filter(row => !orphanKeys.has(row.cursor_key));+ const retries = [...new Set(resumable.map(row => managedSyncRetryCommand(row)))];+ const orphanNote = orphans.length ? ` ${orphans.length} of these (${orphans.map(orphan => `${orphan.source_id}:${orphan.cursor_key.slice(0, 12)} ${orphan.reason}`).join(', ')}) cannot be resumed or cleared by any sync: `+ + `preview gbrain repair managed-sync-orphans${new Set(orphans.map(orphan => orphan.source_id)).size === 1 ? ` --source ${orphans[0]!.source_id}` : ''} and apply with the hash it prints (docs/guides/repair.md#managed-sync-orphans).` : '';const recovery = requiresManagedRetry- ? `Fix the cause, then run ${retries.length ? retries.join(' ; ') : 'gbrain sync --no-pull --retry-failed with the same source and options'}. Completed full runs do not resolve a different unfinished cursor.`+ ? `${resumable.length || !orphans.length ? `Fix the cause, then run ${retries.length ? retries.join(' ; ') : 'gbrain sync --no-pull --retry-failed with the same source and options'}. Completed full runs do not resolve a different unfinished cursor.` : ''}${orphanNote}`.trim(): "Fix the file(s) and re-run 'gbrain sync', or use 'gbrain sync --skip-failed' to acknowledge legacy file failures.";return { name: 'sync_failures', status: severity.status, message: `${summary} ${details.join('; ')} ${recovery}`,- remediation, remediation_status: remediation ? 'remediable' : 'blocked', ...(engine ? {} : { message: `${summary} Durable sync state is unavailable without a database connection; the local ledger is only a compatibility mirror.` }) };+ remediation, remediation_status: remediation ? 'remediable' : 'blocked', ...(orphans.length ? { details: { orphans } } : {}),+ ...(engine ? {} : { message: `${summary} Durable sync state is unavailable without a database connection; the local ledger is only a compatibility mirror.` }) };}diff --git a/src/core/persistence/managed-sync-orphans.ts b/src/core/persistence/managed-sync-orphans.tsnew file mode 100644index 0000000000..931a3e15c2--- /dev/null+++ b/src/core/persistence/managed-sync-orphans.ts@@ -0,0 +1,144 @@+/**+ * Managed-sync orphans (#5459): durable sync bookkeeping nothing current can+ * resume, clear or retire, which doctor reports as an unresolved failure forever.+ *+ * Two shapes:+ *+ * - `failure_row`: a `managed-sync-failure` row whose cursor key has no+ * `managed-sync` cursor at all. `clearManagedSyncFailureAfterSuccess` clears a+ * failure only on a success under the same key, and live runs succeed under a+ * different key, so the row never clears.+ * - `unfinished_cursor`: a `managed-sync` cursor that is not `done` and that the+ * live writer cannot resume: its recorded principal is not an active local+ * writer ([R19]: the join is on the principal the cursor recorded, never on+ * the current one), or it predates recorded sync options and a newer cursor+ * for the same source and incarnation has since completed. A cursor whose+ * pending request is still queued, running or recovering is never an orphan.+ *+ * `classifyManagedSyncOrphans` is read-only (doctor consumes it);+ * `retireManagedSyncOrphan` deletes one orphan's rows atomically with every+ * predicate re-checked, so a cursor the writer picked up meanwhile is kept.+ */+import type { BrainEngine } from '../engine.ts';+import type { SqlEngine } from './model.ts';+import { clearManagedSyncFailure } from '../sync-failure-ledger.ts';++export type ManagedSyncOrphanReason = 'no_cursor' | 'principal_unadoptable' | 'superseded';+export type ManagedSyncOrphanRetained = 'pending_request_live' | 'resumable';++export interface ManagedSyncOrphan {+ kind: 'failure_row' | 'unfinished_cursor';+ cursor_key: string;+ source_id: string;+ source_incarnation: string;+ run_id: string | null;+ /** The principal the cursor recorded (null for a failure row without one). */+ principal: { kind: string; id: string } | null;+ pending_request_id: string | null;+ pending_state: string | null;+ reason: ManagedSyncOrphanReason;+ updated_at: string;+}++export interface ManagedSyncOrphanClassification {+ orphans: ManagedSyncOrphan[];+ /** Unfinished cursors kept with why: a live pending request, or a cursor the live writer can still resume. */+ retained: Array<{ cursor_key: string; source_id: string; why: ManagedSyncOrphanRetained }>;+}++const TERMINAL = ['committed', 'failed', 'conflict', 'cancelled'];++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;+}++/** 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>(`+ SELECT c.fingerprint AS cursor_key,s.id AS source_id,s.incarnation::text AS source_incarnation,c.completed_keys->0->>'runId' AS run_id,+ c.completed_keys->0->'authority'->'writer'->'principal'->>'kind' AS principal_kind,+ c.completed_keys->0->'authority'->'writer'->'principal'->>'id' AS principal_id,+ (c.completed_keys->0 ? 'syncOptions') AS has_sync_options,+ c.completed_keys->0->'pending'->>'requestId' AS pending_request_id,r.state AS pending_state,+ EXISTS(SELECT 1 FROM persistence_local_writers w WHERE w.revoked_at IS NULL+ AND 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')) AS principal_live,+ EXISTS(SELECT 1 FROM op_checkpoints n WHERE n.op='managed-sync' AND n.fingerprint<>c.fingerprint+ AND n.completed_keys->0->>'sourceId'=s.id AND n.completed_keys->0->>'incarnation'=s.incarnation::text+ AND COALESCE(n.completed_keys->0->>'done','false')='true' AND n.updated_at>c.updated_at) AS superseded,+ to_char(c.updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS updated_at+ FROM op_checkpoints c+ JOIN 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)+ LEFT JOIN persistence_requests r ON r.source_id=s.id AND r.source_incarnation=s.incarnation+ AND r.request_id=(c.completed_keys->0->'pending'->>'requestId')::uuid+ AND r.principal_id=c.completed_keys->0->'authority'->'writer'->'principal'->>'id'+ AND 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]);+ 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;+ 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 });+ }+ const failures = await engine.executeRaw<{ cursor_key: string; source_id: string; source_incarnation: string; run_id: string | null; request_id: string | null; updated_at: string }>(`+ SELECT f.fingerprint AS cursor_key,s.id AS source_id,s.incarnation::text AS source_incarnation,f.completed_keys->0->>'run_id' AS run_id,+ f.completed_keys->0->>'request_id' AS request_id,to_char(f.updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS updated_at+ FROM op_checkpoints f+ JOIN sources s ON s.id=f.completed_keys->0->>'source_id' AND s.incarnation::text=f.completed_keys->0->>'source_incarnation' AND NOT COALESCE(s.archived,false)+ WHERE f.op='managed-sync-failure' AND ($1::text[] IS NULL OR s.id=ANY($1::text[]))+ AND NOT EXISTS(SELECT 1 FROM op_checkpoints c WHERE c.op='managed-sync' AND c.fingerprint=f.fingerprint)+ ORDER BY s.id,f.fingerprint`, [sourceIds]);+ for (const row of failures) {+ orphans.push({ kind: 'failure_row', cursor_key: row.cursor_key, source_id: row.source_id, source_incarnation: row.source_incarnation, run_id: row.run_id,+ principal: null, pending_request_id: row.request_id, pending_state: null, reason: 'no_cursor', updated_at: row.updated_at });+ }+ return { orphans, retained };+}++/**+ * Delete one orphan's rows in one transaction: the cursor (unless the writer+ * finished or resumed it meanwhile, or its pending request went live), its+ * same-key failure row, and its manifest when no other cursor shares the run.+ * Returns what was removed; an empty result means the orphan is gone or no+ * longer qualifies and nothing was touched.+ */+export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<ManagedSyncOrphan, 'kind' | 'cursor_key' | 'run_id' | 'source_id' | 'source_incarnation'>): Promise<{ cursor: boolean; failure: boolean; manifest: boolean }> {+ const removed = await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','2000ms',true)");+ let cursor = false;+ if (orphan.kind === 'unfinished_cursor') {+ const rows = await tx.executeRaw(`+ DELETE FROM op_checkpoints c WHERE c.op='managed-sync' AND c.fingerprint=$1+ AND COALESCE(c.completed_keys->0->>'done','false')<>'true'+ AND c.completed_keys->0->>'sourceId'=$2 AND c.completed_keys->0->>'incarnation'=$3+ AND NOT EXISTS(SELECT 1 FROM persistence_requests r WHERE r.request_id=(c.completed_keys->0->'pending'->>'requestId')::uuid+ AND r.source_id=$2 AND r.state NOT IN ('committed','failed','conflict','cancelled'))+ AND NOT EXISTS(SELECT 1 FROM persistence_local_writers w WHERE w.revoked_at IS NULL+ AND 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]);+ cursor = rows.length > 0;+ if (!cursor) return { cursor: false, failure: false, manifest: false };+ }+ const failure = (await tx.executeRaw(`DELETE FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1+ AND NOT EXISTS(SELECT 1 FROM op_checkpoints c WHERE c.op='managed-sync' AND c.fingerprint=$1) RETURNING fingerprint`, [orphan.cursor_key])).length > 0;+ let manifest = false;+ if (orphan.run_id) {+ manifest = (await tx.executeRaw(`DELETE FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1+ AND NOT EXISTS(SELECT 1 FROM op_checkpoints c WHERE c.op='managed-sync' AND c.completed_keys->0->>'runId'=$1) RETURNING fingerprint`, [orphan.run_id])).length > 0;+ }+ return { cursor, failure, manifest };+ });+ if (removed.cursor || removed.failure) try { clearManagedSyncFailure(orphan.cursor_key); } catch { /* the local ledger is a compatibility mirror */ }+ return removed;+}diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 409b130c48..a63c111d8e 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 38deb581a1..4926fe9c9e 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -25,7 +25,7 @@ import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricinimport { shellQuote, type Action } from '../agent-output.ts';import type { RepairKindSpec } from './registry.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/managed-sync-orphans.ts b/src/core/repair/managed-sync-orphans.tsnew file mode 100644index 0000000000..c547aa539d--- /dev/null+++ b/src/core/repair/managed-sync-orphans.ts@@ -0,0 +1,71 @@+/**+ * `gbrain repair managed-sync-orphans [--source <id>]` (#5459): retire managed+ * sync bookkeeping nothing current can resume or clear, so doctor stops+ * reporting it as an unresolved failure. Explicit-only and preview-bound: the+ * preview lists each orphan with its class and saves the set under a hash;+ * `--apply --expect <hash>` retires exactly that set. Bookkeeping rows only+ * (`op_checkpoints`); 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.+ */+import { OperationError } from '../ops/contract.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { classifyManagedSyncOrphans, retireManagedSyncOrphan, type ManagedSyncOrphan } from '../persistence/managed-sync-orphans.ts';+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++type ApprovedOrphan = ManagedSyncOrphan & { selection: string[] };+type OrphanItem = RepairItem & { orphan: ManagedSyncOrphan; hash: string; last: boolean };++const previewCommand = (scope: RepairScope) => `gbrain repair managed-sync-orphans${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;++function item(orphan: ManagedSyncOrphan, index: number, hash: string, last: boolean): OrphanItem {+ return { cursor: { phase: orphan.kind === 'unfinished_cursor' ? 0 : 1, id: index + 1 }, source_id: orphan.source_id,+ slug: `${orphan.kind}:${orphan.cursor_key.slice(0, 12)}`, chars: 0, action: `retire_${orphan.reason}`,+ change: { from: JSON.stringify({ kind: orphan.kind, cursor_key: orphan.cursor_key, run_id: orphan.run_id, reason: orphan.reason, pending_request_id: orphan.pending_request_id }), to: 'retired' },+ orphan, hash, last };+}++const describe = (orphan: ManagedSyncOrphan) => orphan.reason === 'no_cursor' ? 'failure row with no cursor under its key'+ : 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'}` : ''}`+ : 'cursor from before recorded sync options, superseded by a completed run';++export const managedSyncOrphansRepair: RepairHandler = {+ kind: 'managed-sync-orphans',+ publication: 'projection',+ embeds: false,+ outcomeItemsLimit: 1000,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const command = previewCommand(scope);+ if (!opts?.apply) {+ const { orphans, retained } = await classifyManagedSyncOrphans(engine, scope.source_ids);+ const hash = previewHash({ kind: 'managed-sync-orphans-v1', brain_id: scope.brain_id, selection: scope.source_ids,+ orphans: orphans.map(orphan => [orphan.kind, orphan.cursor_key, orphan.run_id, orphan.reason]) });+ if (orphans.length) await saveApprovedSet<ApprovedOrphan>(engine, { command: 'managed-sync-orphans', hash }, orphans.map(orphan => ({ ...orphan, selection: scope.source_ids })));+ const residuals: Record<string, number> = {};+ for (const row of retained) residuals[row.why] = (residuals[row.why] ?? 0) + 1;+ return { items: orphans.map((orphan, index) => item(orphan, index, hash, index === orphans.length - 1)), preview_hash: hash, residuals,+ listing: orphans.map(orphan => ({ item: `${orphan.source_id}:${orphan.cursor_key.slice(0, 12)}`, class: orphan.reason, detail: describe(orphan) })),+ details: { retained } };+ }+ if (!opts.expect) {+ throw new OperationError('invalid_params', 'gbrain repair managed-sync-orphans --apply retires only the set a preview printed.',+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`, 'docs/guides/repair.md#explicit-only-repair-kinds');+ }+ const approved = await loadApprovedSet<ApprovedOrphan>(engine, { command: 'managed-sync-orphans', hash: opts.expect, previewCommand: command });+ if (approved.items.some(entry => JSON.stringify(entry.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);+ const items = approved.items.map(({ selection: _selection, ...orphan }, index) => item(orphan, index, opts.expect!, index === approved.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { orphan, hash, last } = entry as OrphanItem;+ const removed = await retireManagedSyncOrphan(ctx.engine, orphan);+ if (last) await clearApprovedSet(ctx.engine, { command: 'managed-sync-orphans', hash });+ const applied = removed.cursor || removed.failure;+ return { applied, outcome: applied ? 'retired' : 'kept', ...(applied ? {} : { reason: 'no_longer_orphaned' }), detail: removed };+ },+ render(details) {+ const retained = (details.retained ?? []) as Array<{ cursor_key: string; source_id: string; why: string }>;+ return retained.map(row => `kept ${row.source_id}:${row.cursor_key.slice(0, 12)}: ${row.why === 'pending_request_live'+ ? 'its pending request is still queued or running' : 'the live writer can resume it with the sync command doctor prints'}`);+ },+};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 39392a41f8..1546882e57 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -44,6 +44,7 @@ import { requestIndexesRepair } from './request-indexes.ts';import { connectorFencesRepair } from './connector-fences.ts';import { takeSupersessionRepair } from './take-supersession.ts';import { orphanBindingsRepair } from './orphan-bindings.ts';+import { managedSyncOrphansRepair } from './managed-sync-orphans.ts';import { embeddingEffectsRepair } from './embedding-effects.ts';import { googleFileModesRepair } from './google-file-modes.ts';import { staleAtomsRepair } from './stale-atoms.ts';@@ -251,6 +252,13 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'so search and graph reads stop planning as slow nested loops. PGLite also resets each table\'s pending row count; Postgres runs each '+ 'ANALYZE with a 60 s statement and 2 s lock timeout. No journal admission and no user data changes. Brain-wide.',},+ 'managed-sync-orphans': {+ handler: managedSyncOrphansRepair, embeds: 'none', checks: ['sync_failures'], explicit_only: true, preview_bound: true,+ summary: 'Retire managed sync bookkeeping nothing current can resume or clear (#5459): failure rows whose cursor key has no cursor, and unfinished '+ + 'cursors recorded by a principal that is no longer an active local writer (or superseded pre-options cursors) whose pending request is terminal. '+ + 'Bookkeeping only (op_checkpoints); no journal admission. The preview prints a hash; --apply --expect <hash> retires exactly that set. '+ + 'A cursor with a live pending request, or one the live writer can still resume, is kept and counted.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 2eb31d9968..4bb7fce3c2 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments'];+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));diff --git a/test/repair-managed-sync-orphans.test.ts b/test/repair-managed-sync-orphans.test.tsnew file mode 100644index 0000000000..1b38865e4b--- /dev/null+++ b/test/repair-managed-sync-orphans.test.ts@@ -0,0 +1,121 @@+/**+ * #5459: managed sync bookkeeping nothing current can resume or clear.+ *+ * The classifier names the orphans doctor used to report forever (a failure+ * row with no cursor under its key, an unfinished cursor recorded by a+ * principal that is no longer an active local writer, a pre-options cursor a+ * later run superseded) and keeps what the loop still owns (a live pending+ * request, a cursor the live writer can resume). Doctor's `sync_failures`+ * names the repair for the orphans instead of a retry that never clears.+ * `gbrain repair managed-sync-orphans` is explicit-only and preview-bound and+ * retires exactly the previewed set, atomically, leaving the kept rows alone.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { checkSyncFailures } from '../src/commands/doctor/checks/sync-failures.ts';+import { classifyManagedSyncOrphans } from '../src/core/persistence/managed-sync-orphans.ts';+import { recordManagedSyncFailure, readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';+import { registerLocalWriter, readLocalWriter } from '../src/core/persistence/identity.ts';+import { managedSyncOrphansRepair } from '../src/core/repair/managed-sync-orphans.ts';+import { REPAIR_KINDS, runRepair } from '../src/core/repair/core.ts';+import { repairSpec, PREVIEW_BOUND_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY } from '../src/core/repair/registry.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let home: string;+const SOURCE = 'orphans-src';+let incarnation: string;+let liveWriterId: string;+const ctx = () => ({ engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false } as unknown as OperationContext);++const cursor = (key: string, body: Record<string, unknown>, done = false) => engine.executeRaw(+ "INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)",+ [key, JSON.stringify([{ sourceId: SOURCE, incarnation, index: 0, target: 'abc', ...(done ? { done: true } : {}), ...body }])]);+const principal = (kind: string, id: string) => ({ authority: { writer: { principal: { kind, id } } } });+const keys = async (op: string) => (await engine.executeRaw<{ fingerprint: string }>('SELECT fingerprint FROM op_checkpoints WHERE op=$1 ORDER BY fingerprint', [op])).map(row => row.fingerprint);++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-sync-orphans-'));+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host' }, async () => { await registerLocalWriter(engine, 'cli'); liveWriterId = (await readLocalWriter(engine, 'cli'))!.id; });+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [SOURCE]);+ [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [SOURCE]);+}, 120_000);+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++test('the kind is registered explicit-only and preview-bound, clearing sync_failures', () => {+ expect(REPAIR_KINDS).toContain('managed-sync-orphans');+ expect(repairSpec('managed-sync-orphans')).toMatchObject({ explicit_only: true, preview_bound: true, embeds: 'none', checks: ['sync_failures'] });+ expect(EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind)).toContain('managed-sync-orphans');+ expect(PREVIEW_BOUND_REPAIR_REGISTRY.map(spec => spec.kind)).toContain('managed-sync-orphans');+});++test('orphans are classified by what nothing current can do, doctor names the repair, and the apply retires exactly the previewed set', () => withEnv({ GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host' }, async () => {+ // (1) unfinished legacy_token cursor: its pending request is invisible to the live writer (not_found) → principal_unadoptable.+ await cursor('ck-legacy', { runId: 'run-legacy', pending: { requestId: randomUUID() }, syncOptions: { full: false }, ...principal('legacy_token', 'tok') });+ await recordManagedSyncFailure(engine, { source_id: SOURCE, source_incarnation: incarnation, path: '2026-08-08.md', code: 'sync_incomplete', message: 'cursor unfinished',+ request_id: null, run_id: 'run-legacy', target: 'abc', cursor_key: 'ck-legacy', phase: 'resume', state: 'unfinished', observation_id: 'run-legacy:0' });+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-manifest','run-legacy','[{\"path\":\"2026-08-08.md\"}]'::jsonb)");+ // (2) unfinished cursor of the live writer with recorded options → resumable, kept.+ await cursor('ck-live', { runId: 'run-live', syncOptions: { full: false }, ...principal('local_cli', liveWriterId) });+ // (3) pre-options cursor of the live writer, superseded by a later completed run → superseded.+ await cursor('ck-old', { runId: 'run-old', ...principal('local_cli', liveWriterId) });+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '2 days' WHERE fingerprint='ck-old'");+ await cursor('ck-done', { runId: 'run-done', syncOptions: { full: false }, ...principal('local_cli', liveWriterId) }, true);+ // (4) legacy cursor whose pending request is still queued → kept, the loop owns it.+ const busyRequest = randomUUID();+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,terminal_reservation,state)+ VALUES('legacy_token','tok',$1::uuid,'put_page',$2,$3::uuid,'busy','d','{}'::jsonb,0,0,'queued')`, [busyRequest, SOURCE, incarnation]);+ await cursor('ck-busy', { runId: 'run-busy', pending: { requestId: busyRequest }, syncOptions: { full: false }, ...principal('legacy_token', 'tok') });+ // (5) failure row with no cursor under its key → no_cursor.+ await recordManagedSyncFailure(engine, { source_id: SOURCE, source_incarnation: incarnation, path: 'twin.md', code: 'page_identity_changed', message: 'sync_origin_mismatch',+ request_id: null, run_id: 'run-twin', target: 'abc', cursor_key: 'ck-fail-orphan', phase: 'discovery', state: 'failed', observation_id: 'run-twin:0' });++ const before = await classifyManagedSyncOrphans(engine, [SOURCE]);+ expect(before.orphans.map(orphan => [orphan.kind, orphan.cursor_key, orphan.reason]).sort()).toEqual([+ ['failure_row', 'ck-fail-orphan', 'no_cursor'], ['unfinished_cursor', 'ck-legacy', 'principal_unadoptable'], ['unfinished_cursor', 'ck-old', 'superseded']]);+ expect(before.retained.map(row => [row.cursor_key, row.why]).sort()).toEqual([['ck-busy', 'pending_request_live'], ['ck-live', 'resumable']]);+ expect(before.orphans.find(orphan => orphan.cursor_key === 'ck-legacy')).toMatchObject({ principal: { kind: 'legacy_token', id: 'tok' }, pending_state: null, run_id: 'run-legacy' });++ // Doctor still counts every unfinished cursor, and now says which ones no sync can reach and what retires them.+ const check = (await checkSyncFailures(engine, { remote: false, sourceIds: [SOURCE] }))!;+ expect(check.status).not.toBe('ok');+ expect(check.message).toContain('3 of these');+ expect(check.message).toContain('cannot be resumed or cleared by any sync');+ expect(check.message).toContain(`gbrain repair managed-sync-orphans --source ${SOURCE}`);+ expect(check.message).toContain('ck-legacy'.slice(0, 12) + ' principal_unadoptable');+ expect(check.message).toContain('--retry-failed');+ expect((check.details as { orphans: unknown[] }).orphans).toHaveLength(3);+ const remote = (await checkSyncFailures(engine, { remote: true, sourceIds: [SOURCE] }))!;+ expect(remote.message).not.toContain('ck-legacy');++ // Preview: the plan lists the three with their class and prints a hash; the kept rows are residuals.+ const scope = { brain_id: 'host', source_ids: [SOURCE] };+ const preview = await runRepair(ctx(), managedSyncOrphansRepair, scope, { apply: false, explicit: true, spec: repairSpec('managed-sync-orphans') });+ expect(preview.affected).toBe(3);+ expect(preview.preview_hash).toMatch(/^[a-f0-9]{64}$/);+ expect(preview.residuals).toEqual({ pending_request_live: 1, resumable: 1 });+ expect(preview.apply_command).toContain(`--apply --expect ${preview.preview_hash}`);+ // Apply without the hash, or with a stale one, is refused and changes nothing.+ await expect(runRepair(ctx(), managedSyncOrphansRepair, scope, { apply: true, explicit: true, spec: repairSpec('managed-sync-orphans') })).rejects.toMatchObject({ code: 'invalid_params' });+ await expect(runRepair(ctx(), managedSyncOrphansRepair, scope, { apply: true, explicit: true, expect: 'f'.repeat(64), spec: repairSpec('managed-sync-orphans') })).rejects.toMatchObject({ code: 'preview_changed' });+ expect(await keys('managed-sync')).toEqual(['ck-busy', 'ck-done', 'ck-legacy', 'ck-live', 'ck-old']);++ const applied = await runRepair(ctx(), managedSyncOrphansRepair, scope, { apply: true, explicit: true, expect: preview.preview_hash, spec: repairSpec('managed-sync-orphans') });+ expect(applied.applied).toBe(3);+ expect(await keys('managed-sync')).toEqual(['ck-busy', 'ck-done', 'ck-live']);+ expect(await keys('managed-sync-failure')).toEqual([]);+ expect(await keys('managed-sync-manifest')).toEqual([]);+ const after = await classifyManagedSyncOrphans(engine, [SOURCE]);+ expect(after.orphans).toEqual([]);+ expect(after.retained.map(row => row.cursor_key).sort()).toEqual(['ck-busy', 'ck-live']);+ expect((await readManagedSyncFailures(engine, [SOURCE])).map(row => row.cursor_key).sort()).toEqual(['ck-busy', 'ck-live']);+ // A second preview finds nothing; its apply command still binds to "nothing to do".+ const again = await runRepair(ctx(), managedSyncOrphansRepair, scope, { apply: false, explicit: true, spec: repairSpec('managed-sync-orphans') });+ expect(again.affected).toBe(0);+}), 60_000);