Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): retire old-incarnation sync bookkeeping and stale ledger mirrors (#6518)

garrytan8644944bfa05
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index fe8670bbd5..534ff5030d 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -34,7 +34,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/{safe-index,self-capture,stale-embedding-effects}.ts` — `safe_index_pending` (BRAIN: re-sealable pages below the safe-chunk fence, names `gbrain repair safe-chunks`; kept code/image pages are informational), `self_capture` (BRAIN, #5413: corpus `.txt` files whose session id matches a gbrain claude-cli scratch transcript are classified, ones with no harness transcript left are unclassifiable; classification is `isClaudeCliSelfSessionId`; details carry `newest_capture_at`, a capped sample and copy-paste quarantine commands into `<corpus>.quarantine`, and the message says new captures stopped (#5820) so only the existing files need one quarantine; never moves or deletes), `stale_embedding_effects` (OPS, #5629: committed writes with a queued embedding effect untouched for an hour; names each effect with its inspect command; reported as unsupported). Unreadable state is warn with `details.health: 'unknown'`. `writer_version` (`checks/writer-version.ts`, owned by the persistence entry) is registered in the same table as operator-required. Tests: `test/doctor-self-capture.test.ts`, `test/recovery-layer.test.ts`.
- `src/commands/doctor/checks/managed-sync-backlog.ts` — #5984: lists unfinished managed sync cursors with remaining entries, the last drain's pages/min and indexing ETA (`persistence/sync-drain.ts` `readManagedSyncBacklog`); warns when a cursor has not advanced for an hour, with its resume command. Tests: `test/sync-drain.test.ts`.
-- `src/commands/doctor/checks/sync-failures.ts` — reads managed durable cursor/receipt state even when its compatibility ledger is absent. An unavailable read is unknown/warn, not healthy; local findings carry diagnostics and remote findings contain only source-scoped aggregates. Legacy remediation stays separate from explicit managed retry. Failures on archived sources (which sync refuses) are left out of the count and severity and only reported as an ignored total. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/doctor-report-remote.serial.test.ts`, `test/doctor-sync-failures-archived.test.ts`.
+- `src/commands/doctor/checks/sync-failures.ts` — reads managed durable cursor/receipt state even when its compatibility ledger is absent. An unavailable read is unknown/warn, not healthy; local findings carry diagnostics and remote findings contain only source-scoped aggregates. Legacy remediation stays separate from explicit managed retry. Failures on archived sources (which sync refuses) are left out of the count and severity and only reported as an ignored total. #6518: with an engine, `classifyManagedSyncOrphans` runs whenever the brain is reachable (not only when a current failure is counted), so retired-incarnation and mirror-only bookkeeping is named with the repair preview even at zero visible failures, and a failed classification is reported as "could not be classified", never as healthy; without an engine (`doctor --fast`) only the unmanaged ledger rows enter the severity calculation, and mirrored managed rows are reported apart as `warn` "could not be verified without a database connection" (uncertainty, never recovery). Tests: `test/persistence-sync-failures.serial.test.ts`, `test/doctor-report-remote.serial.test.ts`, `test/doctor-sync-failures-archived.test.ts`, `test/managed-sync-orphans-incarnation-6518.test.ts`.
- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `checkPostgresCancellationDriver` (`postgres_cancellation_driver`) inspects a real reserved runtime owner through the shared cancellation helper: unsupported `discard()` is a typed local failure with a repair link, connection/deadline failure is a warning, and PGLite is exempt. The bounded reserve releases late arrivals and does not make general engine connect require cancellation, preserving broken-install diagnostics. `--no-migrate` keeps doctor observational: the CLI connects with `probeOnly` so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carrying `buildChecks` (flag parse into a `DoctorContext`, then `runDoctorRegistry`), `runDoctor` and output rendering; the checks run as the ordered registry in `src/commands/doctor/registry.ts` (see that entry), the check-function library lives in bundles under `src/commands/doctor/checks/` plus four tail-cluster modules under `src/commands/doctor/` (see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text via `test/helpers/doctor-source.ts`, never by reading this file alone. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`; a version AHEAD of this client's `LATEST_VERSION` warns "upgrade this client"; and when the ledger reads current, a read-only `detectMissingColumns` diff from `src/core/schema-verify.ts` runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance `config.version` over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the `gbrain init --migrate-only` hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by `test/doctor-schema-column-diff.test.ts`), `upgrade_errors` (async `checkUpgradeErrors(engine)` over `~/.gbrain/upgrade-errors.jsonl`: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via `engine.getConfig('version')`; a missing engine or unverifiable schema keeps the warn, fail-closed, because `self-upgrade` swaps the binary before `post-upgrade` runs migrations and the binary alone can lie; pinned by `test/doctor-upgrade-errors.test.ts` + `test/doctor-upgrade-errors-stale.test.ts`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](../path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check (`doctor/checks/supervisor-health.ts`) consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings on the doctor surface and in `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate; `pgliteDataDirEntry` in `doctor/checks/db-connection.ts`): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure checks: `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo; it finds each source's Git root once with `sourceGitScope` and passes it to `resolveSourceLocalFilePath` as `gitScope`; `connector_database` sources are skipped and counted in the message); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_capability` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered by the `supervisor` registry entry after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check, a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check. PR #6463: `pidfileHost` (PID-file line 3) makes the same pid under a drifted hostname `single` → `ok` + `host_label_drift`; a two-line legacy file warns `same_pid_host_label_differs`; another pid keeps the warning emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource, connectError?): Promise<Check[]>` exported as a test seam; the optional `connectError` is the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classified `connection` fail entry (so `checks[name=="connection"]` exists in every failure shape — smoke-test branches on it). The `connection` check's failure path classifies via `src/core/pg-access-classify.ts` into a redacted message + `details: {reason, transient, fix_hint}` naming `gbrain db-repair` (deliberately NOT `remediation[]`/`makeRemediationStep` — that lane feeds `--remediate`, whose Minion jobs need the very DB that's down; applicator boundary: `--remediate` = brain-DATA quality with a live engine, `db-repair` = DB ACCESS engine-free). The URL-only `pgbouncerPrepareCheck` helper and the engine-free `db_repair_recurrence` check run BOTH before the connection check and in the dead-DB filesystem lane; `pglite_scale` (engine-fit, warn at ≥1000 pages on pglite) runs in the DB phase. `computeDoctorReport(checks, extras?)` accepts optional `{engine, db_url_source}` which land as additive `DoctorReport.engine` / `DoctorReport.db_url_source` JSON fields (schema_version stays 2). `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`. Schema health is a two-check pair: `schema_version` resolves through `schemaVersionHealth` (`src/core/schema-version-health.ts`, shared with the remote doctor report; a DB AHEAD of the client warns with an upgrade-this-client hint rather than suggesting migrations), and on ledger-current brains a read-only `schema_columns` check diffs live columns against the expected schema (`detectMissingColumns`, dynamically imported inside the ledger-current branch — positional guard in `test/doctor-schema-column-diff.test.ts`) and warns naming the missing columns with the `gbrain init --migrate-only` hint.
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers the façade: re-exports, `Check`/`DoctorReport` and report scoring, the `buildChecks` flag parse, `runDoctor`, output rendering and `--locks`; every check block lives in a registry entry under `doctor/checks/*` (refactor wave 1 W4 doctor), remediation in `doctor/remediate.ts`, wave checks in `doctor/wave-checks.ts`.
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 177f870aa1..74d37eb3f5 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -53,4 +53,4 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- Foreground priority (#5984 Phase 4.5, `foreground_priority` switch, `journal.ts`): `claimableWriteSql` lets a non-sync request pass earlier queued sync rows of its root that have not started and do not name its page (slug, page id or `intent.renameFrom.slug`), claims it first, and holds a passed sync row while that request runs; `claimNextLaneHead` starts no lane head while such a request is unfinished, except one head per foreground commit since the run's last head claim (`seen_sequence`). A consumer whose claimed write passed sync rows (`passed_sync`) claims plain FIFO on that root after it commits (`owesSyncTurn`), so a stream of writes cannot starve the drain. The sync side's pauses (no admit-ahead for 60 s after a write, no group while one is queued, the 25-page credit wait) apply only with the switch off. Receipt health judges a claimed write only against earlier started writes. Pinned by `test/managed-sync-foreground-priority.test.ts` (two processes) and `test/persistence-diagnostics.test.ts`.
-- `src/core/persistence/managed-sync-orphans.ts` + `src/core/repair/managed-sync-orphans.ts` — `gbrain repair managed-sync-orphans --source <id>` (#5459), explicit-only and preview-bound (approved set, `preview_changed` on drift). `classifyManagedSyncOrphans` (read-only; doctor `sync_failures` names the repair when it finds any) takes the source's managed-sync bookkeeping and classes each row `no_cursor` (a failure row with no cursor to resume), `principal_unadoptable` (an unfinished cursor recorded by a principal that is no longer an active local writer, by join on the recorded principal) or `superseded` (a pre-options cursor a later run replaced), and keeps `pending_request_live` and `resumable` rows untouched. `retireManagedSyncOrphan` retires one row atomically. `sources set-strategy` points at it when an unfinished run blocks a strategy change. Pinned by `test/repair-managed-sync-orphans.test.ts`; `test/repair-explicit-only.test.ts` pins its place last in `REPAIR_KINDS`.
+- `src/core/persistence/managed-sync-orphans.ts` + `src/core/repair/managed-sync-orphans.ts` — `gbrain repair managed-sync-orphans --source <id>` (#5459), explicit-only and preview-bound (approved set, `preview_changed` on drift). `classifyManagedSyncOrphans` (read-only; doctor `sync_failures` names the repair when it finds any) takes the source's managed-sync bookkeeping and classes each row `no_cursor` (a failure row with no cursor to resume), `principal_unadoptable` (an unfinished cursor recorded by a principal that is no longer an active local writer, by join on the recorded principal), `superseded` (a pre-options cursor a later run replaced), `incarnation_retired` (#6518: an unfinished cursor or a failure row recorded under a source incarnation the source no longer has, joined on the source id alone, archived sources excluded, a live pending request still retaining it) or `mirror_only` (#6518: a local ledger row with a `managed_cursor_key` and no durable failure row under that key; `mirrorOnlyManagedFailures`, which throws on a failed durable read rather than naming every mirror), and keeps `pending_request_live` and `resumable` rows untouched. `retireManagedSyncOrphan` retires one row atomically: an `incarnation_retired` cursor needs the source still active under another incarnation at apply time and skips the live-writer veto (no retired key is resumable); a `mirror_row` deletes nothing durable and prunes the ledger row only when the durable read, repeated at apply, still finds none. `pruneMirrorOnlyManagedFailures` is the successful-sync path (`clearSettledManagedSyncFailures`). Doctor `sync_failures` classifies whenever the brain is reachable, so the diagnostic is reachable with no current-incarnation failure visible, and reports a failed classification as unknown. `sources set-strategy` points at it when an unfinished run blocks a strategy change. Pinned by `test/repair-managed-sync-orphans.test.ts` and `test/managed-sync-orphans-incarnation-6518.test.ts` (both engines); `test/repair-explicit-only.test.ts` pins its place last in `REPAIR_KINDS`.
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index 6757ec94f8..a9c4f758aa 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -39,7 +39,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.
- `src/core/persistence/sync-page-fault.ts` — #6340: a page that moved under a managed catch-up holds the page, not the run. `headCommittedBytes` returns the working-tree bytes of a path when their blob id equals `HEAD:<path>` (sha1 or sha256 by HEAD's id length), so `freezeEntry` imports bytes committed past the pinned target as HEAD has them (the later pin..HEAD diff re-imports them as a no-op; idea and first test from PR #6323, which this supersedes) and `prepareManagedSyncMutation`'s `newerWorkingTree` screen never sees them. `pageChangeProof` is #6194's revision-linked proof usable at freeze time; `pageChangedHold` builds the `concurrent_write` hold for a database page that was edited, deleted or re-bound after enumeration (with the competing request when proven, else `page_revision` + `expected_revision`), `worktreeDirtyHold` the new `worktree_dirty` hold (pinned `blob_oid`, `working_hash`) for uncommitted bytes that match neither the pin nor the page, `pinnedWorktreeConflict` recognizes that receipt and `pageMovedSinceAdmission` a `revision_conflict` receipt whose page really moved (a run-level conflict with the page where it was still blocks). In `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws (`page_identity_changed`, `revision_conflict`, the renamed-source conflict) into holds when holds are on (a page that still holds exactly what the import carries is re-bound to its new revision and passed by the waiver screen; `sync.holds=fail` and company-brain cursors keep the refusals), `holdFailedFenceRequest` converts the two receipts (imports and deletes) through `receiptPageFaultHold`, re-freezes an entry once under a fresh request when its file changed between admission and publication (`fileChangedAfterAdmission`, the `raw_file_changed` receipt: committed bytes then import as HEAD has them, a second change under the re-frozen request is held `worktree_dirty`; `holdUnderGate` takes `refrozen` in place of `hold` and records the conversion as `refrozen`), `convertBlockedCursor` converts a cursor an older release left blocked (re-freezing a dirty file that is committed now), `originFaultHold` holds an entry whose recorded origin no longer identifies the enumerated page (`assertSyncPageOrigin` at freeze), every page-fault hold marks the cursor `overtaken` (#5522: another cursor may have checkpointed this target), and the `--retry-failed` start tries that conversion before rediscovering, so the frozen manifest survives. `writeGitHold` counts `meta.attempts` per re-hold with the same code; `HOLD_ATTEMPTS_NEEDS_HUMAN` (3) turns a page hold into `needs_human`. The run's catch skips the failure ledger for `isRetryableConnError` / statement timeouts. Tests: `test/managed-sync-page-fault-holds.test.ts` (freeze-time DB edit → hold, same content → re-bind, dirty → `worktree_dirty` → commit → import, committed past pin → HEAD bytes, old blocked cursor → in-place conversion with attempts, connection death → no ledger row, same run on relaunch, one extra pass), the updated expectations in `test/persistence-managed-sync.test.ts` and `test/managed-sync-concurrent-write-hold.test.ts`.
- `src/core/persistence/sync-write-diagnostic.ts` — `managedSyncWriteDiagnostic`, the `managedWrite` block of a managed sync result (terminal receipt reason, suggestion with the retry command, the CRLF-only note), moved unchanged out of `sync-run.ts` by #6340.
-- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`).
+- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate; #6518: the newest cursor recorded under the source's *current* incarnation, the only one a current sync can select), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). When no current-incarnation cursor or failure exists but an unfinished cursor stands under an older incarnation, the status is `cursor: null` with `last_error.code: cursor_incarnation_retired` (table row: systemic, `repair`, no human) and `next` is the `gbrain repair managed-sync-orphans --source <id>` preview, never a sync that selects nothing. `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`).
- `src/core/persistence/sync-drain.ts` (#6340 additions) — `isConnectionDrop` (a retryable connection error that is not #6329's `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` settle discard; `retry-matcher.ts` now matches `ECONNABORTED`, `ETIMEDOUT` and `EPIPE` beside `ECONNRESET`); `runDrain` reconnects (`DrainInput.reconnect`, `engine.reconnect` from `drainManagedSync`) and retries a dropped pass on `CONNECTION_RETRY_MS` (5/15/45 s), resets the count on every committed page, and after `CONNECTION_STRIKES` drops with no commit between them ends `blocked` / `connection_lost` with `drain.connection { drops, last_error }` (URLs stripped) and the resume command as a loopable `next` (`sync_drain_connection_lost` in the catalogue, `connection_lost` in the registry). `drainManagedSync` takes exactly one extra pass (`drain.extra_pass { from, to }`, counts merged by `mergeExtraPass`) when HEAD moved past the pinned target during a `synced` run, so a live checkout ends at HEAD without looping. Tests: `test/sync-drain-connection.test.ts`. In-pass governor: `src/core/persistence/drain-step.ts` — `runDrain` races every pass against a governor that runs with or without `announce`: the pass gets its own `AbortController`, the governor's head read is bounded (`GOVERN_PROBE_MS`, or the window when shorter), and on a stop the pass signal is aborted with `DrainPassAbandoned` (the pass's `assertActive` / `stampDrainStep` boundaries throw it, so it admits and writes nothing more; `stampDrainStep` does not throw the caller's own cancel, which still banks admitted work) and its late result or rejection is dropped. A head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; `PUBLICATION_CEILING_DEFAULT_MS`) stops `blocked` / `drain_stalled` / `publication_overdue` with `stall.in_pass` and a `next` that says restart (never a promised reclaim); a pass with no commit, no unfinished request and nothing changing for `IN_PASS_NO_PROGRESS_MS` (5 min) stops `no_admission`, an unchanged non-empty head `no_progress` / `owner_missing`; a live preparation is left to its own budget and ceiling. `drain-step.ts` holds the process-local step (`freeze`, `waiver_run`, `admission`, `await_receipt`, stamped in `sync-run.ts`) and the last statement label (`noteDrainSql`, from `waiveNoopRun`). `enterClaimPhase(clock, 'publishing')` stamps `waiting_on: 'publication'`. `drainManagedSync` prints one line when the sync's own pool is a transaction-mode pooler. `sync-waivers.ts` `waiveNoopRun` pipelines at most `WAIVER_PIPELINE_MAX` (64) calls per round trip and sends the next chunk only while the prefix holds. `commands/sync-delegate.ts`: a serve-delegated `no_admission` stop continues once with the CLI's own consumer (`serve_no_admission`); a `publication_overdue` stop is reported as it is. Tests: `test/sync-drain-inpass-stall.test.ts`, `test/sync-drain-no-admission.test.ts`, `test/sync-waivers-chunk.test.ts`.
- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). Tests: `test/persistence-manifest-git-scope.test.ts`, `test/hardened-git-filters.test.ts`.
- `src/core/git-checkout.ts` — #6210 (fix wave 12): `classifyGitCheckout(dir, env = process.env): 'git' | 'not_git' | 'unknown'` decides from the filesystem alone whether a directory is inside a Git checkout: `not_git` only when the directory exists and no `.git` entry (directory or gitdir file) is at or above it and `GIT_DIR` is unset; `unknown` for a missing directory or any lookup error other than absence. Git's own exit 128 is locale-dependent and also means a damaged HEAD, a bad gitdir or dubious ownership, so callers that soften "not a checkout" use this instead. `isDurabilityHardenedAsync` (`brain-repo-durability.ts`) returns false only for `not_git` or an absent hook; every other failure (a git probe run with `LC_ALL=C` failing, a timeout, an unreadable hook) rejects `git_unavailable`, and `runPersistenceEffects` (`persistence/effects.ts`) settles each cached per-root probe to `{durable}|{error}` and records the error on every coalesced effect, so the effects stay queued (and park after repeated failures) instead of completing as `durability_not_enabled`. Tests: `test/git-checkout.test.ts`, the `#6210` block of `test/persistence-git-coalescing-5530.slow.test.ts` (Postgres via its e2e twin).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index f49588dd3a..e6331522b5 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -695,6 +695,16 @@ More: [docs/guides/core-memory.md#remote-edits](../../docs/guides/core-memory.md
|---|---|---|---|---|---|---|
| Cost preview requires yes. | The step needs the user's decision before it runs. | Stop and ask the user; re-run only with the authorization the message names. | user | `repeat the read that failed` | 1 | no |
+### cursor_incarnation_retired
+
+<a id="cursor_incarnation_retired"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| An unfinished managed sync cursor of this source was recorded under a source incarnation the source no longer has (it was re-pointed at a new checkout, or removed and added again), so no current sync selects or resumes it. | The cursor key digests the incarnation; every incarnation-joined reader drops the old rows while the local ledger mirror and the source-id-only cursor read still showed them. Retiring the bookkeeping says nothing about whether the current source's files are imported. | Preview gbrain repair managed-sync-orphans --source <id> and apply it with the hash it prints; then gbrain sync status --source <id> --json shows the current cursor, if any. Run: gbrain repair managed-sync-orphans --source '{source_id}' | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/repair.md#managed-sync-orphans](../../docs/guides/repair.md#managed-sync-orphans)
+
### cycle_failed
<a id="cycle_failed"></a>
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 0d60532d80..f6df5fac18 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -411,11 +411,24 @@ Classes in the preview:
| `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 |
+| `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` |
+| `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 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
+the exact `gbrain sync ... --retry-failed` command). An `incarnation_retired`
+cursor is retired even when its recording principal is the live local writer
+with recorded options: that veto is for a cursor the writer could still
+resume, which no retired key can be. Rows on an archived source are never
+listed, and an apply that finds the source archived meanwhile keeps them.
+Retiring an old incarnation's bookkeeping says nothing about whether the
+current source's files are imported; `gbrain sync status --source <id> --json`
+does. Without a database connection, `gbrain doctor --fast` reports the mirror
+rows it cannot verify as `warn` ("could not be verified"), never `fail`: a
+better fast score there is less certainty, not recovery; `gbrain doctor --only
+sync_failures` with the brain reachable is the authoritative check.
+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
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index ef3ebda2d6..ce5a879ab4 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -111,6 +111,7 @@ Every hold and error has three fields, from one table
| `permission_denied` | systemic | none | yes | always |
| `plan_stale` | systemic | none | yes | always |
| `invalid_params` | systemic | none | yes | always |
+| `cursor_incarnation_retired` | systemic | repair | no | the repair preview lists nothing to retire, or the same code returns after the apply |
<!-- sync-fault-table:end -->
A `cancelled` error whose group was released by a lane fault (`lock_timeout`
diff --git a/src/commands/doctor/checks/sync-failures.ts b/src/commands/doctor/checks/sync-failures.ts
index 9d67e8acee..6fcb1059d8 100644
--- a/src/commands/doctor/checks/sync-failures.ts
+++ b/src/commands/doctor/checks/sync-failures.ts
@@ -4,28 +4,59 @@ import { loadSyncFailures, unacknowledgedSyncFailures, decideSyncFailureSeverity
import { 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';
+import { classifyManagedSyncOrphans, type ManagedSyncOrphan } from '../../../core/persistence/managed-sync-orphans.ts';
import { readManagedMode } from '../../../core/persistence/ownership.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: `
+ + 'a better fast score means less certainty, not that sync recovered. Run gbrain doctor --only sync_failures with the brain reachable.';
+
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.
const archived = new Set(engine ? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived = true')).map(row => row.id) : []);
const allManaged = engine ? await readManagedSyncFailures(engine, opts.sourceIds) : [];
- let allLegacy: SyncFailure[] = [];
- try { allLegacy = loadSyncFailures().filter(row => (!engine || !row.managed_cursor_key) && (!opts.sourceIds || opts.sourceIds.includes(row.source_id))); } catch { }
+ let ledger: SyncFailure[] = [];
+ try { ledger = loadSyncFailures().filter(row => !opts.sourceIds || opts.sourceIds.includes(row.source_id)); } catch { }
+ // With an engine the durable rows are the authority and the mirror is ignored; without one (#6518 [R18 iii]) the
+ // mirror rows are reported apart, as unverifiable, while unmanaged ledger failures keep their own severity.
+ const allLegacy = ledger.filter(row => !row.managed_cursor_key);
+ const mirrorRows = engine ? [] : ledger.filter(row => row.managed_cursor_key && (row.state === 'open' || row.state === 'auto_skipped'));
const managed = allManaged.filter(row => !archived.has(row.source_id));
const legacy = allLegacy.filter(row => !archived.has(row.source_id));
const archivedCount = allManaged.length - managed.length + allLegacy.length - legacy.length;
const archivedNote = archivedCount ? ` ${archivedCount} failure(s) on archived source(s) ignored; restore a source to retry them.` : '';
+ const mirrorNote = mirrorRows.length ? ` ${MIRROR_UNVERIFIED(mirrorRows.length)}` : '';
const entries: SyncFailure[] = [...legacy, ...managed.map(row => ({ source_id: row.source_id, path: row.path, code: row.code, error: row.message,
commit: row.target ?? '', first_seen: row.first_seen, ts: row.first_seen, attempts: row.attempts, state: 'open' as const }))];
const severity = decideSyncFailureSeverity({ entries, nowMs: Date.now(), failHours: resolveHoursEnv('GBRAIN_SYNC_FRESHNESS_FAIL_HOURS', 72) });
- if (!severity.unresolved) 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;
+ // #5459/#6518 [R18 ii, iv]: bookkeeping nothing current can resume or clear is classified whenever the brain is reachable, not only
+ // when a current-incarnation failure is visible; a failed classification is reported as unknown, never as "no orphans".
+ let orphans: ManagedSyncOrphan[] = [], orphanReadError: string | null = null;
+ if (engine) {
+ try { orphans = (await classifyManagedSyncOrphans(engine, opts.sourceIds ?? null)).orphans; }
+ catch (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 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 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 } } : {}) };
+ }
+ 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;
+ }
const summary = `${severity.unresolved} unresolved sync failure(s)${severity.auto_skipped ? ` (${severity.auto_skipped} auto-skipped — pages NOT indexed)` : ''}.${archivedNote}`;
- if (opts.remote !== false) return { name: 'sync_failures', status: severity.status, message: summary + ' Ask the host operator to inspect doctor and repair the accepted sync; no paths or receipt details are exposed remotely.' };
+ if (opts.remote !== false) return { name: 'sync_failures', status: severity.status, message: summary + ' Ask the host operator to inspect doctor and repair the accepted sync; no paths or receipt details are exposed remotely.' + remoteOrphanNote + unreadNote + mirrorNote };
// The `engine ?` tolerance is the doctor's: with no engine there is no managed retry to name; the read itself fails closed (#6482).
const managedBrain = engine ? await readManagedMode(engine) : false;
- const requiresManagedRetry = managedBrain || managed.length > 0 || legacy.some(row => row.managed_cursor_key);
+ const requiresManagedRetry = managedBrain || managed.length > 0 || mirrorRows.length > 0;
const details = managed.map(formatManagedSyncFailure);
const unresolvedLegacy = unacknowledgedSyncFailures(legacy);
details.push(...unresolvedLegacy.map(row => `${row.source_id}: ${row.path} (${row.code}: ${row.error})`));
@@ -35,16 +66,13 @@ export async function checkSyncFailures(engine: BrainEngine | null, opts: { sour
severity: severity.status === 'fail' ? 'high' : 'medium', est_seconds: 30, est_usd_cost: 0,
rationale: `Retry ${severity.unresolved} unresolved sync failure(s)` })];
// #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
- ? `${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.";
+ ? `${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}${unreadNote}`.trim()
+ : `Fix the file(s) and re-run 'gbrain sync', or use 'gbrain sync --skip-failed' to acknowledge legacy file failures.${orphanNote}${unreadNote}`;
return { name: 'sync_failures', status: severity.status, message: `${summary} ${details.join('; ')} ${recovery}`,
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.` }) };
+ ...(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.ts
index 215c8b656f..c8e636ba1e 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -473,6 +473,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// #6529 (GBRA-79). `since` is provisional: stamped at the current VERSION because a `since` past VERSION discloses on every fresh brain (goldens, notice tests); the integrator restamps both rows to the release (0.60.182.0 placeholder) at the merge slot.
{ since: '0.60.182.0', text: 'With `GBRAIN_EMBEDDING_MULTIMODAL=true`, managed sync now imports image files through the coordinated image importer (OCR text, image vector and `source_path` at import) instead of holding them as `managed_image_sync_unsupported`; existing image holds are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. With it off, images stay held as before.' },
{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },
+ // wave 16 (GBRA-79). `since` is provisional at the branch VERSION; the integrator restamps it at the merge slot.
+ { since: '0.60.183.0', text: 'Managed sync bookkeeping recorded under a source incarnation the source no longer has (a source re-pointed at a new checkout, or removed and added again) is now retirable: `gbrain repair managed-sync-orphans --source <id>` lists such cursor and failure rows as `incarnation_retired` and local ledger rows whose durable failure row is gone as `mirror_only`, and a successful sync prunes a source\'s stale mirror rows. `gbrain doctor` names them with the repair even when no current failure is visible; `gbrain doctor --fast` (no database) now reports mirrored managed rows as `warn` "could not be verified" instead of `fail` (a better fast score is less certainty, not recovery; the engine-backed check stays authoritative), while old unmanaged file failures keep their severity. `gbrain sync status` reports only a cursor a current sync can select: an old-incarnation cursor is `cursor: null` with `last_error.code: cursor_incarnation_retired` and the repair preview as `next`, instead of a resumable cursor whose `next` selected nothing.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 1d1834c163..15c429f44c 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -133,6 +133,12 @@ export const CODES = {
core_remote_edit_refused: { class: 'consent', summary: "Remote edits to always-loaded core pages are refused by memory.core.remote_edit.", docs: 'docs/guides/core-memory.md#remote-edits', actor: 'user' },
cost_cap_exceeded: { class: 'server', summary: "The run reached its cost cap before finishing." },
cost_preview_requires_yes: { class: 'consent', summary: "Cost preview requires yes." },
+ // wave 16 (GBRA-79) #6518: `gbrain sync status` names a cursor no current sync can select.
+ cursor_incarnation_retired: { class: 'caller', summary: "An unfinished managed sync cursor of this source was recorded under a source incarnation the source no longer has (it was re-pointed at a new checkout, or removed and added again), so no current sync selects or resumes it.",
+ why: "The cursor key digests the incarnation; every incarnation-joined reader drops the old rows while the local ledger mirror and the source-id-only cursor read still showed them. Retiring the bookkeeping says nothing about whether the current source's files are imported.",
+ docs: 'docs/guides/repair.md#managed-sync-orphans',
+ suggestion: 'Preview gbrain repair managed-sync-orphans --source <id> and apply it with the hash it prints; then gbrain sync status --source <id> --json shows the current cursor, if any.',
+ fix: { argv: ['gbrain', 'repair', 'managed-sync-orphans', '--source', '{source_id}'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the retired bookkeeping and prints the apply command; writes nothing.' } },
cycle_failed: { class: 'server', summary: "The maintenance (dream) cycle failed, or a phase threw and was contained so later phases could run." },
d_sel_too_small: { class: 'caller', summary: "The selection split has too few tasks for meaningful validation." },
database_error: { class: 'server', summary: "The brain database could not be reached or refused the operation." },
diff --git a/src/core/persistence/managed-sync-orphans.ts b/src/core/persistence/managed-sync-orphans.ts
index 931a3e15c2..1ddf8ef790 100644
--- a/src/core/persistence/managed-sync-orphans.ts
+++ b/src/core/persistence/managed-sync-orphans.ts
@@ -2,7 +2,7 @@
* Managed-sync orphans (#5459): durable sync bookkeeping nothing current can
* resume, clear or retire, which doctor reports as an unresolved failure forever.
*
- * Two shapes:
+ * Four shapes:
*
* - `failure_row`: a `managed-sync-failure` row whose cursor key has no
* `managed-sync` cursor at all. `clearManagedSyncFailureAfterSuccess` clears a
@@ -14,23 +14,39 @@
* 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.
+ * - `incarnation_retired` (#6518): an unfinished cursor, or a failure row, whose
+ * recorded source incarnation is no longer the source's (the source was
+ * re-pointed at a new checkout, or removed and added again). The cursor key
+ * digests the incarnation, so no current run selects it, and every
+ * 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.
+ * - `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
+ * mirror is only ever pruned after a durable delete, so one whose durable row
+ * is already gone keeps `doctor --fast` warning forever.
*
- * `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.
+ * `classifyManagedSyncOrphans` is read-only (doctor consumes it); a failed
+ * durable read throws instead of returning an empty list, so an unreachable
+ * database never reads as "no orphans". `retireManagedSyncOrphan` deletes one
+ * orphan's rows atomically with every predicate re-checked, so a cursor the
+ * writer picked up meanwhile is kept and a mirror whose durable row appeared
+ * since the preview is kept.
*/
import type { BrainEngine } from '../engine.ts';
import type { SqlEngine } from './model.ts';
-import { clearManagedSyncFailure } from '../sync-failure-ledger.ts';
+import { clearManagedSyncFailure, loadSyncFailures } from '../sync-failure-ledger.ts';
-export type ManagedSyncOrphanReason = 'no_cursor' | 'principal_unadoptable' | 'superseded';
+export type ManagedSyncOrphanReason = 'no_cursor' | 'principal_unadoptable' | 'superseded' | 'incarnation_retired' | 'mirror_only';
export type ManagedSyncOrphanRetained = 'pending_request_live' | 'resumable';
export interface ManagedSyncOrphan {
- kind: 'failure_row' | 'unfinished_cursor';
+ kind: 'failure_row' | 'unfinished_cursor' | 'mirror_row';
cursor_key: string;
source_id: string;
- source_incarnation: string;
+ /** The incarnation the row recorded; null for a ledger mirror row, which records none. */
+ source_incarnation: string | null;
run_id: string | null;
/** The principal the cursor recorded (null for a failure row without one). */
principal: { kind: string; id: string } | null;
@@ -101,17 +117,98 @@ export async function classifyManagedSyncOrphans(engine: SqlEngine, sourceIds: s
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 });
}
+ // #6518: rows keyed under an incarnation the source no longer has. The join is on the source id alone; the live
+ // pending-request guard stays, the live-writer guard does not apply (no current key can select these rows).
+ const retiredCursors = await engine.executeRaw<Pick<CursorRow, 'cursor_key' | 'source_id' | 'source_incarnation' | 'run_id' | 'principal_kind' | 'principal_id' | 'pending_request_id' | 'pending_state' | 'updated_at'>>(`
+ SELECT c.fingerprint AS cursor_key,s.id AS source_id,c.completed_keys->0->>'incarnation' 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->'pending'->>'requestId' AS pending_request_id,r.state AS pending_state,
+ 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.request_id=(c.completed_keys->0->'pending'->>'requestId')::uuid
+ 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]);
+ for (const row of retiredCursors) {
+ 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; }
+ 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: row.principal_kind && row.principal_id ? { kind: row.principal_kind, id: row.principal_id } : null, pending_request_id: row.pending_request_id, pending_state: row.pending_state,
+ reason: 'incarnation_retired', updated_at: row.updated_at });
+ }
+ // A retired failure row rides with its unfinished cursor when one exists under its key (the cursor's retirement deletes it).
+ const retiredFailures = 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,f.completed_keys->0->>'source_incarnation' 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 AND COALESCE(c.completed_keys->0->>'done','false')<>'true')
+ ORDER BY s.id,f.fingerprint`, [sourceIds]);
+ for (const row of retiredFailures) {
+ 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: 'incarnation_retired', updated_at: row.updated_at });
+ }
+ for (const row of await mirrorOnlyManagedFailures(engine, sourceIds)) {
+ orphans.push({ kind: 'mirror_row', cursor_key: row.cursor_key, source_id: row.source_id, source_incarnation: null, run_id: row.run_id, principal: null,
+ pending_request_id: row.request_id, pending_state: null, reason: 'mirror_only', updated_at: row.updated_at });
+ }
return { orphans, retained };
}
+/**
+ * #6518: local ledger rows carrying a `managed_cursor_key` with no durable `managed-sync-failure` row under that key
+ * (any incarnation), on active sources. The durable read is the authority: when it fails, this throws rather than
+ * naming every mirror as prunable. A ledger that cannot be read names nothing.
+ */
+export async function mirrorOnlyManagedFailures(engine: SqlEngine, sourceIds: string[] | null = null): Promise<Array<{ cursor_key: string; source_id: string; run_id: string | null; request_id: string | null; updated_at: string }>> {
+ let rows: ReturnType<typeof loadSyncFailures> = [];
+ try { rows = loadSyncFailures(); } catch { return []; }
+ const mirrors = rows.filter(row => row.managed_cursor_key && (!sourceIds || sourceIds.includes(row.source_id)));
+ if (!mirrors.length) return [];
+ const archived = new Set((await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived = true')).map(row => row.id));
+ const keys = [...new Set(mirrors.map(row => row.managed_cursor_key!))];
+ const durable = new Set((await engine.executeRaw<{ fingerprint: string }>("SELECT fingerprint FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=ANY($1::text[])", [keys])).map(row => row.fingerprint));
+ const seen = new Set<string>();
+ const out: Array<{ cursor_key: string; source_id: string; run_id: string | null; request_id: string | null; updated_at: string }> = [];
+ for (const row of mirrors) {
+ const key = row.managed_cursor_key!;
+ if (durable.has(key) || archived.has(row.source_id) || seen.has(key)) continue;
+ seen.add(key);
+ out.push({ cursor_key: key, source_id: row.source_id, run_id: row.run_id ?? null, request_id: row.request_id ?? null, updated_at: row.ts });
+ }
+ return out;
+}
+
+/** #6518: prunes a source's mirror-only ledger rows (the successful-sync path); returns how many it removed. */
+export async function pruneMirrorOnlyManagedFailures(engine: SqlEngine, sourceId: string): Promise<number> {
+ const rows = await mirrorOnlyManagedFailures(engine, [sourceId]);
+ for (const row of rows) clearManagedSyncFailure(row.cursor_key);
+ return rows.length;
+}
+
/**
* 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.
+ * A `mirror_row` orphan deletes nothing durable: its ledger row goes only when
+ * the durable read, repeated now, still finds no failure row under its key.
* Returns what was removed; an empty result means the orphan is gone or no
* longer qualifies and nothing was touched.
+ *
+ * #6518 [R18]: an `incarnation_retired` cursor is deleted when the source is
+ * still active under a different incarnation at apply time; the live-writer
+ * veto below is for a cursor the live writer could still resume, which no
+ * retired key can be, so it does not apply. The live pending-request guard does.
*/
-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 }> {
+export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<ManagedSyncOrphan, 'kind' | 'cursor_key' | 'run_id' | 'source_id' | 'source_incarnation' | 'reason'>): Promise<{ cursor: boolean; failure: boolean; manifest: boolean; mirror: boolean }> {
+ const retired = orphan.reason === 'incarnation_retired';
+ 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 };
+ return { cursor: false, failure: false, manifest: false, mirror: clearManagedSyncFailure(orphan.cursor_key) };
+ }
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;
@@ -122,23 +219,28 @@ export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<
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]);
+ AND ($4::boolean AND EXISTS(SELECT 1 FROM sources s WHERE s.id=$2 AND NOT COALESCE(s.archived,false) AND s.incarnation::text<>$3)
+ OR NOT $4::boolean 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, retired]);
cursor = rows.length > 0;
- if (!cursor) return { cursor: false, failure: false, manifest: false };
+ if (!cursor) return { cursor: false, failure: false, manifest: false, mirror: 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;
+ const failure = (await tx.executeRaw(`DELETE FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=$1
+ AND NOT EXISTS(SELECT 1 FROM op_checkpoints c WHERE c.op='managed-sync' AND c.fingerprint=$1
+ AND ($2::boolean IS DISTINCT FROM true OR COALESCE(c.completed_keys->0->>'done','false')<>'true'))
+ AND ($2::boolean IS DISTINCT FROM true OR EXISTS(SELECT 1 FROM sources s WHERE s.id=f.completed_keys->0->>'source_id'
+ AND NOT COALESCE(s.archived,false) AND s.incarnation::text<>f.completed_keys->0->>'source_incarnation'))
+ RETURNING fingerprint`, [orphan.cursor_key, retired && orphan.kind === 'failure_row'])).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 };
+ return { cursor, failure, manifest, mirror: false };
});
- if (removed.cursor || removed.failure) try { clearManagedSyncFailure(orphan.cursor_key); } catch { /* the local ledger is a compatibility mirror */ }
+ if (removed.cursor || removed.failure) try { removed.mirror = clearManagedSyncFailure(orphan.cursor_key); } catch { /* the local ledger is a compatibility mirror */ }
return removed;
}
diff --git a/src/core/persistence/sync-failures.ts b/src/core/persistence/sync-failures.ts
index 3c208c2203..49b2820ae4 100644
--- a/src/core/persistence/sync-failures.ts
+++ b/src/core/persistence/sync-failures.ts
@@ -6,6 +6,7 @@ import type { SyncProcessingOptions } from './sync-authority.ts';
import type { SyncCursorOptions } from './sync-prepare.ts';
import { resolveManagedSyncContext, syncGit, syncGitPath } from './sync-discovery.ts';
import { readGitHold } from './sync-holds.ts';
+import { pruneMirrorOnlyManagedFailures } from './managed-sync-orphans.ts';
export interface ManagedSyncFailure {
source_id: string;
@@ -108,6 +109,8 @@ async function sourceFailureRows(engine: BrainEngine, sourceId: string): Promise
/**
* #6288: after a successful managed sync, clears this source's recorded failures under other cursor keys (a `--full` run's
* key is never resumed by autopilot) whose cursor is finished or gone and whose file the imported commit already settles.
+ * #6518: then prunes the source's local mirror rows whose durable failure row is already gone (`mirror_only`); a failed
+ * durable read prunes nothing.
*/
export async function clearSettledManagedSyncFailures(engine: BrainEngine, run: ManagedSyncImported): Promise<number> {
let cleared = 0;
@@ -115,6 +118,7 @@ export async function clearSettledManagedSyncFailures(engine: BrainEngine, run:
if (row.unfinished || await unsettledReason(engine, run, row.failure)) continue;
if (await deleteFailure(engine, row.key, row.failure)) cleared++;
}
+ await pruneMirrorOnlyManagedFailures(engine, run.sourceId);
return cleared;
}
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 45871550c9..b05b5af5c6 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -79,6 +79,8 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
{ code: 'permission_denied', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'This principal may not sync the source; the owner grants it.' },
{ code: 'plan_stale', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The approved company-brain manifest changed; inspect and approve the repository again.' },
{ code: 'invalid_params', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The resume options conflict with the stored cursor; use the resume command the error prints.' },
+ // #6518: bookkeeping of an incarnation the source no longer has; a retry selects a different key, so only the repair clears it.
+ { code: 'cursor_incarnation_retired', class: 'systemic', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview lists nothing to retire, or the same code returns after the apply' },
];
const BY_CODE = new Map(SYNC_FAULT_TABLE.map(rule => [rule.code, rule]));
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 1e46d87864..acff386811 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -83,12 +83,20 @@ interface CursorHeader { runId: string; index: number; total: number; target: st
progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };
processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean }; syncOptions?: Parameters<typeof managedSyncResumeArgs>[0]['syncOptions'] }
-async function cursorHeader(engine: BrainEngine, sourceId: string): Promise<CursorHeader | null> {
+/** The newest cursor a current sync of the source can select: #6518, one recorded under its current incarnation. */
+async function cursorHeader(engine: BrainEngine, sourceId: string, incarnation: string): Promise<CursorHeader | null> {
const rows = await engine.executeRaw<{ header: CursorHeader }>(
- `SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 ORDER BY updated_at DESC LIMIT 1`, [sourceId]);
+ `SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->>'incarnation'=$2 ORDER BY updated_at DESC LIMIT 1`, [sourceId, incarnation]);
return rows[0]?.header ?? null;
}
+/** #6518: whether an unfinished cursor of the source stands under an incarnation it no longer has (nothing current resumes it). */
+async function retiredCursorStands(engine: BrainEngine, sourceId: string, incarnation: string): Promise<{ first_seen: string } | null> {
+ const [row] = await engine.executeRaw<{ first_seen: string }>(`SELECT to_char(updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS first_seen FROM op_checkpoints
+ WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->>'incarnation'<>$2 AND COALESCE(completed_keys->0->>'done','false')<>'true' ORDER BY updated_at LIMIT 1`, [sourceId, incarnation]);
+ return row ?? null;
+}
+
/**
* #6377: the verdict of a repair-class hold follows its stored repair state. A fence hold whose state is `manual` (a
* manual-only reason, a gate rejection, a model failure the run does not retry) or `paid` (spend only the user raises),
@@ -119,7 +127,7 @@ function holdStatus(record: GitHoldRecord, auto?: FenceAutoRepair): SyncStatusHo
export async function readSyncStatus(engine: BrainEngine, sourceId: string): Promise<SyncStatus> {
const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);
if (!source) throw Object.assign(new Error(`Source ${sourceId} does not exist.`), { code: 'not_found' });
- const header = await cursorHeader(engine, sourceId);
+ const header = await cursorHeader(engine, sourceId, source.incarnation);
const [committed] = await engine.executeRaw<{ n: number | string }>(`SELECT count(*) AS n FROM persistence_requests WHERE source_id=$1 AND state='committed'
AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete') AND completed_at > now() - interval '10 minutes'`, [sourceId]);
const records = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.incarnation === source.incarnation);
@@ -129,8 +137,13 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');
const failure = failures[0];
const laneFault = failure?.code === 'cancelled' ? laneFaultInMessage(failure.message) : null;
+ const retired = failure || header ? null : await retiredCursorStands(engine, sourceId, source.incarnation);
+ const repairPreview: Action = { argv: ['gbrain', 'repair', 'managed-sync-orphans', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Previews the sync bookkeeping nothing current can resume or clear (an old incarnation\'s cursor and failure rows, stale mirror rows) with the hash its --apply takes; writes nothing.' };
const lastError: SyncStatusError | null = failure ? { code: failure.code, ...(laneFault ? { detail: laneFault } : {}), message: failure.message, path: failure.path, phase: failure.phase, first_seen: failure.first_seen, attempts: failure.attempts,
- ...(failure.request_id ? { request_id: failure.request_id } : {}), ...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message }) } : null;
+ ...(failure.request_id ? { request_id: failure.request_id } : {}), ...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message }) }
+ : retired ? { code: 'cursor_incarnation_retired', message: `An unfinished sync cursor of ${sourceId} was recorded under an incarnation the source no longer has; no current sync selects it, and it says nothing about whether the current files are imported. `
+ + `Retire it with ${repairPreview.argv!.join(' ')} (preview, then --apply with the printed hash).`, phase: 'resume', first_seen: retired.first_seen, attempts: 1, ...classifySyncFault({ code: 'cursor_incarnation_retired' }) } : null;
const unfinished = !!header && !header.done;
const remaining = header ? Math.max(0, Number(header.total) - Number(header.index)) : null;
const p = header?.progress;
@@ -147,6 +160,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
why: `${actionable.length} held file(s) have a safe action: unblock schedules each one whose condition holds (a committed edit, a stalled preparation) for a re-screen`
+ `${repairable ? `, repairs the ${repairable} content hold(s) the content-repair lane clears (hash-bound repairs under the fences.repair caps, one receipt per file, then the re-screen)` : ''}`
+ ' and names the sync to run; it refuses the rest by name and drops nothing.' }
+ : retired ? { ...repairPreview, verify }
: unfinished || lastError
? { argv: ['gbrain', 'sync', ...resume, ...(lastError ? ['--retry-failed'] : [])], consent: [], actor: 'agent', requires_exclusive: false, verify,
why: lastError ? `The last run recorded ${lastError.code} (${lastError.class}); this release holds or retries it, and --retry-failed converts the stopped entry in place without re-freezing the manifest.`
@@ -228,7 +242,7 @@ export async function unblockSync(engine: BrainEngine, sourceId: string, opts: U
const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);
if (!source) throw Object.assign(new Error(`Source ${sourceId} does not exist.`), { code: 'not_found' });
const holds = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.incarnation === source.incarnation);
- const header = await cursorHeader(engine, sourceId);
+ const header = await cursorHeader(engine, sourceId, source.incarnation);
const resume = managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });
const context = holds.some(hold => hold.code === 'worktree_dirty') ? await resolveManagedSyncContext(engine, { sourceId, noPull: true }).catch(() => null) : null;
const auto = await fenceAutoRepairFor(engine, holds);
diff --git a/src/core/repair/managed-sync-orphans.ts b/src/core/repair/managed-sync-orphans.ts
index c547aa539d..6067ae2054 100644
--- a/src/core/repair/managed-sync-orphans.ts
+++ b/src/core/repair/managed-sync-orphans.ts
@@ -4,9 +4,12 @@
* 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.
+ * (`op_checkpoints`) and, since #6518, the local ledger's mirror rows whose
+ * 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.
+ * Retiring an old incarnation's bookkeeping says nothing about whether the
+ * current source's files were imported; `gbrain sync status` does.
*/
import { OperationError } from '../ops/contract.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
@@ -19,7 +22,7 @@ type OrphanItem = RepairItem & { orphan: ManagedSyncOrphan; hash: string; last:
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,
+ return { cursor: { phase: orphan.kind === 'unfinished_cursor' ? 0 : orphan.kind === 'failure_row' ? 1 : 2, 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 };
@@ -27,6 +30,8 @@ function item(orphan: ManagedSyncOrphan, index: number, hash: string, last: bool
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'}` : ''}`
+ : 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'
: 'cursor from before recorded sync options, superseded by a completed run';
export const managedSyncOrphansRepair: RepairHandler = {
@@ -60,7 +65,7 @@ export const managedSyncOrphansRepair: RepairHandler = {
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;
+ const applied = removed.cursor || removed.failure || removed.mirror;
return { applied, outcome: applied ? 'retired' : 'kept', ...(applied ? {} : { reason: 'no_longer_orphaned' }), detail: removed };
},
render(details) {
diff --git a/src/core/sync-failure-ledger.ts b/src/core/sync-failure-ledger.ts
index 362347601a..060a457f20 100644
--- a/src/core/sync-failure-ledger.ts
+++ b/src/core/sync-failure-ledger.ts
@@ -667,10 +667,12 @@ export function mirrorManagedSyncFailure(failure: { source_id: string; path: str
});
}
-export function clearManagedSyncFailure(key: string): void {
- withLedgerLock(() => {
+/** Removes the mirror row(s) under a managed cursor key; true when one was there. */
+export function clearManagedSyncFailure(key: string): boolean {
+ return withLedgerLock(() => {
const entries = loadSyncFailures(), kept = entries.filter(row => row.managed_cursor_key !== key);
if (kept.length !== entries.length) _writeAll(kept);
+ return kept.length !== entries.length;
});
}
diff --git a/test/managed-sync-orphans-incarnation-6518.test.ts b/test/managed-sync-orphans-incarnation-6518.test.ts
new file mode 100644
index 0000000000..8ce9ddfbb1
--- /dev/null
+++ b/test/managed-sync-orphans-incarnation-6518.test.ts
@@ -0,0 +1,269 @@
+/**
+ * #6518: incarnation-scoped readers versus incarnation-blind writers. A managed
+ * source re-pointed at a new checkout gets a new incarnation; the cursor and
+ * failure rows written under the old one stay in `op_checkpoints`, every
+ * incarnation-joined reader drops them (`readManagedSyncFailures`, the orphan
+ * classifier, the clear paths), and the local ledger keeps their mirror rows.
+ *
+ * Contract pinned here (reviewed plan G3.2, [R18], CEO C05):
+ * - `classifyManagedSyncOrphans` names such rows `incarnation_retired`, and
+ * `retireManagedSyncOrphan` removes cursor + failure + manifest + mirror row
+ * even when a live local writer with `syncOptions` exists (that veto applies
+ * to live incarnations only); a manifest another cursor shares is kept.
+ * - a ledger row whose `managed_cursor_key` has no durable failure row under
+ * any incarnation is `mirror_only`: listed by the preview, pruned on
+ * `--apply`, and pruned by the successful-sync clear path for its source.
+ * - the orphan diagnostic is reachable from doctor with no visible managed
+ * failure (`managed.length === 0`), locally with the repair command and
+ * remotely without keys or paths.
+ * - `doctor --fast` (no engine) reports mirror rows as `warn` "could not be
+ * verified", never `fail`, while an old unmanaged failure keeps `fail`.
+ * - `readSyncStatus` filters the cursor by the current incarnation: an
+ * old-only cursor is `cursor: null` + `cursor_incarnation_retired` whose
+ * `next` is the repair preview; beside a current cursor it is invisible.
+ * - a failed durable read never reads as "no failures" and never authorises a
+ * mirror deletion; archived sources are excluded and refused at apply.
+ * Both engines where a database is involved.
+ */
+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 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 { checkSyncFailures } from '../src/commands/doctor/checks/sync-failures.ts';
+import { classifyManagedSyncOrphans, retireManagedSyncOrphan } from '../src/core/persistence/managed-sync-orphans.ts';
+import { clearSettledManagedSyncFailures, readManagedSyncFailures, recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';
+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
+import { registerLocalWriter, readLocalWriter } from '../src/core/persistence/identity.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 { loadSyncFailures, mirrorManagedSyncFailure, recordFailures } from '../src/core/sync-failure-ledger.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-6518-'));
+const env = { GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host' };
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const ctx = (engine: BrainEngine) => ({ engine, config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false } as unknown as OperationContext);
+const spec = repairSpec('managed-sync-orphans');
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ await withEnv(env, async () => { for (const engine of engines) await registerLocalWriter(engine, 'cli'); });
+}, 120_000);
+afterAll(async () => { for (const engine of engines) await engine.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });
+
+const each = (fn: (engine: BrainEngine) => Promise<void>) => withEnv(env, async () => { for (const engine of engines) { rmSync(join(home, 'sync-failures.jsonl'), { force: true }); await fn(engine); } });
+const keys = async (engine: BrainEngine, op: string, like: string) => (await engine.executeRaw<{ fingerprint: string }>('SELECT fingerprint FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2 ORDER BY fingerprint', [op, `${like}%`])).map(row => row.fingerprint);
+const mirrors = (prefix: string) => loadSyncFailures().filter(row => row.managed_cursor_key?.startsWith(prefix)).map(row => row.managed_cursor_key);
+
+/** A live source plus bookkeeping written under its previous incarnation (the issue's re-pointed checkout). */
+async function fixture(engine: BrainEngine) {
+ const id = `s6518-${randomUUID().slice(0, 8)}`, prefix = `ck-${id}-`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);
+ const [{ incarnation: old }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ const liveWriterId = (await readLocalWriter(engine, 'cli'))!.id;
+ const principal = { authority: { writer: { principal: { kind: 'local_cli', id: liveWriterId } } } };
+ const cursor = (key: string, incarnation: string, body: Record<string, unknown>) => engine.executeRaw(
+ "INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)",
+ [key, JSON.stringify([{ sourceId: id, incarnation, index: 0, total: 1, target: 'deadbeef', syncOptions: { full: false }, ...principal, ...body }])]);
+ const failure = (key: string, incarnation: string, runId: string, path: string) => recordManagedSyncFailure(engine, { source_id: id, source_incarnation: incarnation, path, code: 'recovery_required',
+ message: 'The private physical-checkout identity cannot be verified.', request_id: null, run_id: runId, target: 'deadbeef', cursor_key: key, phase: 'resume', state: 'failed', observation_id: `${runId}:0` });
+ // The probe's pair: an unfinished cursor of the live writer (with recorded options) and its same-key failure row, plus the manifest.
+ await cursor(`${prefix}old`, old, { runId: `${prefix}run-old` });
+ await failure(`${prefix}old`, old, `${prefix}run-old`, 'notes/2026-09-30.md');
+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-manifest',$1,'[{\"path\":\"notes/2026-09-30.md\"}]'::jsonb)", [`${prefix}run-old`]);
+ // A failure row under the old incarnation with no cursor under its key.
+ await failure(`${prefix}oldfail`, old, `${prefix}run-oldfail`, 'notes/2026-09-29.md');
+ // Re-point: the source gets a new incarnation, as `sources set-path` to a new checkout does.
+ await engine.executeRaw('UPDATE sources SET incarnation=gen_random_uuid() WHERE id=$1', [id]);
+ const [{ incarnation: current }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ expect(current).not.toBe(old);
+ return { id, prefix, old, current, cursor, failure, principal };
+}
+
+test('an old-incarnation cursor and failure are incarnation_retired; doctor reaches the diagnostic with no visible managed failure; sync status does not name the dead cursor', async () => each(async engine => {
+ const f = await fixture(engine);
+ // The issue's symptoms on master: every incarnation-joined reader drops the rows while the mirror keeps them.
+ expect((await readManagedSyncFailures(engine, [f.id])).length).toBe(0);
+ expect(mirrors(f.prefix).sort()).toEqual([`${f.prefix}old`, `${f.prefix}oldfail`]);
+
+ const before = await classifyManagedSyncOrphans(engine, [f.id]);
+ expect(before.orphans.map(orphan => [orphan.kind, orphan.cursor_key, orphan.reason, orphan.source_incarnation]).sort()).toEqual([
+ ['failure_row', `${f.prefix}oldfail`, 'incarnation_retired', f.old], ['unfinished_cursor', `${f.prefix}old`, 'incarnation_retired', f.old]]);
+ expect(before.retained).toEqual([]);
+
+ // (ii) reachable with managed.length === 0: locally with the repair, remotely without keys or paths.
+ const local = await checkSyncFailures(engine, { remote: false, sourceIds: [f.id] });
+ expect(local?.status).toBe('warn');
+ expect(local!.message).toContain('incarnation_retired');
+ expect(local!.message).toContain(`gbrain repair managed-sync-orphans --source ${f.id}`);
+ expect(local!.message).toContain('says nothing about whether the current source\'s files are imported');
+ expect((local!.details as { orphans: unknown[] }).orphans).toHaveLength(2);
+ const remote = await checkSyncFailures(engine, { remote: true, sourceIds: [f.id] });
+ expect(remote?.status).toBe('warn');
+ expect(remote!.message).not.toContain(f.prefix);
+ expect(remote!.message).not.toContain('notes/');
+ expect(remote!.details).toBeUndefined();
+
+ // (4) status: the dead cursor is not reported as resumable; the next step is the repair preview.
+ const status = await readSyncStatus(engine, f.id);
+ expect(status.cursor).toBeNull();
+ expect(status.run_id).toBeNull();
+ expect(status.last_error).toMatchObject({ code: 'cursor_incarnation_retired', needs_human: false, safe_actions: ['repair'] });
+ expect(status.next?.argv).toEqual(['gbrain', 'repair', 'managed-sync-orphans', '--source', f.id]);
+ expect(JSON.stringify(status)).not.toContain('deadbeef');
+ // An old-only cursor beside a current one: the current cursor is the one shown.
+ await f.cursor(`${f.prefix}current`, f.current, { runId: `${f.prefix}run-current`, index: 0, total: 3 });
+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-manifest',$1,'[{\"path\":\"a.md\"},{\"path\":\"b.md\"},{\"path\":\"c.md\"}]'::jsonb)", [`${f.prefix}run-current`]);
+ const beside = await readSyncStatus(engine, f.id);
+ expect(beside.cursor).toMatchObject({ index: 0, total: 3, done: false });
+ expect(beside.run_id).toBe(`${f.prefix}run-current`);
+ expect(beside.last_error?.code).not.toBe('cursor_incarnation_retired');
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE fingerprint IN ($1,$2)", [`${f.prefix}current`, `${f.prefix}run-current`]);
+
+ // The repair: preview lists both with the class; apply retires them although the recording principal is the live local writer with syncOptions.
+ const scope = { brain_id: 'host', source_ids: [f.id] };
+ const preview = await runRepair(ctx(engine), managedSyncOrphansRepair, scope, { apply: false, explicit: true, spec });
+ expect(preview.affected).toBe(2);
+ const applied = await runRepair(ctx(engine), managedSyncOrphansRepair, scope, { apply: true, explicit: true, expect: preview.preview_hash, spec });
+ expect(applied.applied).toBe(2);
+ expect(await keys(engine, 'managed-sync', f.prefix)).toEqual([]);
+ expect(await keys(engine, 'managed-sync-failure', f.prefix)).toEqual([]);
+ expect(await keys(engine, 'managed-sync-manifest', f.prefix)).toEqual([]);
+ expect(mirrors(f.prefix)).toEqual([]);
+ expect((await classifyManagedSyncOrphans(engine, [f.id])).orphans).toEqual([]);
+ expect(await checkSyncFailures(engine, { remote: false, sourceIds: [f.id] })).toBeNull();
+ const after = await readSyncStatus(engine, f.id);
+ expect(after.cursor).toBeNull();
+ expect(after.last_error).toBeNull();
+ expect(after.next).toBeNull();
+}), 120_000);
+
+test('a mirror row with no durable failure is mirror_only: listed, pruned on apply, pruned by the successful-sync clear; a durable row appearing before apply keeps it', async () => each(async engine => {
+ const id = `s6518m-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ const mirror = (key: string) => mirrorManagedSyncFailure({ source_id: id, path: 'notes/a.md', code: 'recovery_required', message: 'stale', target: 'deadbeef', cursor_key: key,
+ request_id: null, run_id: `run-${key}`, observation_id: `run-${key}:0`, first_seen: new Date().toISOString(), attempts: 1 });
+ mirror(`${id}-m1`); mirror(`${id}-m2`); mirror(`${id}-m3`);
+ // A mirror whose durable row exists under the current incarnation is not mirror_only.
+ await recordManagedSyncFailure(engine, { source_id: id, source_incarnation: incarnation, path: 'notes/live.md', code: 'storage_error', message: 'durable', request_id: null,
+ run_id: 'run-live', target: 'deadbeef', cursor_key: `${id}-live`, phase: 'receipt', state: 'failed', observation_id: 'run-live:0' });
+
+ const classified = await classifyManagedSyncOrphans(engine, [id]);
+ expect(classified.orphans.filter(orphan => orphan.reason === 'mirror_only').map(orphan => orphan.cursor_key).sort()).toEqual([`${id}-m1`, `${id}-m2`, `${id}-m3`]);
+ expect(classified.orphans.find(orphan => orphan.cursor_key === `${id}-m1`)).toMatchObject({ kind: 'mirror_row', source_id: id });
+
+ const scope = { brain_id: 'host', source_ids: [id] };
+ const preview = await runRepair(ctx(engine), managedSyncOrphansRepair, scope, { apply: false, explicit: true, spec });
+ expect(preview.affected).toBe(4); // three mirrors + the durable no_cursor failure row
+ // A durable failure row appears under m2 between preview and apply: its mirror is no longer mirror-only and is kept
+ // (a `<checkpoint>` path, which no imported commit settles, so the #6288 clear below leaves the durable row alone).
+ await recordManagedSyncFailure(engine, { source_id: id, source_incarnation: incarnation, path: '<checkpoint>', code: 'storage_error', message: 'late', request_id: null,
+ run_id: `run-${id}-m2`, target: 'deadbeef', cursor_key: `${id}-m2`, phase: 'receipt', state: 'failed', observation_id: `run-${id}-m2:1` });
+ const applied = await runRepair(ctx(engine), managedSyncOrphansRepair, scope, { apply: true, explicit: true, expect: preview.preview_hash, spec });
+ expect(applied.applied).toBe(3);
+ expect(mirrors(`${id}-`).sort()).toEqual([`${id}-m2`]);
+ expect(await keys(engine, 'managed-sync-failure', `${id}-`)).toEqual([`${id}-m2`]);
+
+ // The successful-sync clear path prunes this source's mirror-only rows and leaves another source's alone.
+ mirror(`${id}-m4`);
+ const otherId = `${id}-other`;
+ mirrorManagedSyncFailure({ source_id: otherId, path: 'x.md', code: 'storage_error', message: 'other', target: null, cursor_key: `${otherId}-m`, request_id: null, run_id: 'r', observation_id: 'r:0', first_seen: new Date().toISOString(), attempts: 1 });
+ await clearSettledManagedSyncFailures(engine, { sourceId: id, incarnation, root: home, gitRoot: home, target: 'deadbeef' });
+ expect(mirrors(`${id}-`).sort()).toEqual([`${id}-m2`, `${otherId}-m`]);
+}), 120_000);
+
+test('doctor --fast (no engine) warns on mirror rows it cannot verify and keeps fail for an old unmanaged failure', async () => each(async () => {
+ const id = `s6518f-${randomUUID().slice(0, 8)}`;
+ mirrorManagedSyncFailure({ source_id: id, path: 'notes/a.md', code: 'recovery_required', message: 'stale', target: 'deadbeef', cursor_key: `${id}-m`, request_id: null, run_id: 'r',
+ observation_id: 'r:0', first_seen: new Date(Date.now() - 10 * 86_400_000).toISOString(), attempts: 1 });
+ // Age the mirror row past the 72 h fail cadence: before, it alone turned the fast check `fail`.
+ const aged = loadSyncFailures().map(row => row.managed_cursor_key === `${id}-m` ? { ...row, ts: new Date(Date.now() - 10 * 86_400_000).toISOString() } : row);
+ const { writeFileSync } = await import('node:fs');
+ writeFileSync(join(home, 'sync-failures.jsonl'), aged.map(row => JSON.stringify(row)).join('\n') + '\n');
+ const mirrorOnly = await checkSyncFailures(null, { remote: false, sourceIds: [id] });
+ expect(mirrorOnly?.status).toBe('warn');
+ expect(mirrorOnly!.message).toContain('could not be verified without a database connection');
+ expect(mirrorOnly!.message).toContain('gbrain doctor --only sync_failures');
+ expect(mirrorOnly!.message).toMatch(/less certainty/);
+ expect(mirrorOnly!.remediation).toBeUndefined();
+ // A genuinely old unmanaged failure in the same ledger keeps its authoritative severity.
+ recordFailures(id, [{ path: 'legacy.md', error: 'YAML broke' }], 'c1');
+ const agedBoth = loadSyncFailures().map(row => row.path === 'legacy.md' ? { ...row, ts: new Date(Date.now() - 10 * 86_400_000).toISOString() } : row);
+ writeFileSync(join(home, 'sync-failures.jsonl'), agedBoth.map(row => JSON.stringify(row)).join('\n') + '\n');
+ const mixed = await checkSyncFailures(null, { remote: false, sourceIds: [id] });
+ expect(mixed?.status).toBe('fail');
+ expect(mixed!.message).toContain('1 unresolved sync failure(s)');
+ expect(mixed!.message).toContain('could not be verified');
+ const remote = await checkSyncFailures(null, { remote: true, sourceIds: [id] });
+ expect(remote?.status).toBe('fail');
+ expect(remote!.message).not.toContain('legacy.md');
+}));
+
+test('a failing durable read is not "no failures" and never deletes a mirror; archived sources are excluded and refused at apply; a recreated source retires its old rows', async () => each(async engine => {
+ const f = await fixture(engine);
+ const executeRaw = engine.executeRaw;
+ const failReads = () => { engine.executeRaw = (async (sql: string, params?: unknown[]) => {
+ // The classifier's mirror read (the durable rows under the ledger's keys) fails; the current-incarnation read still answers.
+ if (/managed-sync-failure/.test(sql) && (/fingerprint=ANY/.test(sql) || sql.startsWith("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure'"))) throw Object.assign(new Error('connection reset'), { code: 'ECONNRESET' });
+ return executeRaw.call(engine, sql, params);
+ }) as BrainEngine['executeRaw']; };
+ const restore = () => { engine.executeRaw = executeRaw; };
+ // Preview with a healthy read, then the apply's own re-check fails: the mirror and the rows stay.
+ const scope = { brain_id: 'host', source_ids: [f.id] };
+ mirrorManagedSyncFailure({ source_id: f.id, path: 'notes/m.md', code: 'storage_error', message: 'm', target: null, cursor_key: `${f.prefix}mirror`, request_id: null, run_id: 'rm', observation_id: 'rm:0', first_seen: new Date().toISOString(), attempts: 1 });
+ const preview = await runRepair(ctx(engine), managedSyncOrphansRepair, scope, { apply: false, explicit: true, spec });
+ expect(preview.affected).toBe(3);
+ failReads();
+ try {
+ await expect(classifyManagedSyncOrphans(engine, [f.id])).rejects.toMatchObject({ code: 'ECONNRESET' });
+ const check = await checkSyncFailures(engine, { remote: false, sourceIds: [f.id] });
+ expect(check?.status).toBe('warn');
+ expect(check!.message).toContain('could not be classified (ECONNRESET)');
+ expect(check!.message).toContain('not proof');
+ await expect(retireManagedSyncOrphan(engine, { kind: 'mirror_row', cursor_key: `${f.prefix}mirror`, run_id: null, source_id: f.id, source_incarnation: f.current, reason: 'mirror_only' })).rejects.toMatchObject({ code: 'ECONNRESET' });
+ } finally { restore(); }
+ expect(mirrors(f.prefix).sort()).toEqual([`${f.prefix}mirror`, `${f.prefix}old`, `${f.prefix}oldfail`]);
+ expect(await keys(engine, 'managed-sync', f.prefix)).toEqual([`${f.prefix}old`]);
+
+ // Archived: not classified; an approved set from before the archive is refused row by row (kept), nothing deleted.
+ await engine.executeRaw('UPDATE sources SET archived=true, archived_at=now(), archive_expires_at=now()+interval \'72 hours\' WHERE id=$1', [f.id]);
+ expect((await classifyManagedSyncOrphans(engine, null)).orphans.filter(orphan => orphan.source_id === f.id)).toEqual([]);
+ for (const orphan of (await classifyManagedSyncOrphans(engine, null)).orphans) expect(orphan.source_id).not.toBe(f.id);
+ const keptCursor = await retireManagedSyncOrphan(engine, { kind: 'unfinished_cursor', cursor_key: `${f.prefix}old`, run_id: `${f.prefix}run-old`, source_id: f.id, source_incarnation: f.old, reason: 'incarnation_retired' });
+ expect(keptCursor).toEqual({ cursor: false, failure: false, manifest: false, mirror: false });
+ expect(await keys(engine, 'managed-sync', f.prefix)).toEqual([`${f.prefix}old`]);
+ expect(await keys(engine, 'managed-sync-failure', f.prefix).then(rows => rows.length)).toBe(2);
+ await engine.executeRaw('UPDATE sources SET archived=false, archived_at=NULL, archive_expires_at=NULL WHERE id=$1', [f.id]);
+
+ // Recreated: the source is removed and added again (a third incarnation); rows under both earlier incarnations are retired.
+ await f.cursor(`${f.prefix}second`, f.current, { runId: `${f.prefix}run-second` });
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [f.id]);
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [f.id]);
+ const retired = (await classifyManagedSyncOrphans(engine, [f.id])).orphans;
+ expect(retired.map(orphan => [orphan.cursor_key, orphan.reason]).sort()).toEqual([
+ [`${f.prefix}mirror`, 'mirror_only'], [`${f.prefix}old`, 'incarnation_retired'], [`${f.prefix}oldfail`, 'incarnation_retired'], [`${f.prefix}second`, 'incarnation_retired']]);
+ // A manifest another cursor still references survives the retirement of one of them.
+ await f.cursor(`${f.prefix}twin`, f.old, { runId: `${f.prefix}run-old` });
+ const twinRetired = await retireManagedSyncOrphan(engine, { kind: 'unfinished_cursor', cursor_key: `${f.prefix}old`, run_id: `${f.prefix}run-old`, source_id: f.id, source_incarnation: f.old, reason: 'incarnation_retired' });
+ expect(twinRetired).toEqual({ cursor: true, failure: true, manifest: false, mirror: true });
+ expect(await keys(engine, 'managed-sync-manifest', f.prefix)).toEqual([`${f.prefix}run-old`]);
+ expect(mirrors(f.prefix).sort()).toEqual([`${f.prefix}mirror`, `${f.prefix}oldfail`]);
+ // Preview/apply race: a row retired by another apply in between is reported kept, and the rest of the set still applies.
+ const race = await runRepair(ctx(engine), managedSyncOrphansRepair, scope, { apply: false, explicit: true, spec });
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE fingerprint=$1", [`${f.prefix}second`]);
+ const raced = await runRepair(ctx(engine), managedSyncOrphansRepair, scope, { apply: true, explicit: true, expect: race.preview_hash, spec });
+ expect(raced.applied).toBe(race.affected - 1);
+ expect(raced.skipped).toBe(1);
+ expect(await keys(engine, 'managed-sync', f.prefix)).toEqual([]);
+ expect(await keys(engine, 'managed-sync-failure', f.prefix)).toEqual([]);
+ expect(mirrors(f.prefix)).toEqual([]);
+}), 120_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 62207336c5..9a29b8164b 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -71,6 +71,7 @@ test/managed-sync-group-completion.test.ts
test/managed-sync-group-uncommitted-head.test.ts
test/managed-sync-images-5493.test.ts
test/managed-sync-lanes.test.ts
+test/managed-sync-orphans-incarnation-6518.test.ts
test/managed-sync-page-fault-holds.test.ts
test/managed-sync-pinned-reads.test.ts
test/managed-sync-preparation-stalled-holds.test.ts