Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync): drain a managed sync backlog in one run with a resumable/blocked outcome (#5984)
garrytan9f86f66c9d5e
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex c87373ab9f..83efd97c3a 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -26,6 +26,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.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; `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 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.serial.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.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex 3cfc7317ed..4f3831d37a 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -16,6 +16,7 @@- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).+- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`) sets `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; jobs, serve, the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`. Tests: `test/sync-drain.test.ts`, `test/managed-sync-drain.test.ts`.- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 6e28a3aa60..58f22ea6d1 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -13,6 +13,69 @@ results erode trust. The brain becomes unreliable.With this: edits show up in search within minutes. The vector DB stays currentwith the brain repo automatically. You never have to remember to run sync.+## Catching up a large backlog on managed Postgres++On a managed brain (managed persistence on, Postgres), every changed file+publishes through its own durable write request, in manifest order. One+command drains the whole backlog:++```bash+gbrain sync --source <id> --no-pull --json+```++`--no-pull` is required on managed brains: the checkout is fast-forwarded by+`gbrain sources refresh <id>`, never by sync. Sync then catches the index up+to whatever the checkout holds.++The run prints one line before the first write and a progress line about+every 10 seconds on stderr:++```+[sync] managed catch-up: 9382 entries frozen, 9382 remaining; one write request per page.+[sync] 1240/9382 processed (1200 written, 40 waived this run) · 42.1 pages/min · indexing ETA 3h13m+```++*Written* pages published a change. *Waived* entries needed no write (an+unchanged file, or a delete of a page that is already deleted) and advanced+the cursor without a request. The ETA covers indexing only; embeddings and+extraction queued by the run drain afterwards. Measured throughput by database+distance is in [`docs/eval/managed-sync-catchup.md`](../eval/managed-sync-catchup.md).++The run ends in exactly one outcome:++| Outcome | Exit | Meaning | What to do |+| --- | --- | --- | --- |+| `synced` | 0 | The cursor reached its target. | Nothing. |+| `resumable` | 0 | A deadline, `--timeout` or Ctrl-C stopped it; the cursor and accepted writes are intact. | Rerun `next.command`; safe in a loop. |+| `blocked` | 1 | A page failed or the writer needs intervention. | Follow `next.why`, then run `next.command`. See [drain stops](write-refusals.md#managed-sync-drain-stops). |++**Say to your agent:** *"Catch up my managed brain's sync backlog and tell me+how long it will take."* or *"My managed sync stopped. Is it safe to rerun?"*++Timing knobs the drain uses:++| Knob | Scope | Default | At expiry |+| --- | --- | --- | --- |+| `--timeout <dur>` | Whole drain (per source under `--all`). Never extended by progress. | none | Stops as `resumable`. |+| `--hard-deadline <dur>` | Whole process, enforced out of band. | none | The drain stops itself about 15 s early as `resumable`; the watchdog stops a hung process. |+| `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` | Whole process, non-interactive runs. Extends while pages keep committing. | 3600 (non-TTY) | Stops only after `GBRAIN_SYNC_STALL_ABORT_SECONDS` without progress. |+| `GBRAIN_SYNC_STALL_ABORT_SECONDS` | Progress window for the deadline above. | 900 | The watchdog stops the run and prints the resume command. |+| No-progress detector | Awaited write and checkout head unchanged. | 30 s and 3 passes | Stops as `blocked` / `drain_stalled` with diagnostics. |+| Page write wait | One page's publication before the drain re-checks. | 5 s (checkpoint 8 s) | The drain re-enters; this is not a stop. |++Two more tips:++- **Run the catch-up near the database.** Each page costs several database+ round trips, so a host in the database's region drains far faster than a+ laptop across the internet.+- **Triage.** `gbrain sources writer status <id>` shows the oldest unfinished+ request and why it waits. `gbrain doctor` reports a managed cursor's+ remaining entries and ETA from any process.++Before this drain shipped, the workaround was a shell loop around+`gbrain sync --source <id> --no-pull` until it printed `synced`. That loop+still works, and each run now drains as far as its deadline allows.+## Implementation### Prerequisite: a reachable direct connectiondiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex d4532bffaa..4ed7e84027 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -146,6 +146,26 @@ that already reached the verified upstream commit moves on to syncing.reports `worktree_refresh_stuck` for a refresh active longer than 15 minutes,with the resume command.+## Managed sync drain stops++`gbrain sync` on a managed brain keeps going until the source's cursor is done+(see [catching up a large backlog](live-sync.md#catching-up-a-large-backlog-on-managed-postgres)).+When it stops early, the run ends in one outcome: `resumable` (exit 0, safe to+rerun the same command) or `blocked` (exit 1, needs a fix first). `--json`+carries `outcome`, `drain.stop_reason` and `next: { command, safe_to_loop,+retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run+`next.command`; loop on it only when `next.safe_to_loop` is true.++**Say to your agent:** *"Catch up my managed brain's sync backlog and tell me how long it will take."*++| Stop reason | Code | Outcome | What it means | Recovery |+| --- | --- | --- | --- | --- |+| <a id="drain-stopped-at-its-deadline"></a>`deadline` | `writer_pending` | `resumable` | `--timeout`, `--hard-deadline`, Ctrl-C or the run deadline stopped the drain. Accepted page writes keep their request IDs and the cursor is intact. | Rerun `next.command` (the same options). It resumes where the last run stopped. |+| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout did not change for 30 s across several passes, and nothing on this host can claim it. `drain.stall` names the request, its state, `blocked_reason` and whether this host owns the checkout. | `gbrain sources writer status <source>`. When this host is not the owner, make sure the owner (`gbrain serve`) is running. Then rerun `next.command`. |+| <a id="drain-database-contention"></a>`database_contention` | `database_contention` | error | Three consecutive passes hit database contention, a statement timeout or a dropped connection. The drain retries these with backoff before giving up. | Rerun the same command. If it repeats, check the database or pooler (`gbrain engine status --probe`). |+| <a id="drain-writer-blocked"></a>`recovery_required`, `owner_unavailable`, `unexpected_file_bytes`, `unexpected_staging_bytes` | `recovery_required` | `blocked` | The checkout's writer needs intervention before more pages can publish: interrupted publication recovery, no live owner, or unexpected bytes in the file or staging area. | `gbrain sources writer status <source>` and the fix it prints. Unexpected bytes are the user's edits; ask before discarding them. Then rerun `next.command`. |+| <a id="drain-blocked-by-a-failed-page"></a>`blocked_by_failures` | `blocked_by_failures` | `blocked` | A page write failed terminally. `managed_write` and `failures` name the page and cause. Rerunning without a fix returns the same failure. | Fix the cause, then run `next.command` (it adds `--retry-failed`). Ask the user before skipping content. |+## Unbound sources on PostgresA source with a checkout path (`local_path`, or `sync.repo_path` for thediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex d0c6f75034..dde4fb8b3f 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -12,7 +12,7 @@ src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp snsrc/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2)src/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.tssrc/core/ai/gateway.ts 4393 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts)-src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)+src/commands/sync.ts 486 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts)src/core/cycle.ts 3205 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts)src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)diff --git a/src/cli.ts b/src/cli.tsindex 77feb9d737..916b212cfb 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2442,6 +2442,7 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promisconst { syncWatchdogPlan } = await import('./core/sync-reconcile.ts');const plan = syncWatchdogPlan(args, res);syncWatchdog = installProcessWatchdog(plan.watchdog);+ (await import('./core/forward-progress.ts')).registerRunDeadline({ atMs: Date.now() + res.deadlineMs, strict: !res.progressWindowMs });process.stderr.write(plan.armedLine);}} catch (e) {diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.tsindex 06a38457cc..f821574ae4 100644--- a/src/commands/doctor/checks/local-audits.ts+++ b/src/commands/doctor/checks/local-audits.ts@@ -87,6 +87,11 @@ async function runStubGuard(ctx: DoctorContext): Promise<Check[]> {} catch {checks.push({ name: 'sync_failures', status: 'warn', message: 'Durable sync failure state could not be read; health is unknown.' });}+ try {+ const { checkManagedSyncBacklog } = await import('./managed-sync-backlog.ts');+ const check = engine ? await checkManagedSyncBacklog(engine, orphanRatioSourceId ? [orphanRatioSourceId] : undefined) : null;+ if (check) checks.push(check);+ } catch { /* managed backlog is informational; doctor's other checks report persistence health */ }// 3d. Slug-fallback audit (v0.32.7 CJK wave, codex C7). Informational// count of pages where importFromFile fell back to a frontmatter slugdiff --git a/src/commands/doctor/checks/managed-sync-backlog.ts b/src/commands/doctor/checks/managed-sync-backlog.tsnew file mode 100644index 0000000000..536f0aa75b--- /dev/null+++ b/src/commands/doctor/checks/managed-sync-backlog.ts@@ -0,0 +1,17 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { formatManagedSyncBacklog, readManagedSyncBacklog } from '../../../core/persistence/sync-drain.ts';++const IDLE_MS = 60 * 60_000;++/** #5984: unfinished managed sync cursors, their remaining entries and ETA; warns when one has not advanced for an hour. */+export async function checkManagedSyncBacklog(engine: BrainEngine, sourceIds?: string[]): Promise<Check | null> {+ const backlog = await readManagedSyncBacklog(engine, sourceIds);+ if (!backlog.length) return null;+ const idle = backlog.filter(b => !b.last_progress_at || Date.now() - Date.parse(b.last_progress_at) > IDLE_MS);+ const lines = backlog.map(formatManagedSyncBacklog).join('; ');+ return { name: 'managed_sync_backlog', status: idle.length ? 'warn' : 'ok',+ message: idle.length+ ? `${idle.length} managed sync cursor(s) have not advanced for over an hour. ${lines}. Run the resume command; it drains the backlog in one run (safe to rerun).`+ : `Managed sync catch-up in progress. ${lines}.` };+}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 610d91d223..9dfe4b04cd 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1240,6 +1240,8 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {);const connectors = await (await import('../core/persistence/connector-status.ts')).readConnectorSourceStatuses(engine);+ const drainMod = await import('../core/persistence/sync-drain.ts');+ const backlog = new Map((await drainMod.readManagedSyncBacklog(engine).catch(() => [])).map(b => [b.source_id, b]));if (json) {const enriched = metrics.map((m) => ({...m,@@ -1247,6 +1249,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {sync_holder: syncRunning.get(m.source_id) ?? null,...(ingestion.get(m.source_id) ? { ingestion: ingestion.get(m.source_id) } : {}),...(connectors.get(m.source_id) ? { connector: connectors.get(m.source_id) } : {}),+ ...(backlog.get(m.source_id) ? { managed_backlog: backlog.get(m.source_id) } : {}),}));console.log(JSON.stringify({ schema_version: 1, sources: enriched }, null, 2));return;@@ -1286,6 +1289,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {console.log('');const { connectorStatusLines } = await import('../core/persistence/connector-status.ts');for (const [sourceId, status] of connectors) for (const line of connectorStatusLines(sourceId, status)) console.log(line);+ for (const b of backlog.values()) console.log(` ${drainMod.formatManagedSyncBacklog(b)}`);for (const m of metrics) {const warns: string[] = [];if (!m.local_path) warns.push('no local_path');diff --git a/src/commands/sync-persistence-delegate.ts b/src/commands/sync-persistence-delegate.tsindex f453e07ff5..ca6dc423e1 100644--- a/src/commands/sync-persistence-delegate.ts+++ b/src/commands/sync-persistence-delegate.ts@@ -16,6 +16,8 @@ import type { SyncResult } from './sync.ts';import { buildSingleSyncJsonEnvelope } from '../core/sync-embed-backfill.ts';import { printManagedSyncDiagnostic } from './sync-diagnostics.ts';import { parseDurationSeconds } from '../core/sync-concurrency.ts';+import { runDrain, drainJsonFields, formatDrainSummary, syncOutcome } from '../core/persistence/sync-drain.ts';+import { syncResumeCommand } from '../core/sync-reconcile.ts';export async function parsePersistenceSyncArgs(args:string[],cwd=process.cwd()) {const options:Record<string,unknown>={};@@ -48,30 +50,35 @@ export async function maybeDelegateSyncToPersistence(hostConfig:GBrainConfig|nultry {const params=await parsePersistenceSyncArgs(args);const deadline=params.timeoutSeconds>0?performance.now()+params.timeoutSeconds*1000:Infinity;- let result:SyncResult&{source_id?:string};+ const stop=new AbortController();+ const timer=Number.isFinite(deadline)?setTimeout(()=>stop.abort(),deadline-performance.now()):undefined;console.error('[sync] Delegating to the registered PGLite owner.');- for(;;){- const remaining=deadline-performance.now();- const delegated=await maybeDelegateLocalAdministration('writer_sync',params as unknown as Record<string,unknown>,config,- {timeoutMs:Math.min(86_400_000,Math.max(30_000,remaining+30_000))});- if(!delegated.handled)throw new OperationError('owner_unavailable','The observed PGLite owner stopped before sync admission.','Retry the same sync options to resume its durable cursor.');- result=delegated.result as SyncResult;- if(result.status!=='partial'||!['writer_yield','writer_pending'].includes(result.reason??''))break;- if(performance.now()>=deadline){result={...result,reason:'timeout'};break;}- await new Promise(resolve=>setTimeout(resolve,result.reason==='writer_pending'?250:0));- }+ // #5984: the owner returns one bounded slice per call; the shared drain owns re-entry and the stop rules.+ let result:SyncResult&{source_id?:string};+ try {+ result=await runDrain({signal:stop.signal,announce:true,pass:async()=>{+ const delegated=await maybeDelegateLocalAdministration('writer_sync',{...params,timeoutSeconds:Number.isFinite(deadline)?Math.max(1,Math.ceil((deadline-performance.now())/1000)):params.timeoutSeconds} as unknown as Record<string,unknown>,config,+ {timeoutMs:Math.min(86_400_000,Math.max(30_000,deadline-performance.now()+30_000))});+ if(!delegated.handled)throw new OperationError('owner_unavailable','The observed PGLite owner stopped before sync admission.','Retry the same sync options to resume its durable cursor.');+ return delegated.result as SyncResult;+ }});+ } finally { if(timer)clearTimeout(timer); }+ const sourceId=result.source_id??params.options.sourceId??'default';+ const resume=syncResumeCommand(args,getCliOptions().brain);if(args.includes('--json')) {- await writeStdoutFinal(JSON.stringify({ ...buildSingleSyncJsonEnvelope(result.source_id??params.options.sourceId??'default',result),- ...(result.managedWrite ? { managed_write: result.managedWrite } : {}) })+'\n');+ await writeStdoutFinal(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId,result),+ ...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result,resume,sourceId) })+'\n');printManagedSyncDiagnostic(result, process.stderr);+ for(const line of formatDrainSummary(result,resume,sourceId))process.stderr.write(line+'\n');}else {(await import('./sync.ts')).printSyncResult(result);+ for(const line of formatDrainSummary(result,resume,sourceId))process.stdout.write(line+'\n');if(!params.options.dryRun&&!params.options.noEmbed&&result.added+result.modified>0) {console.error('[sync] embeds deferred — the owner drains them using its configured provider and keys.');}}- if(result.managedWrite||result.status==='blocked_by_failures'||result.reason==='pull_failed'||(await import('./sync/report.ts')).isFailedPartial(result))setCliExitVerdict(1);+ if(syncOutcome(result)==='blocked')setCliExitVerdict(1);return true;}catch(error){if(error instanceof PersistenceIpcTransportError&&error.sent)error=new OperationError('write_pending','The sync acknowledgment was lost; accepted page requests retain their IDs.','Repeat the same sync options to resume the durable cursor.');diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex f1e9408b66..d8c9d87092 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -94,6 +94,10 @@ export interface SyncResult {* everything," the exact misdiagnosis in the #1794 recurrence report.*/bankedFiles?: number;+ /** #5984: the managed drain's verdict and the next step for the agent (see sync-drain.ts). */+ drain?: import('../core/persistence/sync-drain.ts').DrainReport;+ /** #5984: managed cursor position (`index` of `total` manifest entries) and its active drain window. */+ managedCursor?: { index: number; total: number; progress?: import('../core/persistence/sync-run.ts').CursorProgress };/** Fix wave 4: connector items held after repeated item-scoped failures (not blocking freshness). */connectorHolds?: { held: number; newly_held: number; retry_command: string; status_command: string };}@@ -301,7 +305,16 @@ export interface SyncOpts {* `sync_status` IPC polls read. Absent for direct CLI runs (stderr* breadcrumbs already cover that surface).*/- onProgress?: (p: { phase: string; bankedFiles?: number }) => void;+ onProgress?: (p: { phase: string; bankedFiles?: number; total?: number; waived?: boolean }) => void;+ /**+ * #5984: managed sync only. Re-enter the single-pass managed sync until the+ * cursor is done, the caller's signal/deadline stops it, or it is blocked+ * (src/core/persistence/sync-drain.ts). Set by the CLI; jobs and library+ * callers keep the single-pass contract.+ */+ drain?: boolean;+ /** #5984: wall-clock ms the current drain started; managed cursors measure their rate from it. */+ drainStartedAt?: number;}// The git-plumbing cluster (git(), discoverGitRoot, createSyncBaselineCommit,diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex ea0cecf059..3ca533c808 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -68,7 +68,9 @@ Options:checkpoint; unchanged pages are not admitted again.--watch Re-sync continuously on an interval.--interval N Watch-mode interval in seconds (default 60).- --no-pull Skip 'git pull' before the sync (useful for tests).+ --no-pull Skip 'git pull' before the sync. Required on managed+ brains: 'gbrain sources refresh <id>' moves the+ checkout, and sync catches the index up to it.--no-delegate On a PGLite brain with a live 'gbrain serve', syncnormally delegates the run to the serve process overits IPC socket (the lock owner does the work; embeds@@ -106,6 +108,16 @@ Options:parses cleanly.Exit codes: 0 = all sources ok or skipped,1 = any error, 2 = cost-prompt-not-confirmed.+ Managed syncs add outcome (synced | resumable |+ blocked), drain and next {command, safe_to_loop,+ eta_seconds, why}.+ --timeout <dur> Stop the sync after <dur> (per source with --all).+ A managed sync drains its whole backlog in one run+ until it is done, blocked, or this budget ends;+ progress never extends it. A stopped managed drain+ is 'resumable' (exit 0): rerun the same command.+ See docs/guides/live-sync.md (catching up a large+ backlog on managed Postgres).--yes Accept any interactive prompts (CI / non-TTY).See also:diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex 6e7cd0dcc0..73840feafc 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -55,7 +55,9 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<}if (opts.signal?.aborted) return finish(await interruptedBeforeWork());if (managed) {- const result = await (await import('../../core/persistence/sync-run.ts')).performManagedSync(engine, opts);+ const result = opts.drain+ ? await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true)+ : await (await import('../../core/persistence/sync-run.ts')).performManagedSync(engine, opts);if (!opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);return result;}diff --git a/src/commands/sync/report.ts b/src/commands/sync/report.tsindex 2253ad33bb..2be063560c 100644--- a/src/commands/sync/report.ts+++ b/src/commands/sync/report.ts@@ -173,6 +173,11 @@ export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = pwrite(` Check the warnings above (expired or revoked credentials print there), fix the cause, then re-run 'gbrain sync --source <id>'.`);break;}+ // #5984: a managed cursor knows its manifest size; the drain summary prints the next step.+ if (result.managedCursor) {+ write(`Sync PARTIAL at ${result.fromCommit?.slice(0, 8) ?? '<initial>'}: ${result.managedCursor.index} of ${result.managedCursor.total} manifest entries processed, reason=${result.reason ?? 'timeout'} (last_commit unchanged; safe to retry).`);+ break;+ }// v0.41.13.0 (T7 / D-V3-5): --timeout fired before the bookmark write// so last_commit is UNCHANGED. The next sync re-walks the same diff// and content_hash short-circuits already-imported files at ~10ms each.diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex fcb8a423a2..5c90ef0130 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -33,6 +33,7 @@ import {isFailedPartial,} from './report.ts';import { runSyncTrigger } from './trigger.ts';+import { drainJsonFields, formatDrainSummary, syncOutcome } from '../../core/persistence/sync-drain.ts';type SyncAllSourceRow = { id: string; name: string; local_path: string | null; config: Record<string, unknown>; last_commit: string | null; chunker_version: string | null };@@ -114,9 +115,12 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {// Only sources with a non-null local_path participate. A GitHub-only// source (no checkout) has nothing for `sync` to pull. Sources with// syncEnabled=false in config.jsonb are skipped too.- if (syncAll) return await runSyncAll(engine, { ...flags, ...fanout }, { noEmbed, embeddingCredentialError });+ const { syncResumeCommand } = await import('../../core/sync-reconcile.ts');+ const { getCliOptions } = await import('../../core/cli-options.ts');+ const resumeCommand = syncResumeCommand(args, getCliOptions().brain);+ if (syncAll) return await runSyncAll(engine, { ...flags, ...fanout }, { noEmbed, embeddingCredentialError, resumeCommand });- return await runSingleSourceSync(engine, { ...flags, ...fanout }, { sourceId, companyPolicy, noEmbed });+ return await runSingleSourceSync(engine, { ...flags, ...fanout }, { sourceId, companyPolicy, noEmbed, resumeCommand });}async function runSyncBreakLock(@@ -268,13 +272,13 @@ async function resolveCliSyncSource(async function runSyncAll(engine: BrainEngine,flags: SyncFlags & SyncFanoutFlags,- input: { noEmbed: boolean; embeddingCredentialError: Error | undefined },+ input: { noEmbed: boolean; embeddingCredentialError: Error | undefined; resumeCommand: string },): Promise<void> {const {dryRun, full, noPull, noExtract, skipFailed, retryFailed, noSchemaPack, explicitProcessing, includeGitignored,workingTree, missingPathMode, jsonOut, yesFlag, serialFlag, noAutoEmbed, maxSources, concurrency, timeoutSeconds,} = flags;- const { noEmbed, embeddingCredentialError } = input;+ const { noEmbed, embeddingCredentialError, resumeCommand } = input;// v0.41.31: SELECT carries last_commit + chunker_version so the inline// cost preview's "unchanged source → 0" short-circuit can mirror sync's// own "do work?" gate (sync.ts:1057+1075) + doctor's sync_freshness.@@ -442,6 +446,7 @@ async function runSyncAll(strategy: cfg.strategy,concurrency,signal: composeAbortSignals(allInterrupt.signal, controller?.signal),+ drain: true,};// v0.40.6.0 (D6): wrap performSync in withSourcePrefix so every slog /// serr line emitted from inside the sync code path gets prefixed with@@ -514,7 +519,7 @@ async function runSyncAll(const okCount = perSourceResults.filter((r) => r.status === 'ok').length;const errCount = perSourceResults.filter((r) => r.status === 'error').length;- if (jsonOut) emitSyncAllEnvelope({ perSourceResults, embedBackfillBySource, effectiveParallel, okCount, errCount, costGate: embedPlan.costGate });+ if (jsonOut) emitSyncAllEnvelope({ perSourceResults, embedBackfillBySource, effectiveParallel, okCount, errCount, costGate: embedPlan.costGate, resumeCommand });// v0.42.7 (#1696): brain-wide extraction-lag nudge after the --all wave.// Best-effort, stderr-only; skipped on dry-run.@@ -577,12 +582,12 @@ async function dispatchSyncAll(input: {const r = results[i];const src = runnableSources[i];if (r.status === 'fulfilled') {- writeHuman(` ${r.value.result.managedWrite || r.value.result.status === 'blocked_by_failures' ? '✗' : '✓'} ${src.name}: ${r.value.result.status} (added=${r.value.result.added}, modified=${r.value.result.modified}, deleted=${r.value.result.deleted})`);- if (r.value.result.managedWrite || r.value.result.status === 'blocked_by_failures') printSyncResult(r.value.result, humanSink);+ writeHuman(` ${syncOutcome(r.value.result) === 'blocked' ? '✗' : '✓'} ${src.name}: ${r.value.result.status} (added=${r.value.result.added}, modified=${r.value.result.modified}, deleted=${r.value.result.deleted})`);+ if (syncOutcome(r.value.result) === 'blocked') printSyncResult(r.value.result, humanSink);perSourceResults.push({sourceId: src.id,sourceName: src.name,- status: r.value.result.managedWrite || r.value.result.status === 'blocked_by_failures' ? 'error' : 'ok',+ status: syncOutcome(r.value.result) === 'blocked' ? 'error' : 'ok',result: r.value.result,});} else {@@ -605,7 +610,7 @@ async function dispatchSyncAll(input: {perSourceResults.push({sourceId: src.id,sourceName: src.name,- status: result.managedWrite || result.status === 'blocked_by_failures' ? 'error' : 'ok',+ status: syncOutcome(result) === 'blocked' ? 'error' : 'ok',result,});} catch (e: unknown) {@@ -632,8 +637,9 @@ function emitSyncAllEnvelope(input: {okCount: number;errCount: number;costGate: Record<string, unknown> | undefined;+ resumeCommand: string;}): void {- const { perSourceResults, embedBackfillBySource, effectiveParallel, okCount, errCount, costGate } = input;+ const { perSourceResults, embedBackfillBySource, effectiveParallel, okCount, errCount, costGate, resumeCommand } = input;// Sort by source_id at emit time so the envelope is deterministic// even though completion order is not (pMapAllSettled semantics).const sortedSources = perSourceResults@@ -651,6 +657,7 @@ function emitSyncAllEnvelope(input: {// consumers can distinguish a self-healing timeout from a wedge....(r.result.reason ? { reason: r.result.reason } : {}),...(r.result.managedWrite ? { managed_write: r.result.managedWrite } : {}),+ ...drainJsonFields(r.result, resumeCommand, r.sourceId),added: r.result.added,modified: r.result.modified,deleted: r.result.deleted,@@ -683,14 +690,14 @@ function emitSyncAllEnvelope(input: {async function runSingleSourceSync(engine: BrainEngine,flags: SyncFlags & SyncFanoutFlags,- input: { sourceId: string; companyPolicy: Awaited<ReturnType<typeof getCompanyBrainProfile>> | null; noEmbed: boolean },+ input: { sourceId: string; companyPolicy: Awaited<ReturnType<typeof getCompanyBrainProfile>> | null; noEmbed: boolean; resumeCommand: string },): Promise<void> {const {repoPath, watch, interval, dryRun, full, noPull, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack,explicitProcessing, includeGitignored, workingTree, jsonOut, yesFlag, noAutoEmbed, strategyArg, srcSubpath,excludePatterns, includeHiddenPatterns, concurrency, timeoutSeconds,} = flags;- const { sourceId, companyPolicy, noEmbed } = input;+ const { sourceId, companyPolicy, noEmbed, resumeCommand } = input;// v0.41.13.0 (T6) — single-source --timeout: same per-source AbortController// shape as the --all runOne closure. Timer scoped to this CLI invocation;// try/finally clears it after performSync resolves (or throws).@@ -713,6 +720,7 @@ async function runSingleSourceSync(exclude: excludePatterns.length > 0 ? excludePatterns : undefined,includeHidden: includeHiddenPatterns.length > 0 ? includeHiddenPatterns : undefined,signal: composeAbortSignals(singleSourceInterrupt.signal, singleSourceController?.signal),+ drain: true,};// v0.42.42.0 (#2139, Step 4b): single-source `gbrain sync` gets the SAME@@ -777,13 +785,15 @@ async function runSingleSourceSync(process.off('SIGINT', onSingleSourceSigint);}printSyncResult(result, jsonOut ? process.stderr : process.stdout);+ for (const line of formatDrainSummary(result, resumeCommand, sourceId)) (jsonOut ? process.stderr : process.stdout).write(line + '\n');// #3068: a pull_failed partial is NOT a success — unlike timeout-class// partials (which converge on retry), a failing pull will not self-heal.// Exit non-zero so cron/monitoring sees the wedge instead of a green run.// Routed through the owned verdict channel (NOT bare `process.exitCode`,// which PGLite's Emscripten runtime clobbers mid-run — see// src/core/cli-force-exit.ts).- if (result.managedWrite || result.status === 'blocked_by_failures' || isFailedPartial(result)) {+ // #5984: the managed drain's verdict decides; a drain that stopped at its deadline with a pending write is resumable (exit 0).+ if (syncOutcome(result) === 'blocked' || isFailedPartial(result)) {const { setCliExitVerdict } = await import('../../core/cli-force-exit.ts');setCliExitVerdict(1);}@@ -844,7 +854,7 @@ async function runSingleSourceSync(}if (jsonOut) {console.log(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate),- ...(result.managedWrite ? { managed_write: result.managedWrite } : {}) }));+ ...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result, resumeCommand, sourceId) }));}return;}@@ -857,9 +867,11 @@ async function runSingleSourceSync(try {const result = await performSync(engine, { ...opts, full: false });consecutiveErrors = 0;+ const ts = new Date().toISOString().slice(11, 19);if (result.status === 'synced') {- const ts = new Date().toISOString().slice(11, 19);slog(`[${ts}] Synced: +${result.added} ~${result.modified} -${result.deleted} R${result.renamed}`);+ } else if (result.drain && result.drain.outcome !== 'synced') {+ for (const line of formatDrainSummary(result, resumeCommand, sourceId)) slog(`[${ts}] ${line}`);}// Same gate as non-watch: only manage .gitignore on successful sync.// v0.41.13.0 (T7 / D-V3-5): partial joins the deferred posture.diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 1bbde5ae97..49c86ee397 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -55,6 +55,12 @@ export const ERROR_CATALOGUE = {refresh_source_changed: { code: 'refresh_source_changed', docs: 'docs/guides/write-refusals.md#refresh_source_changed' },refresh_recovery_required: { code: 'refresh_recovery_required', docs: 'docs/guides/write-refusals.md#refresh_recovery_required' },worktree_refreshing: { code: 'worktree_refreshing', docs: 'docs/guides/write-refusals.md#worktree_refreshing' },+ // #5984 managed sync drain stop reasons (src/core/persistence/sync-drain.ts).+ sync_drain_deadline: { code: 'writer_pending', docs: 'docs/guides/write-refusals.md#drain-stopped-at-its-deadline' },+ sync_drain_stalled: { code: 'drain_stalled', docs: 'docs/guides/write-refusals.md#drain-stalled' },+ sync_drain_database_contention: { code: 'database_contention', docs: 'docs/guides/write-refusals.md#drain-database-contention' },+ sync_drain_writer_blocked: { code: 'recovery_required', docs: 'docs/guides/write-refusals.md#drain-writer-blocked' },+ sync_drain_blocked_by_failures: { code: 'blocked_by_failures', docs: 'docs/guides/write-refusals.md#drain-blocked-by-a-failed-page' },} as const satisfies Record<string, CatalogueEntry>;export type CatalogueName = keyof typeof ERROR_CATALOGUE;diff --git a/src/core/forward-progress.ts b/src/core/forward-progress.tsindex 0852f49ae7..4e42aac7e3 100644--- a/src/core/forward-progress.ts+++ b/src/core/forward-progress.ts@@ -36,3 +36,19 @@ export function onForwardProgress(listener: ForwardProgressListener): () => voidexport function lastForwardProgressAt(): number {return lastProgressAt;}++/**+ * #5984: the process's out-of-band stop time, registered by the CLI when it+ * arms the sync watchdog. `strict` deadlines stop at `atMs` regardless of+ * progress; progress-aware ones extend while progress keeps arriving. A+ * long-running loop stops itself before a strict deadline so it, not the+ * watchdog, writes the final result.+ */+export interface RunDeadline { atMs: number; strict: boolean }+let runDeadline: RunDeadline | null = null;+export function registerRunDeadline(deadline: RunDeadline | null): void {+ runDeadline = deadline;+}+export function currentRunDeadline(): RunDeadline | null {+ return runDeadline;+}diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsnew file mode 100644index 0000000000..e408cc14a0--- /dev/null+++ b/src/core/persistence/sync-drain.ts@@ -0,0 +1,368 @@+/**+ * #5984: drain a managed sync to completion in one invocation.+ *+ * `performManagedSync` is single-pass by contract (ENG-A1): it returns+ * `partial / writer_pending` when a page's write outlives its wait and+ * `partial / writer_yield` at a slice boundary. Callers that want a whole+ * catch-up (the CLI, `--all`, `--watch`, the PGLite owner delegate) re-enter it+ * through `runDrain`, which owns the stop rules: the caller's signal and+ * deadline, a cooperative stop before a strict out-of-band deadline, named+ * transient retries, blocked heads and the no-progress detector. Every drain+ * ends in one outcome (`synced`, `resumable`, `blocked`) carried on+ * `SyncResult.drain`; the CLI turns it into the exit code and `next`.+ */+import type { BrainEngine } from '../engine.ts';+import type { SyncOpts, SyncResult } from '../../commands/sync.ts';+import { OperationError } from '../ops/contract.ts';+import { getCode, isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';+import { currentRunDeadline, noteForwardProgress } from '../forward-progress.ts';+import { serr } from '../console-prefix.ts';+import { ERROR_CATALOGUE, type CatalogueName } from '../error-catalogue.ts';++export type DrainOutcome = 'synced' | 'resumable' | 'blocked';+/** Why a drain ended short of `synced`. Each value has an error-catalogue entry (DX-A4). */+export type DrainStopReason = 'deadline' | 'drain_stalled' | 'database_contention' | 'recovery_required' | 'owner_unavailable'+ | 'unexpected_file_bytes' | 'unexpected_staging_bytes' | 'blocked_by_failures';+export interface DrainStall {+ request_id: string;+ state: string;+ blocked_reason: string | null;+ head_request_id: string | null;+ head_state: string | null;+ claimable_here: boolean;+ owner_is_this_host: boolean | null;+ stalled_seconds: number;+}+export interface DrainReport {+ outcome: DrainOutcome;+ stop_reason?: DrainStopReason;+ passes: number;+ /** Entries processed by this drain (written + waived). */+ processed: number;+ written: number;+ waived: number;+ remaining: number | null;+ rate_pages_per_min: number | null;+ /** Indexing ETA for the remaining manifest at the observed rate; null while the rate is unknown. */+ eta_seconds: number | null;+ retry_after_ms?: number;+ stall?: DrainStall;+}++const TERMINAL_STATUSES = new Set(['synced', 'first_sync', 'up_to_date', 'dry_run']);+const BLOCKED_HEAD_REASONS = new Set(['recovery_required', 'owner_unavailable', 'unexpected_file_bytes', 'unexpected_staging_bytes']);+const PENDING_PAUSE_MS = 250;+const STALL_MS = 30_000;+const STALL_PASSES = 3;+const TRANSIENT_ATTEMPTS = 3;+const REFRESH_WAIT_MS = 5 * 60_000;+const DEADLINE_MARGIN_MS = 15_000;+const PROGRESS_EVERY_MS = 10_000;++function continues(result: SyncResult): boolean {+ return result.status === 'partial' && (result.reason === 'writer_pending' || result.reason === 'writer_yield');+}++/**+ * The outcome of any sync result. A drained result carries its own verdict.+ * A single-pass result with a still-pending managed write keeps the historical+ * failure verdict, because nothing re-enters it.+ */+export function syncOutcome(result: Pick<SyncResult, 'status' | 'reason' | 'managedWrite' | 'drain'>): DrainOutcome {+ if (result.drain) return result.drain.outcome;+ if (TERMINAL_STATUSES.has(result.status)) return 'synced';+ if (result.status === 'blocked_by_failures' || result.managedWrite) return 'blocked';+ if (result.reason === 'pull_failed' || result.reason === 'connector_item_failures' || result.reason === 'connector_partial') return 'blocked';+ return 'resumable';+}++/**+ * Remaining entries, observed rate and indexing ETA. The rate covers only this+ * drain's window, so downtime between runs never depresses it; zero progress+ * means the rate is unknown, never a zero or infinite ETA.+ */+export function drainEstimate(remaining: number | null, processed: number, elapsedMs: number): { rate_pages_per_min: number | null; eta_seconds: number | null } {+ if (processed <= 0 || elapsedMs <= 0) return { rate_pages_per_min: null, eta_seconds: null };+ const perMin = processed / (elapsedMs / 60_000);+ return { rate_pages_per_min: Math.round(perMin * 10) / 10, eta_seconds: remaining === null ? null : Math.ceil(remaining / perMin * 60) };+}++export function formatDuration(seconds: number): string {+ if (seconds < 60) return `${seconds}s`;+ const h = Math.floor(seconds / 3600), m = Math.floor(seconds % 3600 / 60);+ return h ? `${h}h${String(m).padStart(2, '0')}m` : `${m}m${String(seconds % 60).padStart(2, '0')}s`;+}++/** Named transient failures the drain retries; anything else ends the drain (CEO-A31). */+function transientDelay(error: unknown, attempt: number, refreshWaitedMs: number, baseMs: number): number | null {+ if (error instanceof OperationError && error.code === 'worktree_refreshing') {+ if (refreshWaitedMs >= REFRESH_WAIT_MS) return null;+ const hinted = Number(/retry_after_ms=(\d+)/.exec(String(error.detail ?? ''))?.[1]);+ return Number.isFinite(hinted) && hinted > 0 ? hinted : 1000;+ }+ if (attempt > TRANSIENT_ATTEMPTS) return null;+ const contention = error instanceof OperationError && error.code === 'database_contention';+ if (!contention && !isRetryableConnError(error) && !isStatementTimeoutError(error) && getCode(error) !== '57014') return null;+ return baseMs * 4 ** (attempt - 1);+}++function sleep(ms: number, signal?: AbortSignal): Promise<void> {+ if (signal?.aborted) return Promise.resolve();+ return new Promise(resolve => {+ const timer = setTimeout(done, ms);+ function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }+ signal?.addEventListener('abort', done, { once: true });+ });+}++/** Aborts shortly before a strict out-of-band deadline, so the drain writes the final result instead of the watchdog. */+function cooperativeDeadline(): { signal?: AbortSignal; dispose(): void } {+ const deadline = currentRunDeadline();+ if (!deadline?.strict) return { dispose() {} };+ const remaining = deadline.atMs - Date.now();+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(new Error('run deadline')), Math.max(0, remaining - Math.min(DEADLINE_MARGIN_MS, remaining / 2)));+ timer.unref?.();+ return { signal: controller.signal, dispose: () => clearTimeout(timer) };+}++export interface StallProbe {+ /** A head that needs an operator stops the drain at once; otherwise null. */+ blockedHead(result: SyncResult): Promise<{ reason: DrainStopReason; stall: DrainStall } | null>;+ /** A fingerprint of the awaited request and the worktree head; unchanged across the stall window means no progress. */+ fingerprint(result: SyncResult): Promise<{ key: string; stall: Omit<DrainStall, 'stalled_seconds'> } | null>;+}++export interface DrainInput {+ pass(signal: AbortSignal | undefined, onProgress: NonNullable<SyncOpts['onProgress']>): Promise<SyncResult>;+ signal?: AbortSignal;+ onProgress?: SyncOpts['onProgress'];+ probe?: StallProbe;+ /** Throttled progress lines on stderr (CLI). */+ announce?: boolean;+ /** Test seams: the no-progress window, the pause after a pending write and the transient backoff base. */+ stallMs?: number;+ pauseMs?: number;+ backoffMs?: number;+}++/** Re-enter `pass` until the managed cursor is done, the caller stops it, or it is blocked. */+export async function runDrain(input: DrainInput): Promise<SyncResult> {+ const startedAt = Date.now();+ const coop = cooperativeDeadline();+ const signal = coop.signal && input.signal ? AbortSignal.any([input.signal, coop.signal]) : coop.signal ?? input.signal;+ let passes = 0, attempt = 0, refreshWaitedMs = 0, written = 0, waived = 0, index = 0, total: number | null = null;+ let announcedStart = false, lastLine = 0;+ let stall: { key: string; since: number; passes: number } | null = null;+ const remaining = () => total === null ? null : Math.max(0, total - index);+ const onProgress: NonNullable<SyncOpts['onProgress']> = event => {+ input.onProgress?.(event);+ if (typeof event.total === 'number') total = event.total;+ if (typeof event.bankedFiles === 'number') index = event.bankedFiles;+ if (event.phase === 'managed_sync.start' && input.announce && !announcedStart) {+ announcedStart = true;+ serr(`[sync] managed catch-up: ${total ?? '?'} entries frozen, ${remaining() ?? '?'} remaining; one write request per page.`);+ }+ if (event.phase !== 'managed_sync.page_committed') return;+ if (event.waived) waived++; else written++;+ noteForwardProgress();+ if (input.announce && Date.now() - lastLine >= PROGRESS_EVERY_MS) {+ lastLine = Date.now();+ const estimate = drainEstimate(remaining(), written + waived, Date.now() - startedAt);+ serr(`[sync] ${index}/${total ?? '?'} processed (${written} written, ${waived} waived this run) · `+ + `${estimate.rate_pages_per_min ?? '?'} pages/min · indexing ETA ${estimate.eta_seconds === null ? 'unknown' : formatDuration(estimate.eta_seconds)}`);+ }+ };+ const finish = (result: SyncResult, outcome: DrainOutcome, stopReason?: DrainStopReason, extra?: Partial<DrainReport>): SyncResult => {+ if (result.managedCursor) { index = result.managedCursor.index; total = result.managedCursor.total; }+ const left = outcome === 'synced' ? 0 : remaining();+ if (stopReason === 'deadline' && continues(result)) result = { ...result, reason: 'timeout' };+ return { ...result, drain: { outcome, ...(stopReason ? { stop_reason: stopReason } : {}), passes, processed: written + waived, written, waived,+ remaining: left, ...drainEstimate(left, written + waived, Date.now() - startedAt), ...extra } };+ };+ try {+ for (;;) {+ passes++;+ let result: SyncResult;+ try {+ result = await input.pass(signal, onProgress);+ attempt = 0;+ } catch (error) {+ const delay = transientDelay(error, ++attempt, refreshWaitedMs, input.backoffMs ?? 250);+ if (delay === null || signal?.aborted) throw error;+ if (error instanceof OperationError && error.code === 'worktree_refreshing') refreshWaitedMs += delay;+ await sleep(delay, signal);+ continue;+ }+ if (!continues(result)) {+ if (TERMINAL_STATUSES.has(result.status)) return finish(result, 'synced');+ if (result.status === 'blocked_by_failures') return finish(result, 'blocked', 'blocked_by_failures');+ if (result.managedWrite && result.managedWrite.write_error !== 'write_pending') return finish(result, 'blocked', 'blocked_by_failures');+ const outcome = syncOutcome({ ...result, drain: undefined });+ return finish(result, outcome, outcome === 'resumable' ? 'deadline' : undefined);+ }+ if (signal?.aborted) return finish(result, 'resumable', 'deadline');+ if (result.reason === 'writer_pending' && input.probe) {+ const blocked = await input.probe.blockedHead(result);+ if (blocked) return finish(result, 'blocked', blocked.reason, { stall: blocked.stall });+ const print = await input.probe.fingerprint(result);+ if (print) {+ if (!stall || stall.key !== print.key) stall = { key: print.key, since: Date.now(), passes: 0 };+ else if (++stall.passes >= STALL_PASSES && Date.now() - stall.since >= (input.stallMs ?? STALL_MS) && !print.stall.claimable_here) {+ return finish(result, 'blocked', 'drain_stalled', { stall: { ...print.stall, stalled_seconds: Math.round((Date.now() - stall.since) / 1000) } });+ }+ }+ } else stall = null;+ if (result.reason === 'writer_pending') await sleep(input.pauseMs ?? PENDING_PAUSE_MS, signal);+ }+ } finally {+ coop.dispose();+ }+}++/** Engine-backed stall checks: the awaited request, the oldest unfinished request on its worktree, and claimability here. */+export function engineStallProbe(engine: BrainEngine): StallProbe {+ const read = async (result: SyncResult) => {+ const requestId = result.managedWrite?.write_request.request_id;+ if (!requestId) return null;+ const [row] = await engine.executeRaw<{ state: string; updated_at: string; claim_expires_at: string | null; blocked_reason: string | null; recovering: boolean;+ worktree_id: string | null; head_id: string | null; head_state: string | null; head_updated_at: string | null; owner_host_id: string | null }>(+ `SELECT r.state, r.updated_at::text, r.claim_expires_at::text, r.blocked_reason, r.recovery IS NOT NULL AS recovering, r.worktree_id::text,+ h.id::text AS head_id, h.state AS head_state, h.updated_at::text AS head_updated_at, w.owner_host_id::text+ FROM persistence_requests r+ LEFT JOIN persistence_worktrees w ON w.id = r.worktree_id+ LEFT JOIN LATERAL (SELECT e.id, e.state, e.updated_at FROM persistence_requests e WHERE e.worktree_id = r.worktree_id+ AND (e.state IN ('queued','running','recovering') OR e.recovery IS NOT NULL) ORDER BY e.sequence LIMIT 1) h ON r.worktree_id IS NOT NULL+ WHERE r.id = $1::uuid`, [requestId]);+ return row ? { requestId, row } : null;+ };+ const describe = async (requestId: string, row: NonNullable<Awaited<ReturnType<typeof read>>>['row']): Promise<Omit<DrainStall, 'stalled_seconds'>> => {+ const { localHostId } = await import('./identity.ts');+ const { hasClaimableWrite } = await import('./journal.ts');+ const host = localHostId();+ return { request_id: requestId, state: row.state, blocked_reason: row.blocked_reason, head_request_id: row.head_id, head_state: row.head_state,+ claimable_here: await hasClaimableWrite(engine, host).catch(() => false), owner_is_this_host: row.owner_host_id === null ? null : row.owner_host_id === host };+ };+ return {+ async blockedHead(result) {+ const found = await read(result);+ if (!found) return null;+ const reason = found.row.recovering ? 'recovery_required' : found.row.blocked_reason;+ if (!reason || !BLOCKED_HEAD_REASONS.has(reason)) return null;+ return { reason: reason as DrainStopReason, stall: { ...await describe(found.requestId, found.row), stalled_seconds: 0 } };+ },+ async fingerprint(result) {+ const found = await read(result);+ if (!found) return null;+ const { row } = found;+ return { key: [row.state, row.updated_at, row.claim_expires_at, row.blocked_reason, row.head_id, row.head_state, row.head_updated_at].join('|'),+ stall: await describe(found.requestId, row) };+ },+ };+}++/** The managed-sync drain over one engine; the CLI's managed path. */+export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, announce: boolean): Promise<SyncResult> {+ const { performManagedSync } = await import('./sync-run.ts');+ const drainStartedAt = opts.drainStartedAt ?? Date.now();+ return runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine), announce,+ pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt }) });+}++export interface DrainNext {+ command: string;+ safe_to_loop: boolean;+ retry_after_ms: number;+ eta_seconds: number | null;+ rate_pages_per_min: number | null;+ why: string;+ docs?: string;+}++const STOP_DOCS: Record<DrainStopReason, CatalogueName> = {+ deadline: 'sync_drain_deadline', drain_stalled: 'sync_drain_stalled', database_contention: 'sync_drain_database_contention',+ recovery_required: 'sync_drain_writer_blocked', owner_unavailable: 'sync_drain_writer_blocked', unexpected_file_bytes: 'sync_drain_writer_blocked',+ unexpected_staging_bytes: 'sync_drain_writer_blocked', blocked_by_failures: 'sync_drain_blocked_by_failures',+};++/** What the agent runs next, or null when the sync is done (DX-A2). */+export function drainNext(result: SyncResult, resumeCommand: string, sourceId: string): DrainNext | null {+ const outcome = syncOutcome(result);+ if (outcome === 'synced') return null;+ const d = result.drain;+ const estimate = { eta_seconds: d?.eta_seconds ?? null, rate_pages_per_min: d?.rate_pages_per_min ?? null };+ const docs = d?.stop_reason ? ERROR_CATALOGUE[STOP_DOCS[d.stop_reason]].docs : undefined;+ if (outcome === 'resumable') {+ return { command: resumeCommand, safe_to_loop: true, retry_after_ms: d?.retry_after_ms ?? 0, ...estimate,+ why: 'The sync stopped at its deadline with its cursor and accepted writes intact; the same command resumes where it stopped.', ...(docs ? { docs } : {}) };+ }+ const writerBlocked = d?.stop_reason && d.stop_reason !== 'blocked_by_failures' && d.stop_reason !== 'deadline';+ if (writerBlocked) {+ return { command: `gbrain sources writer status ${sourceId}`, safe_to_loop: false, retry_after_ms: 0, ...estimate,+ why: d!.stop_reason === 'drain_stalled'+ ? `No write for this source made progress for ${d!.stall?.stalled_seconds ?? 30}s and nothing here can claim it. Inspect the writer, fix what it names, then rerun: ${resumeCommand}`+ : `The source's writer needs intervention (${d!.stop_reason}) before more pages can publish. Inspect it, fix what it names, then rerun: ${resumeCommand}`,+ ...(docs ? { docs } : {}) };+ }+ const retry = resumeCommand.includes(' --retry-failed') ? resumeCommand : `${resumeCommand} --retry-failed`;+ return { command: retry, safe_to_loop: false, retry_after_ms: 0, ...estimate,+ why: 'A page failed to publish. Fix the cause named in managed_write / failures first; rerunning without a fix returns the same failure. Ask the user before skipping content.',+ ...(docs ? { docs } : {}) };+}++/** `outcome`, `drain` and `next` for a JSON envelope; empty for results that are not managed syncs. */+export function drainJsonFields(result: SyncResult, resumeCommand: string, sourceId: string): Record<string, unknown> {+ if (!result.drain && !result.managedCursor) return {};+ const next = drainNext(result, resumeCommand, sourceId);+ return { outcome: syncOutcome(result), ...(result.drain ? { drain: result.drain } : {}), ...(next ? { next } : {}) };+}++/** Human lines for the end of a managed sync. */+export function formatDrainSummary(result: SyncResult, resumeCommand: string, sourceId: string): string[] {+ const d = result.drain;+ if (!d) return [];+ const lines = [`Managed sync ${d.outcome}: ${d.processed} entries this run (${d.written} written, ${d.waived} waived)`+ + (d.remaining ? `, ${d.remaining} remaining` : '') + (d.rate_pages_per_min !== null ? `, ${d.rate_pages_per_min} pages/min` : '')+ + (d.remaining && d.eta_seconds !== null ? `, indexing ETA ${formatDuration(d.eta_seconds)}` : '') + '.'];+ if (d.stall) lines.push(` Oldest unfinished request ${d.stall.head_request_id ?? d.stall.request_id} (${d.stall.head_state ?? d.stall.state})`+ + `${d.stall.blocked_reason ? `, blocked_reason=${d.stall.blocked_reason}` : ''}; claimable here: ${d.stall.claimable_here ? 'yes' : 'no'}.`);+ const next = drainNext(result, resumeCommand, sourceId);+ if (next) lines.push(` Next: ${next.command}${next.safe_to_loop ? ' (safe to rerun in a loop)' : ''}`, ` Why: ${next.why}`);+ return lines;+}++export interface ManagedSyncBacklog {+ source_id: string;+ index: number;+ total: number;+ remaining: number;+ rate_pages_per_min: number | null;+ eta_seconds: number | null;+ last_progress_at: string | null;+ resume_command: string;+}++/**+ * Unfinished managed cursors with their remaining entries and the rate of+ * their latest drain window (CEO-A18), readable from any process.+ */+export async function readManagedSyncBacklog(engine: BrainEngine, sourceIds?: string[]): Promise<ManagedSyncBacklog[]> {+ const rows = await engine.executeRaw<{ header: { sourceId: string; index: number; total: number; done?: boolean; progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };+ processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean } } }>(+ `SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'`);+ const flags = { noEmbed: '--no-embed', noExtract: '--no-extract', noSchemaPack: '--no-schema-pack' } as const;+ return rows.map(({ header }) => header).filter(h => h?.sourceId && (!sourceIds || sourceIds.includes(h.sourceId))).map(h => {+ const remaining = Math.max(0, Number(h.total) - Number(h.index));+ const p = h.progress;+ const estimate = p ? drainEstimate(remaining, p.lastIndex - p.startIndex, p.lastAt - p.startedAt) : { rate_pages_per_min: null, eta_seconds: null };+ return { source_id: h.sourceId, index: Number(h.index), total: Number(h.total), remaining, ...estimate,+ last_progress_at: p ? new Date(p.lastAt).toISOString() : null,+ resume_command: `gbrain sync --source ${h.sourceId} --no-pull${(Object.keys(flags) as (keyof typeof flags)[]).filter(k => h.processingOptions?.[k]).map(k => ` ${flags[k]}`).join('')}` };+ });+}++export function formatManagedSyncBacklog(b: ManagedSyncBacklog): string {+ return `${b.source_id}: managed sync cursor at ${b.index}/${b.total} (${b.remaining} remaining`+ + (b.rate_pages_per_min !== null ? `, last drain ${b.rate_pages_per_min} pages/min, indexing ETA ${b.eta_seconds === null ? 'unknown' : formatDuration(b.eta_seconds)}` : ', rate unknown')+ + `). Resume: ${b.resume_command}`;+}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 652047051f..1a10a86424 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -48,7 +48,16 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authorityprocessingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions; overtaken?: true;counts: { added: number; modified: number; deleted: number; chunks: number; renamed?: number;/** #5751: unchanged working-tree files skipped only because a no-op publication could never resolve their admit reason. */- skippedContextualMode?: number; skippedCanonicalBytes?: number }; }+ skippedContextualMode?: number; skippedCanonicalBytes?: number };+ /** #5984: the active drain window (reset when a new drain starts), so a backlog ETA never counts downtime. */+ progress?: CursorProgress; }+export interface CursorProgress { startedAt: number; startIndex: number; lastAt: number; lastIndex: number }+/** #5984: the cursor's progress after advancing to `index`, in the drain window that started at `drainStartedAt`. */+function stampProgress(prior: CursorProgress | undefined, fromIndex: number, index: number, drainStartedAt: number): CursorProgress {+ const now = Date.now();+ return prior && prior.startedAt === drainStartedAt ? { ...prior, lastAt: now, lastIndex: index }+ : { startedAt: drainStartedAt, startIndex: fromIndex, lastAt: now, lastIndex: index };+}const OP = 'managed-sync';type CursorHeader = Omit<Cursor, 'entries' | 'companyPlan'> & { total: number };const header = ({ entries, companyPlan: _plan, ...value }: Cursor): CursorHeader => ({ ...value, total: entries.length });@@ -120,7 +129,9 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], readeleted: cursor.counts.deleted, renamed: cursor.counts.renamed ?? 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}),...(cursor.fileRefusals?.length ? { fileRefusals: cursor.fileRefusals } : {}),- filesImported: cursor.index, bankedFiles: cursor.index, ...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),+ filesImported: cursor.index, bankedFiles: cursor.index,+ managedCursor: { index: cursor.index, total: 'total' in cursor ? cursor.total : cursor.entries.length, ...(cursor.progress ? { progress: cursor.progress } : {}) },+ ...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),...(cursor.counts.skippedContextualMode || cursor.counts.skippedCanonicalBytes ? { legacySkips: {contextualMode: cursor.counts.skippedContextualMode ?? 0, canonicalBytes: cursor.counts.skippedCanonicalBytes ?? 0 } } : {}) };}@@ -395,7 +406,8 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slconst analyzeEvery = await importAnalyzeEveryPages(engine);let batchStart = performance.now(), batchPages = 0, foregroundWaitStart = 0, foregroundBaseline = 0;let creditedPages = 0, creditStarted = 0;- const sliceStarted = performance.now(), sliceFirstIndex = cursor.index;+ const sliceStarted = performance.now(), sliceFirstIndex = cursor.index, drainStartedAt = opts.drainStartedAt ?? Date.now();+ opts.onProgress?.({ phase: 'managed_sync.start', bankedFiles: cursor.index, total: cursor.entries.length });while (!cursor.done) {assertActive();if (!cursor.pending) {@@ -431,11 +443,11 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl// #5470: a frozen import whose publication would change nothing advances the cursor without an admission.const waived = prior ? null : await unchangedSyncImport(engine, cursor, pending, config);if (waived) {- const skipped: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts } }; delete skipped.pending;+ const skipped: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts }, progress: stampProgress(cursor.progress, cursor.index, cursor.index + 1, drainStartedAt) }; delete skipped.pending;if (waived.includes('contextual_mode')) skipped.counts.skippedContextualMode = (skipped.counts.skippedContextualMode ?? 0) + 1;if (waived.includes('canonical_file_differs')) skipped.counts.skippedCanonicalBytes = (skipped.counts.skippedCanonicalBytes ?? 0) + 1;cursor = await saveCursor(engine, key, cursor, skipped);- opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index });+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length, waived: true });assertActive();// A skipped entry still counts toward the caller's slice, so a sliced run yields at the same positions.if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');@@ -485,7 +497,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slreturn withLinks(cursor, result(cursor, cursor.from === null ? 'first_sync' : 'synced'));}// The frozen manifest is shared; only the cursor header changes per page.- const next: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts } }; delete next.pending;+ const next: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts }, progress: stampProgress(cursor.progress, cursor.index, cursor.index + 1, drainStartedAt) }; delete next.pending;if (done.outcome?.noop !== true) {if (pending.intent.kind === 'managed_sync_delete') next.counts.deleted++;else if (pending.intent.renameFrom) next.counts.renamed = (next.counts.renamed ?? 0) + 1;@@ -493,7 +505,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl}next.counts.chunks += Number(done.outcome?.chunks ?? 0);cursor = await saveCursor(engine, key, cursor, next);- opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index });+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length });// F4b: PGLite plans the rest of a large sync against fresh statistics (spec Addendum A item 2).if (analyzeEvery > 0 && cursor.index % analyzeEvery === 0) await maybeRefreshPlannerStats(engine, 'managed_sync', { throttle: false }).catch(() => undefined);assertActive();diff --git a/src/core/sync-reconcile.ts b/src/core/sync-reconcile.tsindex bce6ce2fa3..056c8feb02 100644--- a/src/core/sync-reconcile.ts+++ b/src/core/sync-reconcile.ts@@ -226,6 +226,14 @@ export function syncWatchdogPlan(args: string[], res: HardDeadlineResolution): {};}+/**+ * #5984: the shell-quoted `gbrain sync` command that resumes this run with the+ * same brain, source and cursor-defining options (`args` are the sync argv).+ */+export function syncResumeCommand(args: string[], brain: string | null = null): string {+ return ['gbrain', ...(brain ? ['--brain', brain] : []), 'sync', ...args].map(a => /^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`).join(' ');+}+/*** The stdout notice the sync watchdog prints when it stops a run, so the agent* sees why the sync ended and the exact command that resumes it (a SIGTERMed@@ -234,7 +242,7 @@ export function syncWatchdogPlan(args: string[], res: HardDeadlineResolution): {export function syncDeadlineStopNotice(args: string[], res: HardDeadlineResolution): string {const deadlineSec = Math.round(res.deadlineMs / 1000);const windowSec = res.progressWindowMs ? Math.round(res.progressWindowMs / 1000) : null;- const resume = ['gbrain', 'sync', ...args].map(a => /^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`).join(' ');+ const resume = syncResumeCommand(args);const cause = windowSec? `the ${deadlineSec}s sync deadline (${res.reason}) passed and the run made no progress for ${windowSec}s`: `the ${deadlineSec}s sync deadline (${res.reason}) passed`;diff --git a/test/managed-sync-drain.test.ts b/test/managed-sync-drain.test.tsnew file mode 100644index 0000000000..bbf92453e9--- /dev/null+++ b/test/managed-sync-drain.test.ts@@ -0,0 +1,108 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readManagedSyncBacklog, runDrain } from '../src/core/persistence/sync-drain.ts';+import { performSync } from '../src/commands/sync/perform.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-drain-'));+const engines: BrainEngine[] = [];+const sources: string[] = [];+let closePostgres: (() => Promise<void>) | undefined;+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }+async function fixture(engine: BrainEngine, count: number) {+ const id = `drain-${randomUUID().replace(/-/g, '').slice(0, 20)}`; sources.push(id);+ const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (let i = 0; i < count; i++) writeFileSync(join(root, 'notes', `n${i}.md`), `---\ntitle: Note ${i}\n---\nA durable observation number ${i}.\n`);+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { id, root };+}+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; }+}, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]); await engine.disconnect(); }+ });+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++test('a drain re-enters sliced passes over one cursor until it is synced and records its drain window', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, 5);+ const drainStartedAt = Date.now();+ const result = await runDrain({ pass: (signal, onProgress) =>+ performManagedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, signal, onProgress, drainStartedAt }, { maxPages: 1, maxMs: 60_000 }) });+ expect(result.status).toBe('first_sync');+ expect(result.added).toBe(5);+ expect(result.drain).toMatchObject({ outcome: 'synced', written: 5, waived: 0, remaining: 0 });+ expect(result.drain!.passes).toBeGreaterThanOrEqual(5);+ const requests = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1', [f.id]);+ expect(requests[0]!.n).toBe(6);+ }+}), 180_000);++test('a stopped drain is resumable, its backlog is readable from any process, and a rerun finishes it', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, 6);+ const stop = new AbortController();+ let committed = 0;+ const drainStartedAt = Date.now();+ const first = await runDrain({ signal: stop.signal, pass: (signal, onProgress) => performManagedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, signal, drainStartedAt,+ onProgress: e => { onProgress(e); if (e.phase === 'managed_sync.page_committed' && ++committed === 2) stop.abort(); } }, { maxPages: 1, maxMs: 60_000 }) });+ expect(first.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'deadline' });+ const [backlog] = await readManagedSyncBacklog(engine, [f.id]);+ expect(backlog).toMatchObject({ source_id: f.id, total: 6, resume_command: `gbrain sync --source ${f.id} --no-pull --no-embed` });+ expect(backlog!.remaining).toBeGreaterThan(0);+ expect(backlog!.rate_pages_per_min).not.toBeNull();+ const second = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, drain: true });+ expect(second.drain?.outcome).toBe('synced');+ expect(second.added).toBe(6);+ expect(await readManagedSyncBacklog(engine, [f.id])).toEqual([]);+ }+}), 180_000);++test('the CLI reports outcome, drain and next in one JSON envelope with the outcome exit code', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_NO_DELEGATE: '1' }, async () => {+ const { runSyncInner } = await import('../src/commands/sync/run.ts');+ const { currentExitCode, _resetCliExitVerdictForTests } = await import('../src/core/cli-force-exit.ts');+ const { registerRunDeadline } = await import('../src/core/forward-progress.ts');+ const engine = engines[0]!;+ const capture = async (args: string[]) => {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ _resetCliExitVerdictForTests();+ try { await runSyncInner(engine, args); } finally { console.log = original; }+ const json = lines.filter(line => line.startsWith('{'));+ expect(json).toHaveLength(1);+ return { envelope: JSON.parse(json[0]!), exit: currentExitCode() ?? 0 };+ };+ const stopped = await fixture(engine, 3);+ registerRunDeadline({ atMs: Date.now() - 1, strict: true });+ try {+ const { envelope, exit } = await capture(['--source', stopped.id, '--no-pull', '--no-embed', '--json']);+ expect(exit).toBe(0);+ expect(envelope).toMatchObject({ outcome: 'resumable', drain: { outcome: 'resumable', stop_reason: 'deadline' },+ next: { safe_to_loop: true, command: expect.stringContaining(`sync --source ${stopped.id} --no-pull --no-embed --json`) } });+ } finally { registerRunDeadline(null); }+ const { envelope, exit } = await capture(['--source', stopped.id, '--no-pull', '--no-embed', '--json']);+ expect(exit).toBe(0);+ expect(envelope).toMatchObject({ sync_status: 'first_sync', outcome: 'synced', drain: { outcome: 'synced', remaining: 0 } });+ expect(envelope.next).toBeUndefined();+}), 180_000);diff --git a/test/sync-drain.test.ts b/test/sync-drain.test.tsnew file mode 100644index 0000000000..fe0f76d619--- /dev/null+++ b/test/sync-drain.test.ts@@ -0,0 +1,180 @@+import { afterEach, describe, expect, test } from 'bun:test';+import { OperationError } from '../src/core/ops/contract.ts';+import { lastForwardProgressAt, registerRunDeadline } from '../src/core/forward-progress.ts';+import { drainEstimate, drainJsonFields, drainNext, formatDuration, runDrain, syncOutcome, type StallProbe } from '../src/core/persistence/sync-drain.ts';+import type { SyncResult } from '../src/commands/sync.ts';++const base: SyncResult = { status: 'synced', fromCommit: 'a', toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0,+ chunksCreated: 0, embedded: 0, pagesAffected: [] };+const pending = (index: number, total = 10): SyncResult => ({ ...base, status: 'partial', reason: 'writer_pending', managedCursor: { index, total },+ managedWrite: { source_id: 's', slug: 'p', path: 'p.md', write_error: 'write_pending', reason: 'write_pending', message: 'm', suggestion: 's',+ write_request: { request_id: '00000000-0000-0000-0000-000000000001', state: 'queued', retry_after_ms: 0 } as never } });+const yielded = (index: number, total = 10): SyncResult => ({ ...base, status: 'partial', reason: 'writer_yield', managedCursor: { index, total } });+const done = (total = 10): SyncResult => ({ ...base, managedCursor: { index: total, total } });+const RESUME = 'gbrain sync --source s --no-pull';++function scripted(results: Array<SyncResult | Error>) {+ let i = 0;+ return { calls: () => i, pass: async () => { const next = results[Math.min(i++, results.length - 1)]; if (next instanceof Error) throw next; return next; } };+}++afterEach(() => registerRunDeadline(null));++describe('runDrain', () => {+ test('re-enters writer_pending and writer_yield passes until the cursor is done', async () => {+ const s = scripted([pending(1), yielded(3), pending(4), done()]);+ const result = await runDrain({ pass: s.pass, pauseMs: 1 });+ expect(s.calls()).toBe(4);+ expect(result.drain).toMatchObject({ outcome: 'synced', passes: 4, remaining: 0 });+ expect(syncOutcome(result)).toBe('synced');+ });++ test('a stopped signal ends the drain as resumable with the cursor intact', async () => {+ const stop = new AbortController();+ const s = scripted([pending(2)]);+ const result = await runDrain({ pass: async () => { stop.abort(); return s.pass(); }, signal: stop.signal, pauseMs: 1 });+ expect(result.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'deadline', passes: 1, remaining: 8 });+ expect(result.reason).toBe('timeout');+ expect(drainNext(result, RESUME, 's')).toMatchObject({ command: RESUME, safe_to_loop: true });+ });++ test('a strict registered run deadline stops the drain before the watchdog', async () => {+ registerRunDeadline({ atMs: Date.now() + 60, strict: true });+ const started = Date.now();+ const result = await runDrain({ pass: async () => pending(1), pauseMs: 5 });+ expect(result.drain?.outcome).toBe('resumable');+ expect(Date.now() - started).toBeLessThan(2000);+ });++ test('a progress-aware run deadline does not stop a progressing drain', async () => {+ registerRunDeadline({ atMs: Date.now() - 1, strict: false });+ const s = scripted([pending(1), done()]);+ expect((await runDrain({ pass: s.pass, pauseMs: 1 })).drain?.outcome).toBe('synced');+ });++ test('blocked results end the drain as blocked with a retry command', async () => {+ const failed = await runDrain({ pass: async () => ({ ...base, status: 'blocked_by_failures', failedFiles: 1 }) });+ expect(failed.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'blocked_by_failures' });+ expect(drainNext(failed, RESUME, 's')).toMatchObject({ command: `${RESUME} --retry-failed`, safe_to_loop: false });+ const terminal = pending(3);+ terminal.managedWrite!.write_error = 'revision_conflict';+ terminal.status = 'blocked_by_failures';+ expect((await runDrain({ pass: async () => terminal })).drain?.outcome).toBe('blocked');+ });++ test('named transient failures retry with bounded attempts; others stop at once', async () => {+ const contention = () => new OperationError('database_contention', 'busy');+ const s = scripted([contention(), contention(), done()]);+ expect((await runDrain({ pass: s.pass, backoffMs: 1 })).drain?.outcome).toBe('synced');+ expect(s.calls()).toBe(3);+ const exhausted = scripted([contention(), contention(), contention(), contention(), done()]);+ await expect(runDrain({ pass: exhausted.pass, backoffMs: 1 })).rejects.toThrow('busy');+ const fatal = scripted([new OperationError('permission_denied', 'no'), done()]);+ await expect(runDrain({ pass: fatal.pass })).rejects.toThrow('no');+ expect(fatal.calls()).toBe(1);+ });++ test('worktree_refreshing waits its retry_after_ms hint', async () => {+ const refreshing = new OperationError('worktree_refreshing', 'refreshing');+ refreshing.detail = 'retry_after_ms=5';+ const s = scripted([refreshing, refreshing, refreshing, refreshing, done()]);+ expect((await runDrain({ pass: s.pass })).drain?.outcome).toBe('synced');+ expect(s.calls()).toBe(5);+ });++ test('a recovery-blocked head stops the drain as blocked with the writer command', async () => {+ const stall = { request_id: 'r', state: 'queued', blocked_reason: 'recovery_required', head_request_id: 'h', head_state: 'recovering',+ claimable_here: false, owner_is_this_host: true, stalled_seconds: 0 };+ const probe: StallProbe = { blockedHead: async () => ({ reason: 'recovery_required', stall }), fingerprint: async () => null };+ const result = await runDrain({ pass: async () => pending(2), probe, pauseMs: 1 });+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'recovery_required', stall: { head_request_id: 'h' } });+ expect(drainNext(result, RESUME, 's')).toMatchObject({ command: 'gbrain sources writer status s', safe_to_loop: false });+ });++ test('no change in the awaited request across the stall window stops the drain as drain_stalled', async () => {+ const stall = { request_id: 'r', state: 'queued', blocked_reason: null, head_request_id: 'r', head_state: 'queued', claimable_here: false, owner_is_this_host: false };+ const probe: StallProbe = { blockedHead: async () => null, fingerprint: async () => ({ key: 'same', stall }) };+ const result = await runDrain({ pass: async () => pending(2), probe, pauseMs: 1, stallMs: 20 });+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { request_id: 'r', claimable_here: false } });+ expect(result.drain!.passes).toBeGreaterThanOrEqual(4);+ });++ test('a changing fingerprint never counts as a stall', async () => {+ let n = 0;+ const stall = { request_id: 'r', state: 'running', blocked_reason: null, head_request_id: 'r', head_state: 'running', claimable_here: false, owner_is_this_host: true };+ const probe: StallProbe = { blockedHead: async () => null, fingerprint: async () => ({ key: String(n), stall }) };+ const result = await runDrain({ pass: async () => (++n < 8 ? pending(2) : done()), probe, pauseMs: 1, stallMs: 1 });+ expect(result.drain?.outcome).toBe('synced');+ });++ test('progress events count written and waived pages and note forward progress', async () => {+ const before = lastForwardProgressAt();+ const seen: string[] = [];+ const result = await runDrain({ onProgress: e => seen.push(e.phase), pass: async (_signal, onProgress) => {+ onProgress({ phase: 'managed_sync.start', bankedFiles: 0, total: 4 });+ onProgress({ phase: 'managed_sync.page_committed', bankedFiles: 1, total: 4 });+ onProgress({ phase: 'managed_sync.page_committed', bankedFiles: 2, total: 4, waived: true });+ onProgress({ phase: 'managed_sync.page_committed', bankedFiles: 3, total: 4, waived: true });+ return done(4);+ } });+ expect(result.drain).toMatchObject({ processed: 3, written: 1, waived: 2, remaining: 0 });+ expect(seen).toContain('managed_sync.start');+ expect(lastForwardProgressAt()).toBeGreaterThanOrEqual(before);+ });+});++describe('estimates and outcomes', () => {+ test('zero progress reports an unknown rate, never a zero or infinite ETA', () => {+ expect(drainEstimate(100, 0, 60_000)).toEqual({ rate_pages_per_min: null, eta_seconds: null });+ expect(drainEstimate(100, 10, 60_000)).toEqual({ rate_pages_per_min: 10, eta_seconds: 600 });+ expect(drainEstimate(null, 10, 60_000)).toEqual({ rate_pages_per_min: 10, eta_seconds: null });+ });++ test('formatDuration', () => {+ expect(formatDuration(42)).toBe('42s');+ expect(formatDuration(125)).toBe('2m05s');+ expect(formatDuration(3 * 3600 + 12 * 60)).toBe('3h12m');+ });++ test('a single-pass pending write keeps the historical blocked verdict; failed pulls stay blocked', () => {+ expect(syncOutcome(pending(1))).toBe('blocked');+ expect(syncOutcome({ ...base, status: 'partial', reason: 'pull_failed' })).toBe('blocked');+ expect(syncOutcome({ ...base, status: 'partial', reason: 'timeout' })).toBe('resumable');+ expect(syncOutcome({ ...base, status: 'up_to_date' })).toBe('synced');+ });++ test('JSON fields appear only for managed results', () => {+ expect(drainJsonFields(base, RESUME, 's')).toEqual({});+ expect(drainJsonFields(done(), RESUME, 's')).toEqual({ outcome: 'synced' });+ });+});++describe('managed sync backlog', () => {+ const engineWith = (headers: unknown[]) => ({ executeRaw: async () => headers.map(header => ({ header })) }) as never;++ test('estimates from the latest drain window and builds the resume command from stored options', async () => {+ const { readManagedSyncBacklog, formatManagedSyncBacklog } = await import('../src/core/persistence/sync-drain.ts');+ const now = Date.now();+ const [b] = await readManagedSyncBacklog(engineWith([{ sourceId: 'notes', index: 300, total: 1300,+ progress: { startedAt: now - 120_000, startIndex: 100, lastAt: now, lastIndex: 300 }, processingOptions: { noEmbed: true } }]));+ expect(b).toMatchObject({ source_id: 'notes', remaining: 1000, rate_pages_per_min: 100, eta_seconds: 600,+ resume_command: 'gbrain sync --source notes --no-pull --no-embed' });+ expect(formatManagedSyncBacklog(b!)).toContain('indexing ETA 10m00s');+ });++ test('a cursor with no drain window reports rate unknown, never an infinite ETA', async () => {+ const { readManagedSyncBacklog, formatManagedSyncBacklog } = await import('../src/core/persistence/sync-drain.ts');+ const [b] = await readManagedSyncBacklog(engineWith([{ sourceId: 'notes', index: 0, total: 50 }]));+ expect(b).toMatchObject({ remaining: 50, rate_pages_per_min: null, eta_seconds: null });+ expect(formatManagedSyncBacklog(b!)).toContain('rate unknown');+ expect(await readManagedSyncBacklog(engineWith([{ sourceId: 'other', index: 0, total: 5 }]), ['notes'])).toEqual([]);+ });++ test('a resumed drain window resets, so downtime never depresses the rate', async () => {+ const { readManagedSyncBacklog } = await import('../src/core/persistence/sync-drain.ts');+ const now = Date.now();+ const [b] = await readManagedSyncBacklog(engineWith([{ sourceId: 's', index: 500, total: 600,+ progress: { startedAt: now - 60_000, startIndex: 440, lastAt: now, lastIndex: 500 } }]));+ expect(b!.rate_pages_per_min).toBe(60);+ });+});