Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync status): bounded holds, last_commit and live block, superseded errors, truthful notifier and converged target, pass phase lines (#7243)

garrytan6d1d7d6c92e6
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index 37434be875..6cc6d74163 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -24,7 +24,7 @@
- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no final `.ingested` sidecar; never overlaps itself; its sweep diagnostics and thrown ticks reach stderr, each distinct line once per run, plus the skip reasons whenever their set changes (#6785); pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `bootstrap verify` runs the sweep in-process with `corpus: false` (#6786: its engine has no configured gateway, so every window answered `chat_unavailable`). Before any model call the corpus pass runs the facts-absorb owner-readiness preflight per source (`assertSourceLegacyWriter` in `persistence/filesystem-guard.ts`): a claimed, not activated canonical worktree skips the file as `writer_coordinator_required` and logs `gbrain sources writer status <id>` (#6785; the compact and writeback harvest lanes do the same). A `chat_unavailable` result is not terminal: the windowed file or `.wb-` turn keeps no sidecar, nothing is recorded, and the pass stops (`corpus_chat_unavailable`). Failures thrown after a chat call are counted per window (`<file>.failures.json`, see `corpus-windows.ts`) and skipped as `corpus_window_backoff` / `corpus_window_dead_lettered`; `gbrain sweep --retry-failed [--apply]` previews or clears them (doctor `memory_writeback` names the paid retry as its fix). Pinned by `test/sweep-corpus-chat-unavailable-6786.test.ts` and `test/sweep-corpus-failure-cap-6785.test.ts`. `gbrain sweep --once` is the trusted CLI seam for operator catch-up runs (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.
- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `retireCorpusFile` / `retireCorpusTurns` (#6091) record a file or its off-period turns as finished without extracting (`skipped_reason`; a retire overrides another extractor's lease, and a later rewrite extracts only unrecorded turns). `parseCorpusTurns` (defined in the provider-free `corpus-turns.ts`, re-exported here) splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended`/`changed`/`source_changed`/`unavailable`/`backoff`/`dead_lettered` with cumulative counts; an aborted or `unavailable` window records nothing, and a progress a pre-#6786 build finished with `skipped_reason: chat_unavailable` is rewound under the lease CAS to its retired turns (source binding, totals and links kept). Transport and write errors release the lease and throw; one thrown after a chat call (`extractUnderFailureCount`, observed through the AI invocation preflight) counts against the window's start key (`<turn sha256>@<offset>`) and source incarnation in `<file>.failures.json`: retried on the next sweep, then after 10, 20 and 40 minutes (`CORPUS_WINDOW_RETRY_BASE_MS`), stopped at `CORPUS_WINDOW_FAILURE_CAP` (5); tail growth and error labels never reset it, a commit of that window removes it, and one change of `extractionConfigFingerprint` (model, provider, key presence) re-arms a stopped window once (#6785). `corpusFileCompletion` in `corpus-segments.ts` is the one completion classifier (selection, the under-claim re-check, retention GC; `corpusSidecarState` for the drain and the doctor backlog): a `chat_unavailable` sidecar is pending, and only `done`/`legacy` files get the plain retention (#6786); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).
- `src/core/context/corpus-source.ts` — #6268, the session's source for every corpus file. Writers (`hook.ts` compact/stop/session-end, the OpenClaw `compact()`) call `openSessionCorpus`, which freezes one source per session at first use (GBRAIN_SOURCE, then the `.gbrain-source` dotfile, else unresolved) into `<sid>.source.json` in the `sourced/` spool and stamps it into the file name (`.src-<id>`, `default` included; `_unresolved` cannot collide with a real id). Pre-stamp sweepers never list the spool. `resolveCorpusFileSource` is the sweep/harvest/serve read: the stamp or frozen record, else the brain's cwd chain once (frozen, tier `engine`); legacy top-level files are held (`corpus_legacy_unstamped`) unless a legacy wb stamp, a frozen record or a single-source brain proves the source, never assigned the pass source. The first engine resolution binds the source incarnation; a recreated source holds the session (`corpus_source_incarnation_changed`). `gbrain sweep --assign-corpus <source>` is the operator mapping (preview, then `--apply`); doctor `memory_writeback` reports `details.corpus_source_holds`. Tests: `test/corpus-source-stamp.test.ts`.
-- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: `DELEGATED_SYNC_OPTION_FIELDS` (the fields `SYNC_FLAGS` in `src/core/sync-flags.ts` forwards through the serve, plus `sourceId`, `embedDeferred`, `timeoutSeconds` and `origin`) drives the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) runs without the serve with one actionable line; only the opt-out, a serve not answering its socket and a `stale_serve` serve call `forceOwnConsumer` (#6543), the rest admit writes the serve consumes under `persistence.single_consumer`. #6712 PR 1: neither builder sends `explicitProcessing` any more; the serve validates one from an older CLI by shape and drops it (`WIRE_SKEW_WINDOWS` in `src/core/wire-skew.ts`), and a resume inherits the cursor's processing opt-outs. #6712 PR 2: `WIRE_BOOL_FLAGS` / `VALUE_FLAGS` / `IGNORED_FLAGS` and the managed pick list are views of `SYNC_FLAGS`; a retired field the validator drops comes back as `ignored`, and the serve logs `retiredWireNotice` and streams it to the older client as a progress line (`test/sync-flag-table-6712.test.ts`). The serve's delegated run follows the source's drain lease as holder `serve` (`followDrainLease`, `drainHolder`). Wire `embedDeferred` (sent only when true) carries the cost gate's runtime deferral, so adopting a cursor that stores `noEmbed=false` never embeds in that run. `maybeDelegateManagedSyncToServe` refuses `--skip-failed` / `--include-gitignored` on a managed source with `managed_sync_flag_refused` before any probe or socket call (`test/sync-delegated-options-6696.serial.test.ts`, `test/sync-managed-forbidden-flags-6696.test.ts`). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed). GBRA-133 2b.3: the deferred-embed drain re-arms itself until the backlog is gone: a pass that left work retries after `GBRAIN_DEFERRED_EMBED_RETRY_MS` (default 5000), a failing provider backs off 1x/3x/12x/60x, a running delegated sync defers it at most `DEFERRED_EMBED_BUSY_MAX` (3) times before it drains beside the sync, and a keyless brain keeps the backlog with no provider call or timer; `deferredEmbedDecisions` records each decision.
+- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: `DELEGATED_SYNC_OPTION_FIELDS` (the fields `SYNC_FLAGS` in `src/core/sync-flags.ts` forwards through the serve, plus `sourceId`, `embedDeferred`, `timeoutSeconds` and `origin`) drives the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) runs without the serve with one actionable line; only the opt-out, a serve not answering its socket and a `stale_serve` serve call `forceOwnConsumer` (#6543), the rest admit writes the serve consumes under `persistence.single_consumer`. #6712 PR 1: neither builder sends `explicitProcessing` any more; the serve validates one from an older CLI by shape and drops it (`WIRE_SKEW_WINDOWS` in `src/core/wire-skew.ts`), and a resume inherits the cursor's processing opt-outs. #6712 PR 2: `WIRE_BOOL_FLAGS` / `VALUE_FLAGS` / `IGNORED_FLAGS` and the managed pick list are views of `SYNC_FLAGS`; a retired field the validator drops comes back as `ignored`, and the serve logs `retiredWireNotice` and streams it to the older client as a progress line (`test/sync-flag-table-6712.test.ts`). The serve's delegated run follows the source's drain lease as holder `serve` (`followDrainLease`, `drainHolder`). Wire `embedDeferred` (sent only when true) carries the cost gate's runtime deferral, so adopting a cursor that stores `noEmbed=false` never embeds in that run. `maybeDelegateManagedSyncToServe` refuses `--skip-failed` / `--include-gitignored` on a managed source with `managed_sync_flag_refused` before any probe or socket call (`test/sync-delegated-options-6696.serial.test.ts`, `test/sync-managed-forbidden-flags-6696.test.ts`). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed). GBRA-133 2b.3: the deferred-embed drain re-arms itself until the backlog is gone: a pass that left work retries after `GBRAIN_DEFERRED_EMBED_RETRY_MS` (default 5000), a failing provider backs off 1x/3x/12x/60x, a running delegated sync defers it at most `DEFERRED_EMBED_BUSY_MAX` (3) times before it drains beside the sync, and a keyless brain keeps the backlog with no provider call or timer; `deferredEmbedDecisions` records each decision. #7243: `startDelegatedSync`'s in-process `logLines` option (never on the wire) also writes a verified job's human lines to the serve log, for the resident notifier's runs that nobody polls.
- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.
- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).
- Secret and sensitivity scanning (`src/core/secret-scan.ts`, `src/core/secret-scan-allowlist.ts`, `src/core/secret-scan-stream.ts`, `src/core/secret-scan-work.ts`, `src/core/context/sensitivity-scan.ts`): see [secret-scan.md](secret-scan.md).
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index c6639636db..f9b68a60ce 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -21,12 +21,12 @@
- `src/core/persistence/sync-classify.ts` — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (`SyncPathState`: mode, `T[p]`, the level `L`, presence, `Dp`, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: `held`, `spelling`, `untracked`, `kept`, `delete`, `delete_drift`, `gone`, `deleted_same`, `deleted_edited`, `legacy_same`, `dirty`, `matched`, `adopt`, `reparse`, `db_ahead` (sub-labels `pending`/`db_only`/`unproven`; keep_db writes only `db_only` on a clean committed path; an open full obligation skips `db_only`/`unproven`), `import`, `legacy_unverified`, `keep_db`, `drift` (side `both` or `unknown`); then the overlay (unsettled with open work is `in_flight`). `syncClassAction` is the glossary tag (`none`, `owner`, `repair`); `syncPassKind` decides `idle`, `hold_only` or `full` from the converged state and every obligation. Tests: `test/sync-classify-6712.test.ts` (each row, and the cross product against a reference model built from the state space).
- `src/core/persistence/sync-pass.ts` — the read-only shadow of the level-triggered pass (#6712 PR 4a): `readShadowLevel` reads one managed source's level (`T` via `readTreeLevel`, `X`, working-mode untracked files, `Dp` for committed candidates only or every path in working mode, pages keyset on `pages.id` with the import record by a LATERAL primary-key probe and the revision's attestation in the same statement, holds and retry rows, open requests and pending Git effects, deletion markers) and classifies every path with `sync-classify.ts`; it writes and admits nothing. Postgres reads share one `REPEATABLE READ, READ ONLY` transaction; PGLite runs bounded 2,000-row statements. A company-brain source returns null (it keeps its frozen manifest). `shadowConvergence` wraps it in the receipt, `dryRunConvergence` backs `gbrain sync --dry-run --json`'s `convergence` (with the read-only screen), `statusConvergence` backs `sync status --detail` and doctor, and `idleTickProbe` times the idle tick's reads for the bench (`scripts/bench/sync-convergence.ts`). Tests: `test/sync-pass-shadow-6712.test.ts`.
- `src/core/persistence/sync-convergence.ts` — the convergence receipt (#6712 PR 4a, schema `convergence/1`, always `dry_run: true`): per-class `counts` and `classes` with action tags (`in_flight`, `keep_db_pending` beyond 200 per pass, and `deletes_withheld` when #2828's valve trips are classes too), predicted `decisions` by side after `readOnlySameContentScreen` (the dry run's `sameContentAtOrigin`: a screening request through `prepareManagedSyncMutation(..., { unsaved: true })`, at most 200 paths; one call's preparations share group-publish.ts's `preparationReads` memo plus the binding, trust-config and purge-tombstone reads, read their pages through `importGroupReads`' batch (`reread`), and answer each page's origin, timeline, take-collision and safe-chunk-fence reads from one read per kind per call (`sliceReads`), so a call costs a constant, not a statement per page (GBRA-108); equal content is `same_content_noops`, unscreened is `screen_unknown`), `would_hold`, `db_ahead` by prefix, `legacy_unverified`, `legacy_pageless`, `deletes` with the valve verdict and set hash, up to 20 samples per non-matched class, timings and statement count. `--redact-paths` replaces paths with sha256 prefixes and drops slugs.
-- `src/core/persistence/sync-pass-run.ts` — the live level-triggered pass of a managed, non-company source (#6712 PR 4b, design v3.2 §2.2, §3.1–§3.5, §8, §9), run under the source's drain lease. `runSyncPass` retires an unfinished legacy cursor first (its options seed the episode), pins the pass row (`sync.admission`, `HEAD`, the mode; the row is written with the lease token), decides the kind (`idle` stamps only `last_sync_at` as `up_to_date`; `hold_only`; `full`), then runs at most `PASS_MAX_ROUNDS` (4) rounds: read and classify the level (`sync-pass.ts`), admit `C_k = unsettled − S` in batches of at most `PASS_BATCH_MAX` (10,000; deletes, then imports) through sync-run.ts's cursor machinery on an in-memory batch, and add each settled `(path, level)` to `S` (never admitted twice in one pass). With nothing unsettled and nothing in flight it stamps through `applyPassCheckpoint`; four rounds without converging stop `resumable` / `not_converged`. Every stop records its outcome, stop reason, `settled` and `remaining` on the pass row (a stop mid-batch counts the entries its batch passed); a blocked page refusal is replayed with no new request while nothing that decided it changed. Tests: `test/sync-pass-live-6712.test.ts`, `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-outcomes-6712.test.ts`.
+- `src/core/persistence/sync-pass-run.ts` — the live level-triggered pass of a managed, non-company source (#6712 PR 4b, design v3.2 §2.2, §3.1–§3.5, §8, §9), run under the source's drain lease. `runSyncPass` retires an unfinished legacy cursor first (its options seed the episode), pins the pass row (`sync.admission`, `HEAD`, the mode; the row is written with the lease token), decides the kind (`idle` stamps only `last_sync_at` as `up_to_date`; `hold_only`; `full`), then runs at most `PASS_MAX_ROUNDS` (4) rounds: read and classify the level (`sync-pass.ts`), admit `C_k = unsettled − S` in batches of at most `PASS_BATCH_MAX` (10,000; deletes, then imports) through sync-run.ts's cursor machinery on an in-memory batch, and add each settled `(path, level)` to `S` (never admitted twice in one pass). With nothing unsettled and nothing in flight it stamps through `applyPassCheckpoint`; four rounds without converging stop `resumable` / `not_converged`. Every stop records its outcome, stop reason, `settled` and `remaining` on the pass row (a stop mid-batch counts the entries its batch passed); a blocked page refusal is replayed with no new request while nothing that decided it changed. Tests: `test/sync-pass-live-6712.test.ts`, `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-outcomes-6712.test.ts`. #7243: each round emits `managed_sync.round_level` (paths, target, read time) after its level read and `managed_sync.round_admit` (imports, deletes, in flight) before its import walk, which the drain prints.
- `src/core/persistence/sync-pass-row.ts` — the pass row and the rows beside it (#6712 PR 4b, design §3.4), free of heavy imports so doctor, status, the lease, compaction and GC read it without loading the pass. `managed-sync-pass` (fingerprint `<source>:<incarnation>`) holds `obligations` (baseline, episode, cost, the converged state, mismatch and not-converged streaks, page faults, a blocked request to replay) and `telemetry` (the newest pass's kind, round, outcome, stop reason, candidates, settled, remaining, counts, timings). `writePassRow` writes it at pin under `assertDrainLease` and afterwards only `WHERE lease_token = $token`. Beside it: `sync-origin-deleted` (deletion markers), `sync-deletes-withheld` (the mass-delete trip) and `sync-pass-cost` (one reservation per group); `SYNC_PASS_ROW_OPS` lists the ops the checkpoint GC keeps for a live incarnation. `passHealth` is the one health rule (`blocked`, `not_converged`, `settle_mismatch`, `open_stalled`, `nothing_pending`); `SETTLE_MISMATCH_STREAK` and `NOT_CONVERGED_REPORT_STREAK` are 3.
- `src/core/persistence/sync-pass-readers.ts` — the pass row as the former cursor readers see it (#6712 PR 4b, design §3.7): doctor's movement, git-holds and terminal-failure checks, the drain backlog (`readManagedSyncBacklog`), the blocked-run reader and `sources status` read a non-company source's pass row through `readPassReadings` (`passHealth` plus the checkout HEAD from a hardened `rev-parse` on this host; no checkout means `head: null` and the recorded converged target is trusted). `passResumeArgs` is the plain sync that continues the pass, with the open episode's inherited options; `passStopCode` and `passStuckSince` name a stuck pass. Company sources and unretired legacy cursors keep their cursor arm in each reader. Tests: `test/sync-pass-readers-6712.test.ts`, `test/sync-pass-reader-gaps-6712.test.ts`.
- `src/core/persistence/sync-pass-apply.ts` — what a live pass round does besides admitting one-sided imports and deletes (#6712 PR 4b, design v3.2 §2.5–§2.7, §3.1, §5): holds with side and state for the two-sided and deleted rows (`file_drift` with `side`, `tombstone_edited`, `purged_differs`, `file_gone`), the `settle_mismatch` hold after three passes at one level, arm-1 adoption of a record without a revision on `fileSame`, the bounded legacy sweep (500 per round) that records equal legacy pages on the first full round (GBRA-108: in slices of `LEGACY_SWEEP_SLICE` (100) whose records commit before the next slice, each followed by a pass-row save and a `managed_sync.legacy_swept` progress event the drain's in-pass governor counts, so a pass stopped mid-sweep keeps its slices and the next pass sweeps only the rest; seam `sync:legacy_slice`; tests `test/sync-legacy-sweep-gbra108.test.ts` and its Postgres twin), the mass-delete valve (one `sync-deletes-withheld` record; imports and the stamp proceed), `keep_db` admission (200 per pass), deletion-marker retirement in full rounds, and the remote ending (`reconcile_host_required`: one-sided work commits, drift stays unsettled with no hold). Entry points: `applyPassRound`, `finishPassApply`, `summarizeRound`. Tests: `test/sync-pass-completion-6712.test.ts`.
- `src/core/persistence/sync-pass-episode.ts` — pass episodes and cost (#6712 PR 4b, design §6, §7): `episodeClosure` closes an episode by inclusion or at the configured selection (a narrower episode never stamps `chunker_version`; a widened one releases its extra paths), `passCostDecision` defers paid embedding when the envelope is unknown or spent, and `reservePassCost` writes one `sync-pass-cost` row per admitted group (fingerprint `<source>:<incarnation>:<episode_or_pass_id>:<group_id>`, insert-once) inside the group's admission transaction, so a kill keeps the reservation and a replay adds nothing. Tests: `test/sync-pass-completion-6712.test.ts`.
-- `src/core/persistence/sync-pass-status.ts` — the live `convergence` block of `gbrain sync status` (#6712 PR 4b, design §9, `dry_run: false`): built from the pass row (one primary-key read), the withheld-delete record and `syncAdmissionStatus`, plus `passStatusState`, which keeps a source off `synced` while its newest pass is open or ended unconverged (reasons `pass_unfinished`, `not_converged`, `settle_mismatch`, `deletes_withheld`, `selection_scoped`, `admission_paused`, and `writeback_failed`: a writeback the stamp recorded in `converged.writeback` whose Git effect failed or parked, next step `gbrain sources writer retry-effects --dry-run`). Tests: `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-writeback-fold-6712.test.ts`.
+- `src/core/persistence/sync-pass-status.ts` — the live `convergence` block of `gbrain sync status` (#6712 PR 4b, design §9, `dry_run: false`): built from the pass row (one primary-key read), the withheld-delete record and `syncAdmissionStatus`, plus `passStatusState`, which keeps a source off `synced` while its newest pass is open or ended unconverged (reasons `pass_unfinished`, `not_converged`, `settle_mismatch`, `deletes_withheld`, `selection_scoped`, `admission_paused`, and `writeback_failed`: a writeback the stamp recorded in `converged.writeback` whose Git effect failed or parked, next step `gbrain sources writer retry-effects --dry-run`). Tests: `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-writeback-fold-6712.test.ts`. #7243: `target` is the newest pass's pinned commit (telemetry); `converged_target` is the stored converged obligation's target, null while no stamp backs one, so status never presents the pin as a converged state.
- `src/core/persistence/sync-markers.ts` — the deletion marker and the withheld mass-delete record of a managed Git source (#6712 PR 4b). `writeOriginDeletedMarker` runs in the transaction of every page-row deletion of a managed source (`page-purge.ts`, the purge-mirror replay; `test/page-row-deleters-guard-6712.test.ts` refuses any other deleter) and writes `sync-origin-deleted` (`<source>:<incarnation>:<origin>`, value `{kind:'deleted', blob_oids, page_id, slug}` from the import record) only when it can matter: the origin is in the `last_commit` tree (hardened `ls-tree`) or a file backs it on disk, no other live page records it, and the source is bound and not a company brain; an unreadable checkout counts as present. `retireOriginDeletedMarker` is compare-and-delete on the value read. `writeDeletesWithheld` / `readDeletesWithheld` / `clearDeletesWithheld` keep one `sync-deletes-withheld` record per incarnation (`{target, count, reconcilable, ratio, set_hash, samples≤20}`, `deleteSetHash`: sha256 over the sorted NUL-joined set). Seam: `purge:marker_written`.
- `src/commands/doctor/checks/managed-sync-convergence.ts` — doctor `managed_sync_convergence` (#6712 PR 4a, `deep` tier): the convergence shadow's counts for each managed source this host owns; always `ok` (informational), read-only. Tests: `test/doctor-managed-sync-convergence.test.ts`.
- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesQuery` (the paged same-name query and its binds, built per platform so every bound placeholder is referenced (#6659: an unreferenced bind failed every Windows `delete_page` with 42P18), 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain repair file-drift --source <id> --slug <survivor> --prefer file` that imports the kept file into the survivor; #6712 PR 1: sync holds a survivor that differs from the file `file_drift`, and that hold's fix leads with the same command), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). A purge of a shared-origin page refuses and names the soft delete. Tests: `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.
diff --git a/docs/architecture/key-files/commit-notifier.md b/docs/architecture/key-files/commit-notifier.md
index 0a6bf8b886..f1946c8b2c 100644
--- a/docs/architecture/key-files/commit-notifier.md
+++ b/docs/architecture/key-files/commit-notifier.md
@@ -5,9 +5,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/commit-notifier.ts` — the notifier core, pure over its seams (store, git reads, the runner). One loop per resident: claims the host lease every heartbeat (`GBRAIN_NOTIFIER_HEARTBEAT_MS`, default 10 s, lease two heartbeats; PGLite has no lease and the brain's holder owns), re-reads `sync.on_commit` and `sync.on_commit.sources` every 30 s (`parseOnCommit` is the one parser), lists the host's sources every 60 s, reads HEAD every poll (`GBRAIN_NOTIFIER_POLL_MS`, 3 s; a watch only nudges), and scans wanted markers every 15 s or on a nudge, with the flag off too. Starts on the leading edge of a quiet HEAD move (no rebase/merge/cherry-pick marker, no `index.lock`), then a 400 ms trailing window (`GBRAIN_NOTIFIER_QUIET_MS`). Per-source single flight under a host cap, least recently started first. Keeps a source due across refused starts, failed or blocked runs and resumable stops; retries at `RETRY_BACKOFF_MS` (5 s, 15 s, 1 min, 5 min) and reports `notifier_stalled` past the last tier without progress; `operator_blocked` waits for HEAD to move. Checks the fence before each start. Every decision is recorded (`decisions`) for tests; state and coverage rows are written on change only. Managed sources never take pull markers. Tests: `test/serve-head-watcher.test.ts` (memory store, `test/helpers/notifier-memory-store.ts`).
- `src/core/notifier/store.ts` — the durable rows (migration `v262-commit-notifier.ts`): `sync_wanted_markers` (source + intent freshness|pull|full, `generation` bumped on every upsert, `first_due_at` kept), `sync_notifier_leases` (one owner per host, fence bumped on takeover, release expires it now), `sync_notifier_sources` (state, retry schedule, last error and trace path, classic syncer host, coverage record). A drainer deletes only `WHERE generation =` the value it read (`clearMarker`, `settleMarkers`); freshness is due while `wanted_head IS DISTINCT FROM last_commit` (no ancestry assumption). `recordLocalSyncer` runs where `writeSyncAnchor` advances `last_commit`: records the syncer host and prunes satisfied markers (the CLI's re-check). `missingTable` lets callers on a pre-v262 brain read "nothing monitored".
-- `src/core/notifier/resident.ts` + `src/core/notifier/detect.ts` — production seams and the one start path for every resident (`startResidentNotifier`: serve, serve --http through `src/core/serve-head-watcher.ts`, `gbrain jobs work`, the autopilot daemon). Never awaits: the first pass runs in the background. `GBRAIN_NOTIFIER=0` turns it off per process. Lists managed sources whose worktree this host owns and classic sources whose recorded syncer is this host (or `GBRAIN_NOTIFIER_CLASSIC_SOURCES`), skipping the rest with a reason. Starts syncs through the in-process delegated runner. Trace per source at `<gbrain home>/notifier/<source>.jsonl`. `detect.ts` resolves `--absolute-git-dir` / `--git-common-dir` (linked worktrees) and the quiet predicate. Tests: `test/pathological/s-notifier-classic-serve.test.ts`, `test/pathological/s-notifier-residents.test.ts`.
+- `src/core/notifier/resident.ts` + `src/core/notifier/detect.ts` — production seams and the one start path for every resident (`startResidentNotifier`: serve, serve --http through `src/core/serve-head-watcher.ts`, `gbrain jobs work`, the autopilot daemon). Never awaits: the first pass runs in the background. `GBRAIN_NOTIFIER=0` turns it off per process. Lists managed sources whose worktree this host owns and classic sources whose recorded syncer is this host (or `GBRAIN_NOTIFIER_CLASSIC_SOURCES`), skipping the rest with a reason. Starts syncs through the in-process delegated runner. Trace per source at `<gbrain home>/notifier/<source>.jsonl`. `detect.ts` resolves `--absolute-git-dir` / `--git-common-dir` (linked worktrees) and the quiet predicate. Tests: `test/pathological/s-notifier-classic-serve.test.ts`, `test/pathological/s-notifier-residents.test.ts`. #7243: `runnerStart` starts the delegated run with `logLines`, so a background run nobody polls also writes its human lines (the pass's round phase lines and progress) to the serve log as `[serve-sync] job=<id> …` (`test/sync-pass-phase-lines-7243.serial.test.ts`).
- `src/core/notifier/nudge.ts` + `src/core/notifier/handoff.ts` + `src/commands/sync/trigger.ts` — submitters and drainers of wanted markers. `recordTriggerMarker` picks the intent (managed: freshness at the checkout HEAD; classic: pull) and `recordSyncNudge` answers the versioned, acknowledged `sync_nudge` IPC kind (`src/core/context/sync-ipc.ts`, `resolve-ipc.ts`, bound in `src/mcp/resolve-ipc-binding.ts`). `handoff.ts` is the post-run re-check of the `sync` job handler and the serve's delegated runner: read before the run, settle after, at most one follow-up (a queued job with `maxWaiting: 1`, or a nudge); a lock-busy skip records a marker and completes. `gbrain sync trigger` answers queued / coalesced (`maxPending: 1`) / nudged, exit 0, with the `no_resident` notice when no resident watches the source; on PGLite a live serve takes it over IPC (`maybeTriggerThroughServe` in `src/commands/sync-delegate.ts`, which also records a busy delegated sync). The GitHub push webhook (`submitGitHubPush` in `src/commands/serve-http-webhooks.ts`) records the pushed sha first; a managed source answers 409 `refresh_required`. Tests: `test/pathological/s-notifier-marker-handoff.test.ts`.
-- `src/core/notifier/status.ts` — what users and agents see, from rows only (no git call): `readSourceFreshness` feeds the `freshness` entry of search and query responses (`src/core/ops/search.ts` `buildRetrievalResponseMeta`; current, behind, syncing, unknown, not_monitored), and `readNotifierBlock` / `formatNotifierBlock` the notifier block for sync status and doctor (resident or none with the `gbrain sync --source <id> --no-pull` fix; remote callers get no trace path, pid or host id). An owner is live by its unexpired lease (Postgres) or a running pid on this host (PGLite). Tests: `test/pathological/s-notifier-freshness-status.test.ts`. #7189: with no live notifier owner, `readNotifierBlock` reads the drain lease holder (`readDrainHolder`, `drain_holder`, redacted by `publicDrainHolder` for remote callers) and offers no fix while it progresses, the sync-now fix only once `holderStalled`; `formatNotifierBlock` names it (`test/sync-status-coherence-7189.test.ts`).
+- `src/core/notifier/status.ts` — what users and agents see, from rows only (no git call): `readSourceFreshness` feeds the `freshness` entry of search and query responses (`src/core/ops/search.ts` `buildRetrievalResponseMeta`; current, behind, syncing, unknown, not_monitored), and `readNotifierBlock` / `formatNotifierBlock` the notifier block for sync status and doctor (resident or none with the `gbrain sync --source <id> --no-pull` fix; remote callers get no trace path, pid or host id). An owner is live by its unexpired lease (Postgres) or a running pid on this host (PGLite). Tests: `test/pathological/s-notifier-freshness-status.test.ts`. #7189: with no live notifier owner, `readNotifierBlock` reads the drain lease holder (`readDrainHolder`, `drain_holder`, redacted by `publicDrainHolder` for remote callers) and offers no fix while it progresses, the sync-now fix only once `holderStalled`; `formatNotifierBlock` names it (`test/sync-status-coherence-7189.test.ts`). #7243: with no live owner and no drain holder, a coverage row that names a resident (`owner_kind`, the resident its trace rows name) gives `recorded_resident` (kind, pid, host, `seen_at`, the lapsed `lease_expired_at`; no pid or host remotely), and the fix names that resident and its lapsed lease instead of "No resident … watches this source" (`test/sync-status-truthful-7243.test.ts`).
- `src/core/sync-pending.ts` — GBRA-133 2b.5: the oldest unsynced commit per source and the embedding backlog, read by doctor `managed_sync_latency` and `src/core/source-health.ts`. Behind = checkout HEAD differs from `sources.last_commit` (HEAD only). Dated from the reflog entry that first moved HEAD off `last_commit` (`<git dir>/logs/HEAD` read as a file, last 1 MiB), else the notifier's persisted `first_due_at` (`sync_notifier_sources` while not idle, or a due freshness marker; current incarnation only), else `unknown` with `no_reflog` or `history_rewritten`. `git: false` (a remote doctor) reads the database only; a source the notifier never recorded reads `not_observed`, never current. `readEmbedBacklog` ages live unembedded chunks from `embedding_pending_since` (keyless brains read `disabled`). `managed_sync_latency` grades a waiting commit like a p95 sample (over the target warns, over max(1 h, target) fails, unknown age warns, only with `sync.on_commit` or a target), grades classic sources on a non-managed brain, and reports `details.freshness_by_source` with `keyword_visible` and `embedded` per source (embedded is not graded). Tests: `test/pathological/s-truthful-sync-status.test.ts` + its Postgres twin, `test/sync-freshness-6858.test.ts`.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 231da5febb..6cf5026206 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -11,7 +11,7 @@
- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.
-- **`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`), serve's delegated runner and the `sync` job handler (#6706, bounded by `SyncOpts.deadlineAtMs`) set `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. #6706: `runDrain` takes a caller `deadlineAtMs` (the earlier of it and the strict run deadline wins; a past deadline makes zero passes; a far one re-arms past the 2^31−1 ms timer limit), reports `resumable / deadline` when the deadline lands in a retry backoff, abandons a pass still running `DEADLINE_PASS_GRACE_MS` after it, and `deadlinePassed` stops the extra pass and the next stage; `jobDisposition` classifies a drained result for jobs (`synced`, `continue` when `drainNext` is safe to loop, `needs_operator`). `src/core/minions/handlers/sync-job-drain.ts` runs it in the `sync` job: `planJobDrain` (`drain`, `lanes: 1`, a deadline from `job.deadlineAtMs` or the row's wall-clock limit via `WALL_CLOCK_THRESHOLD_MS_SQL`, at most an hour, less 60 s; job-data controls only from trusted submitters; `sync.job_drain=false` turns it off), throttled progress, and `settleJobDrain` (the CLI's `outcome`/`drain`/`next`, `incomplete`, at most one continuation on a worker-backed brain, priority ≥ 5, whose `next` then observes it). A sync job that finds another live sync job on its source skips `sync_in_progress` (`sync-handler-drain-6706.test.ts`). `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`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`.
+- **`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`), serve's delegated runner and the `sync` job handler (#6706, bounded by `SyncOpts.deadlineAtMs`) set `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. #6706: `runDrain` takes a caller `deadlineAtMs` (the earlier of it and the strict run deadline wins; a past deadline makes zero passes; a far one re-arms past the 2^31−1 ms timer limit), reports `resumable / deadline` when the deadline lands in a retry backoff, abandons a pass still running `DEADLINE_PASS_GRACE_MS` after it, and `deadlinePassed` stops the extra pass and the next stage; `jobDisposition` classifies a drained result for jobs (`synced`, `continue` when `drainNext` is safe to loop, `needs_operator`). `src/core/minions/handlers/sync-job-drain.ts` runs it in the `sync` job: `planJobDrain` (`drain`, `lanes: 1`, a deadline from `job.deadlineAtMs` or the row's wall-clock limit via `WALL_CLOCK_THRESHOLD_MS_SQL`, at most an hour, less 60 s; job-data controls only from trusted submitters; `sync.job_drain=false` turns it off), throttled progress, and `settleJobDrain` (the CLI's `outcome`/`drain`/`next`, `incomplete`, at most one continuation on a worker-backed brain, priority ≥ 5, whose `next` then observes it). A sync job that finds another live sync job on its source skips `sync_in_progress` (`sync-handler-drain-6706.test.ts`). `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`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`. #7243: an announcing drain prints a live pass's round phase lines (`[sync] pass round N: read <n> path(s) at <commit> in <t>; …` and `… importing <n> file(s) and deleting <n> page(s) …`) before the import walk's catch-up and progress lines.
- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. #6712 (one page, one fate): a window group publishes whatever its predecessor became; nothing is cancelled for another page's failure, and dependency edges (`sync-group.ts` `dependencyKeys`, `freezeFollowers`' `taken`) keep two changes of one page out of the same group and out of the window while one is in flight. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the members after it stay admitted at the head of the window, so every admitted request's identity stays in the cursor until its own receipt is read (`groupStep`, `promoteWindow`). Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) only orders: under lanes a member whose predecessor member is unfinished releases its claim and waits; a predecessor that ended, committed or not, lets it publish (#6712). `WINDOW_CANCEL_MESSAGE` and `laneFaultCancelMessage` stay only so older receipts still read as legacy knock-ons. Test: `test/sync-group-member-order.test.ts`.
- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must have ended, committed or not (#6712); a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts releases or falls back to the single path (#6712: never cancels), and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. #6712 PR 1: a resume inherits the cursor's processing opt-outs OR-wise (`adoptCursor`, one CAS that also stamps the resumer's validated authority) and reports a flag it overrode in `inherited_options`; nothing refuses over processing options, and `explicitProcessing` is gone. Admitted requests keep their own intent principal: they are read under it (`admittedBy`), and a writer change drops only unadmitted frozen entries. Every managed pass runs under the source's drain lease (`withDrainLease`, `src/core/persistence/sync-lease.ts`), whose token fences admission, the settled/held CAS, fan-in and the cursor CAS (`assertDrainLease`). 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`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits the pass stamps drain step `finish` and emits `managed_sync.finish`; then (unless `noExtract`) the owner derives links for the source's stale pages through `links-maintenance.ts` under `FINISH_BUDGET_MS` (pages left over stay stale for `gbrain extract --stale`), 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. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out. #6696: the cursor key comes from `selectManagedCursor` (`sync-cursor-key.ts`), which every managed caller crosses: a run without `--strategy` and without a company plan keys a fresh cursor with the source's configured strategy, while an unfinished cursor under the raw key keeps resuming under it, so its admitted requests keep matching. `SyncOpts.embedDeferred` (the cost gate's auto-defer) is frozen on the intent and treated as `noEmbed` by preparation, never as a processing option a resume adopts or compares (`test/persistence-sync-cursor-strategy-6696.test.ts`).
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index 9902badb5f..ed36dac8f5 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -47,7 +47,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark: one probe of the partial index `persistence_requests_sync_watermark`, v223; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the writer-status command beside `data_moving: false`; doctor `managed_sync_not_moving` (warn, scored for `not_moving` only) uses the same rule and command as its fix, and fails on a parked cursor whose admitted queue has no consumer past the ceiling (#6552; fix: the resume sync); `serve` prints one `[gbrain notice]` when a source flips. A failed backlog read is `unknown`, never `nothing_pending` (doctor warns). `/health` stays liveness-only.
- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). The printed step is `MOVEMENT_SUPERVISOR_STEP` from the import-free leaf `src/commands/movement-step.ts` (re-exported here), so upgrade loads it before the swap (#6604). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` (backlog unreadable) exits 1 with `movement_unknown`; other read failures keep their code. `--warn-only` prints the same envelopes and exits 0. Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.
- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`. #7189: each `SourceFreshness` carries `behind` (`readGitBehind`, injectable `BehindReader`: `rev-list --count <last_commit>..HEAD` and the oldest of those commits' committer age; null without a checkout or a synced commit), printed by `formatSyncFreshness`.
-- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error.
+- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error. #7243 (GBRA-133 PR 3a): every status carries `last_commit` (`sources.last_commit`) and `live` (the drain-lease holder from `readDrainHolder`, read only when the source read's `gbrain_cycle_locks` probe finds a row, with `job_id` for a Minions sync job and `stalled` from `holderStalled`; `live_job_id` also takes a job holder of a pass); `supersedingAttempt` marks a `last_error` `superseded` (`by`, `age_seconds`) when evidence newer than the failure row passed its phase (`resume` < `discovery` < `freeze`/`admission` < `receipt`/`checkpoint`; evidence: the pass row's `started_at` (pin), a level read (`timings_ms` set or an `up_to_date` idle tick), an uncommitted managed import or delete admitted later, a later commit). The CLI (`sync/operator.ts` `holdsListing`) bounds the holds: `holds_summary` (`topCounts` by code and by state: `needs_human`, `actionable`, `held`) over every hold, then `PLAIN_STATUS_HOLDS` (20) rows needs-human first, or with `--detail` a page of the shared listing contract (`bounded-listing.ts`, kind `sync_status_holds:<source>:<state>`, `--limit`/`--cursor`/`--all`, `--hold-state`), `holds_page` only when a page left rows out or took a cursor, the rows last. Test: `test/sync-status-truthful-7243.test.ts` (both engines).
- `src/core/persistence/resolve-paths.ts` — GBRA-150 `resolveSourcePaths`: what gbrain did with each file path of a source, by its own rules, so a landing check stops copying them. Per path: the sync slug (`resolveSlugForPath`), presence in the last synced commit and at HEAD (Git object reads), the skip reason (`unsyncableReason`, plus `typed_frontmatter` for a skipped metafile), the open hold, the live page by origin (`source_path`) and by slug (`slug_owner` when another file owns it, so a case-folded twin never reads as this file's page), a differing frontmatter `slug:`, chunk and embedding counts (`listEmbeddingStateRows` with its `slugs` filter), and one of `RESOLVE_PATH_STATES` with `searchable` (true / 'keyword' / false), `why` and an existing-command `fix`. Bounded: at most 200 paths, indexed lookups only, nothing written. Tests: `test/sources-resolve-path.test.ts`.
- `src/core/persistence/landing-gaps.ts` — GBRA-150 `readLandingGaps`: committed managed_sync receipts of the last 24 h (at most 2,000, newest first through the watermark index, 2 s statement probe; a timeout reads `unknown`, never ok) whose page is still missing, has chunks waiting for vectors, has no chunks, or is quarantined past `sync.freshness_target_seconds`; one row per page with reason and fix. Consumers: `sync status --detail` `landing` / `landing_read` (`sync-status.ts`) and doctor `sync_landing_gaps`. Tests: `test/sync-landing-gaps.test.ts`.
- `src/commands/doctor/checks/landing-gaps.ts` — GBRA-150 doctor `sync_landing_gaps` (registered after `partial_embedding`, one of `CHEAP_INCIDENT_CHECKS`): warns per source with the gap count by reason and the first fix from `readLandingGaps`; `unknown` read stays a warning, never ok. Tests: `test/doctor-sync-landing-gaps.test.ts`.
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 90e5ba22bc..01f8f20566 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -47,6 +47,16 @@ moving again; ask me only about the ones gbrain will not decide by itself."*
`terminal_failures_read`, `checkpoint_blockers_read` and `cursors_read` say
`not_read` with the `--detail` command as `fix`. Never read a `not_read`
field as "none"; run the fix when the step needs it.
+ `last_commit` is the commit the source's sync applied through, and `live`
+ names the process holding its drain lease (a serve pass, a sync job, a CLI
+ sync), with its heartbeat, `progress` and `stalled`; null means nothing is
+ syncing it now. Holds are bounded: `holds_summary` counts every hold by
+ code and by state (`needs_human`, `actionable`, `held`), and `holds` lists
+ the first 20, needs-human first. When it leaves rows out, `holds_page`
+ names `next_command`; `--detail` pages 100 at a time, `--hold-state
+ needs_human` lists only the holds a person decides. A `last_error` with
+ `superseded` (`by`, `age_seconds`) is history: a later attempt got past
+ the phase it failed in, so it drives neither `state` nor `next`.
2. If `needs_human` is false and nothing committed in the last ten minutes,
run `unblock --apply`: it performs the safe action for every hold that has
one, refuses the rest by name, and prints the sync to run. For a content
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 42de5f3ab6..b022d8a359 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -362,7 +362,7 @@ export interface SyncOpts {
* breadcrumbs already cover that surface).
*/
onProgress?: (p: { phase: string; bankedFiles?: number; total?: number; waived?: boolean; group?: number;
- /** #5984 lanes (phase `managed_sync.lanes`). */ lanes?: { effective: number; stepDown: string | null; overlapped: number; fallbacks: number } }) => void;
+ /** #5984 lanes (phase `managed_sync.lanes`). */ lanes?: { effective: number; stepDown: string | null; overlapped: number; fallbacks: number }; /** #7243: a pass round (`managed_sync.round_level`, `managed_sync.round_admit`). */ round?: { round: number; target: string; paths: number; read_ms?: number; imports?: number; deletes?: number; in_flight?: number } }) => 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
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index 659960bbf3..9e911527a1 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -12,7 +12,9 @@ import type { BrainEngine } from '../../core/engine.ts';
import { cliRenderContext, renderAction } from '../../core/agent-output.ts';
import { writeJsonDocument } from '../../core/cli-force-exit.ts';
import { opError } from '../../core/ops/contract.ts';
-import { readSyncStatus, unblockSync, type SyncStatus } from '../../core/persistence/sync-status.ts';
+import { readSyncStatus, unblockSync, type SyncStatus, type SyncStatusHold } from '../../core/persistence/sync-status.ts';
+import { pageSortedRows, topCounts } from '../../core/bounded-listing.ts';
+import { nextListingCommand, parseListingFlags } from '../../core/bounded-listing-cli.ts';
import { HOLD_ATTEMPTS_NEEDS_HUMAN, HOLD_ESCALATE_MS } from '../../core/persistence/sync-fault-class.ts';
import { CONTENT_REPAIR_HOLD_KINDS } from '../../core/repair/content-lane.ts';
import { resolveSourceIdEngineFree } from '../../core/source-resolver.ts';
@@ -20,8 +22,14 @@ import { resolveSourceIdEngineFree } from '../../core/source-resolver.ts';
/** The hold codes the content-repair lane clears today, for the help text. */
const CONTENT_HOLD_CODES = Object.entries(CONTENT_REPAIR_HOLD_KINDS).filter(([, kind]) => kind).map(([code]) => code).join(', ');
+/** #7243: how the text status names what superseded a last error. */
+const SUPERSEDED_TEXT: Record<NonNullable<NonNullable<SyncStatus['last_error']>['superseded']>['by'] & string, string> = {
+ commit: 'the sync committed a page', admission: 'a later sync admitted a page', level_read: 'a later pass read the source', pin: 'a later pass started',
+};
+
export function printSyncStatusHelp(): void {
console.log(`Usage: gbrain sync status --source <id> [--detail] [--json]
+ [--limit <n>] [--cursor <next_cursor>] [--all] [--hold-state <state>]
Where a managed catch-up stands and what to do next, for an operator agent:
the newest sync pass (convergence: outcome, round, candidates, settled,
@@ -57,6 +65,17 @@ action (who finishes it):
Committed mode reads a file's working-copy dirtiness only for candidates, so
dirty counts only paths sync would otherwise admit.
+Every status names last_commit (the commit sync applied through) and live (the
+process holding the drain lease, a serve pass included, with its heartbeat and
+progress; null when nothing holds it).
+
+Holds are bounded: holds_summary counts every hold by code and by state
+(needs_human | actionable | held), then holds lists the first ${PLAIN_STATUS_HOLDS}
+(needs_human first). With --detail the list pages (100 per page): holds_page
+carries returned, limit, complete, next_cursor and next_command; --limit <n>
+sets the page size, --cursor <next_cursor> prints the next page, --all prints
+every hold, and --hold-state <state> lists only that state.
+
Decision table: docs/guides/sync-unblock-runbook.md
`);
}
@@ -132,10 +151,39 @@ function sourceOf(args: string[]): string {
return source;
}
+/** #7243: the holds a plain status lists (the rest are counted in `holds_summary`; `--detail` pages through them). */
+export const PLAIN_STATUS_HOLDS = 20;
+const HOLD_STATES = ['needs_human', 'actionable', 'held'] as const;
+type HoldState = typeof HOLD_STATES[number];
+/** A hold's state: a person decides, `sync unblock` has a safe action for it, or it stays held (by design or until its file changes). */
+const holdState = (hold: SyncStatusHold): HoldState => hold.needs_human ? 'needs_human' : hold.safe_actions[0] !== 'none' ? 'actionable' : 'held';
+
+/**
+ * #7243: the holds of one status read as a bounded listing: counts by code and state over every hold, then one page,
+ * needs-human first (a plain status lists the first `PLAIN_STATUS_HOLDS`; `--detail`, `--limit`, `--cursor` and `--all` page).
+ * A first page that holds every hold keeps the earlier shape (`holds` only, beside the summary).
+ */
+function holdsListing(holds: readonly SyncStatusHold[], args: string[], sourceId: string) {
+ const { request, rest } = parseListingFlags(args, 'gbrain sync status');
+ const stateAt = rest.indexOf('--hold-state');
+ const state = stateAt >= 0 ? rest[stateAt + 1] : undefined;
+ if (stateAt >= 0 && !HOLD_STATES.includes(state as HoldState)) {
+ throw opError('invalid_params', `--hold-state must be one of ${HOLD_STATES.join(', ')} (got "${state ?? ''}").`, `Example: gbrain sync status --source ${sourceId} --detail --hold-state needs_human --json`);
+ }
+ const sized = args.some(a => a === '--all' || a === '--limit' || a.startsWith('--limit='));
+ const page = pageSortedRows(state ? holds.filter(hold => holdState(hold) === state) : holds, hold => [String(HOLD_STATES.indexOf(holdState(hold))), hold.path],
+ args.includes('--detail') || sized ? request : { ...request, limit: PLAIN_STATUS_HOLDS }, `sync_status_holds:${sourceId}:${state ?? 'all'}`);
+ const summary = { total: holds.length, by_code: topCounts(holds, hold => hold.code, 20), by_state: topCounts(holds, holdState, 20) };
+ const paging = page.complete && request.cursor === undefined ? null
+ : { returned: page.returned, limit: page.limit, complete: page.complete, next_cursor: page.next_cursor, next_command: nextListingCommand(['gbrain', 'sync', 'status', ...rest], page) };
+ return { summary, paging, rows: page.rows };
+}
+
export async function runSyncStatus(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) return printSyncStatusHelp();
const sourceId = sourceOf(args);
const status = await readSyncStatus(engine, sourceId, { detail: args.includes('--detail') });
+ const listing = holdsListing(status.holds, args, sourceId);
const ctx = cliRenderContext();
// #6696 (A4): the capacity picture rides every status read (unthrottled), from the 60 s snapshot.
// #6803 C4: one bounded wait per status read, shared with its notices; a slow snapshot reads unknown for this call only.
@@ -150,22 +198,39 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis
const notifierBlock = await readNotifierBlock(engine, sourceId).catch(() => null);
const notifier = notifierBlock && { ...notifierBlock, fix: notifierBlock.fix ? renderAction(notifierBlock.fix, ctx) : null };
const read = (r: typeof status.cursors_read) => r.status === 'read' ? r : { ...r, fix: renderAction(r.fix, ctx) };
- const rendered = { ...status, holds: status.holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })),
+ const { holds: _holds, ...shown } = status;
+ const rendered = { ...shown,
git_push_holds: status.git_push_holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null,
checkpoint_blockers_read: read(status.checkpoint_blockers_read), cursors_read: read(status.cursors_read), terminal_failures_read: read(status.terminal_failures_read),
landing_read: read(status.landing_read), landing: status.landing?.status === 'ok' ? { ...status.landing, pages: status.landing.pages.map(page => ({ ...page, fix: page.fix ? renderAction(page.fix, ctx) : null })) } : status.landing,
- capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, freshness, notifier, ...(notices.length ? { notices } : {}) };
+ capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, freshness, notifier, ...(notices.length ? { notices } : {}),
+ // #7243: the holds come last, summary first, so a reader can stop before the rows.
+ holds_summary: listing.summary, ...(listing.paging ? { holds_page: listing.paging } : {}), holds: listing.rows.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })) };
if (args.includes('--json')) return writeJsonDocument(JSON.stringify(rendered, null, 2));
const c = status.cursor;
console.log(syncStatusHeadline(status));
console.log(` ${c ? c.done ? `last run finished at ${c.index}/${c.total} (pinned ${c.pinned_target?.slice(0, 8) ?? '?'})` : `cursor ${c.index}/${c.total} at pinned target ${c.pinned_target?.slice(0, 8) ?? '?'}`
+ `${c.last_advance_at ? `, last advance ${c.last_advance_at}` : ''}` : 'no managed cursor'}`);
console.log(` committed in the last 10 minutes: ${status.committed_last_10m}${status.rate_pages_per_min !== null ? `, ${status.rate_pages_per_min} pages/min` : ''}`);
+ // #7243: the applied-through commit, the job doing the work, and what the newest pass pinned against what a stamp backs.
+ console.log(` last synced commit: ${status.last_commit?.slice(0, 8) ?? 'none yet'}`);
+ const live = status.live;
+ console.log(` live: ${live ? `${live.kind}${live.job_id !== null ? ` job #${live.job_id}` : live.id ? ` ${live.id}` : ''}${live.pid ? ` (PID ${live.pid})` : ''} holds the drain lease since ${live.started_at ?? '?'}`
+ + `${live.progress ? `, ${live.progress.committed} page(s) committed since` : ''}${live.stalled ? ', STALLED (no commit or save for the stall window)' : ''}` : 'nothing holds the drain lease'}`);
+ const pass = status.convergence?.dry_run === false ? status.convergence : null;
+ if (pass) console.log(` newest pass: ${pass.outcome}${pass.stop_reason ? ` (${pass.stop_reason})` : ''}, round ${pass.round}, pinned ${pass.target.slice(0, 8)}; `
+ + `${pass.converged_target ? `last converged at ${pass.converged_target.slice(0, 8)} (${pass.converged_at})` : 'no converged stamp stored'}`);
if (freshness) console.log(` freshness: ${formatSyncFreshness(freshness)}`);
if (notifierBlock) console.log(` ${formatNotifierBlock(sourceId, notifierBlock)}`);
console.log(` holds: ${status.holds.length}${status.holds.length ? ` (${status.holds.filter(h => h.needs_human).length} need a person)` : ''}; last error: ${status.last_error ? `${status.last_error.code} [${status.last_error.class}]` : 'none'}`);
- for (const hold of status.holds) console.log(` ${hold.path}${hold.slug ? ` (${hold.slug})` : ''}: ${hold.code} [${hold.class}] safe: ${hold.safe_actions.join(',')}${hold.needs_human ? ` NEEDS HUMAN: ${hold.human_reason}` : ''}${hold.attempts > 1 ? ` (held ${hold.attempts} times)` : ''}`);
- if (status.last_error) console.log(` ${status.last_error.path ?? ''}: ${status.last_error.code}${status.last_error.superseded ? ` (superseded: the sync committed a page at ${status.last_error.superseded.at}, after this error)` : ` safe: ${status.last_error.safe_actions.join(',')}${status.last_error.needs_human ? ` NEEDS HUMAN: ${status.last_error.human_reason}` : ''}`}`);
+ for (const hold of listing.rows) console.log(` ${hold.path}${hold.slug ? ` (${hold.slug})` : ''}: ${hold.code} [${hold.class}] safe: ${hold.safe_actions.join(',')}${hold.needs_human ? ` NEEDS HUMAN: ${hold.human_reason}` : ''}${hold.attempts > 1 ? ` (held ${hold.attempts} times)` : ''}`);
+ if (listing.paging && !listing.paging.complete) {
+ const codes = Object.entries(listing.summary.by_code.counts).map(([code, n]) => `${code} ${n}`).join(', ');
+ console.log(` ... ${status.holds.length - listing.rows.length} more not listed here (${codes}${listing.summary.by_code.other ? `, other ${listing.summary.by_code.other}` : ''}); `
+ + `${listing.paging?.next_command ? listing.paging.next_command.join(' ') : `gbrain sync status --source ${sourceId} --detail --json`} lists them`);
+ }
+ const superseded = status.last_error?.superseded;
+ if (status.last_error) console.log(` ${status.last_error.path ?? ''}: ${status.last_error.code}${superseded ? ` (superseded: ${SUPERSEDED_TEXT[superseded.by ?? 'commit']} at ${superseded.at}, after this error${superseded.age_seconds !== undefined ? `, recorded ${Math.round(superseded.age_seconds / 60)} min ago` : ''})` : ` safe: ${status.last_error.safe_actions.join(',')}${status.last_error.needs_human ? ` NEEDS HUMAN: ${status.last_error.human_reason}` : ''}`}`);
const ob = status.oldest_blocker;
console.log(` oldest unfinished request: ${ob.status === 'unknown' ? `unknown (${ob.reason})` : ob.request ? `${ob.request.request_id} (${ob.request.state}${ob.request.step ? `, step ${ob.request.step}` : ''}${ob.request.blocked_by ? `, blocked by ${ob.request.blocked_by.predicate}` : ''})` : 'none'}`
+ `; recovery records: ${status.recovery.status === 'unknown' ? `unknown (${status.recovery.reason})` : status.recovery.count}`);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index c860518a7a..ffe2308e7c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1062,6 +1062,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.344.0', text: 'On a transaction-mode pooler URL (PgBouncer or Supabase port 6543, `prepare=false`, or `GBRAIN_PREPARE=false`), gbrain now pipelines the statements of one transaction on the server connection the pooler pins for it, instead of waiting one round trip per statement, so a sync or write over a slow link finishes in fewer round trips. It still never sends a statement behind one that may end the transaction (COMMIT, ROLLBACK, END, ABORT, PREPARE TRANSACTION), never pipelines autocommit statements on such a URL, and keeps prepared statements off, so the pooler cannot hand a statement to another client\'s connection. Set `GBRAIN_PG_TXN_PIPELINE=0` to send one statement per round trip again.' },
{ since: '0.60.344.0', text: 'Doctor `managed_sync_latency` now grades the commit that is still waiting, not only commits that already synced: with `sync.on_commit` on or `sync.freshness_target_seconds` set, a source whose checkout HEAD has waited past the target (default 300 s) warns and past one hour fails, dated from the reflog entry that moved HEAD or the notifier\'s recorded first_due_at, and a waiting commit it cannot date (no reflog, rewritten history) warns as unknown. It grades classic sources the same way and reports keyword-visible and embedded freshness per source (`details.freshness_by_source`). `gbrain sources status` compares HEAD only (an uncommitted edit is no longer lag) and dates a behind source\'s lag from when the commit landed instead of from the last no-op sync.' },
{ since: '0.60.344.0', text: '`gbrain sources mirror-readonly <id> --dry-run` and `gbrain sources mirror-writable <id> --dry-run` now print the change they would make with a `(dry-run; no side effects)` banner and write nothing (#7086); before, both ignored `--dry-run` and set or cleared the read-only mirror flag.' },
+ // GBRA-133 PR 3a lane S (#7243 truthful sync status). `since` is stamped at the merge slot.
+ { since: 'TBD', text: '`gbrain sync status --json` now prints at most 20 holds without `--detail`: `holds_summary` counts every hold by code and by state (`needs_human`, `actionable`, `held`), and `holds` lists the first 20, needs-human first, after every other field. When holds are left out, `holds_page` carries `returned`, `limit`, `complete`, `next_cursor` and `next_command`; `--detail` pages 100 holds at a time, `--limit <n>` and `--cursor <next_cursor>` page, `--all` prints every hold, and `--hold-state <state>` lists one state. A source whose holds fit on one page prints them as before. The text status lists the same 20 and says how many more there are.' },
+ { since: 'TBD', text: '`gbrain sync status` always reports `last_commit` (the commit the source\'s sync applied through) and `live`: the process holding the source\'s drain lease (a serve pass, a sync job, a CLI sync or the cycle) with its pid, heartbeat and progress, `job_id` for a Minions sync job and `stalled`, or null. `live_job_id` also names a sync job that drains a pass, not only a legacy cursor. `convergence` adds `converged_target`, the commit the stored converged obligation records (null when no stamp backs one); `convergence.target` stays the newest pass\'s pinned commit.' },
+ { since: 'TBD', text: 'A `last_error` in `gbrain sync status` now also reads `superseded` once a later attempt got past the phase it failed in (a later pass started, read the source, admitted a page or committed one), with `by` naming which and `age_seconds`, and it then sets neither `needs_human`, `state` nor `next`; before, only a later committed page superseded it. The notifier block of `sync status` and doctor adds `recorded_resident`: when its row names a resident whose notifier lease lapsed, the fix names that resident instead of saying no resident watches the source. A managed pass prints `[sync] pass round N: read ...` after each level read and `... importing N file(s) ...` before its import walk, and a resident notifier\'s background run also writes its lines to the serve log (`[serve-sync] job=<id> ...`).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 4a2f754a30..f754584e82 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -78,7 +78,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
@@ -107,7 +107,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--timings', '--trust', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--timings', '--wait', '--yes'],
- 'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
+ 'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--concurrency', '--confirm-destructive', '--content-root', '--cursor', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--hold-state', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--request-id', '--scopes', '--source', '--timeout'],
'repair': ['--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--close', '--diff', '--expect', '--ff-only', '--force', '--force-break-lock', '--from', '--full', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--url', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],
@@ -127,10 +127,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
- 'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
+ 'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],
- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],
diff --git a/src/core/notifier/resident.ts b/src/core/notifier/resident.ts
index 0754b76787..bb28ff93a3 100644
--- a/src/core/notifier/resident.ts
+++ b/src/core/notifier/resident.ts
@@ -135,7 +135,7 @@ export function runnerStart(engine: BrainEngine): Pick<CommitNotifierOptions, 's
const hard = deadline ? Math.max(1, Math.round(deadline.deadlineMs / 1000)) : 3600;
const timeoutSeconds = req.sliceSeconds ? Math.min(hard, Math.max(1, Math.round(req.sliceSeconds))) : hard;
const start = await r.startDelegatedSync(engine, { sourceId, noPull: req.intent !== 'pull', ...(req.intent === 'full' ? { full: true } : {}), timeoutSeconds, origin: 'background' },
- `on-commit-${randomUUID()}`, { registration: { id: local.id, credential: local.credential, lane: 'cli' } });
+ `on-commit-${randomUUID()}`, { registration: { id: local.id, credential: local.credential, lane: 'cli' }, logLines: true });
if (start.ok && start.jobId) return { jobId: start.jobId };
if (start.error === 'busy' || start.error === 'shutting_down') return { busy: true };
return { refused: String(start.refusal?.message ?? start.error ?? 'refused') };
diff --git a/src/core/notifier/status.ts b/src/core/notifier/status.ts
index 46db6ec5a5..b25135416a 100644
--- a/src/core/notifier/status.ts
+++ b/src/core/notifier/status.ts
@@ -49,6 +49,12 @@ export interface NotifierBlock {
* sync), which is syncing it now; null when none holds it. Remote callers get no host, pid or job id.
*/
drain_holder: DrainHolder | null;
+ /**
+ * #7243: with no live notifier owner, the resident the coverage row last recorded as this source's notifier (its trace
+ * rows name it) and when its notifier lease lapsed, so the fix text names it instead of saying none ever watched.
+ * Null when the row records none. Remote callers get no pid or host id.
+ */
+ recorded_resident: { kind: string; pid: number | null; host_id: string | null; seen_at: string | null; lease_expired_at: string | null } | null;
/** Set when nothing will sync the source on its own, the lease holder made no progress, or the notifier stalled. */
fix: Action | null;
}
@@ -57,7 +63,7 @@ interface Row {
id: string; last_commit: string | null; state: NotifierState | null; reason: string | null; first_due_at: unknown; attempts: unknown;
next_retry_at: unknown; last_error_code: string | null; last_error: string | null; last_error_at: unknown; trace_path: string | null;
observed_head: string | null; observed_at: unknown; detection_mode: DetectionMode | null; owner_host_id: string | null; owner_kind: string | null;
- owner_pid: unknown; lease_live: unknown; due_markers: unknown;
+ owner_pid: unknown; owner_seen_at: unknown; lease_live: unknown; lease_expires_at: unknown; due_markers: unknown;
}
const iso = (v: unknown): string | null => v === null || v === undefined ? null : v instanceof Date ? v.toISOString() : new Date(String(v)).toISOString();
@@ -66,8 +72,9 @@ const truthy = (v: unknown) => v === true || v === 't' || v === 1;
async function readRows(engine: Exec, sourceIds: string[] | null): Promise<Row[]> {
return engine.executeRaw<Row>(
`SELECT s.id, s.last_commit, n.state, n.reason, n.first_due_at, n.attempts, n.next_retry_at, n.last_error_code, n.last_error, n.last_error_at,
- n.trace_path, n.observed_head, n.observed_at, n.detection_mode, n.owner_host_id, n.owner_kind, n.owner_pid,
+ n.trace_path, n.observed_head, n.observed_at, n.detection_mode, n.owner_host_id, n.owner_kind, n.owner_pid, n.owner_seen_at,
EXISTS (SELECT 1 FROM sync_notifier_leases l WHERE l.host_id = n.owner_host_id AND l.expires_at > now()) AS lease_live,
+ (SELECT l.expires_at FROM sync_notifier_leases l WHERE l.host_id = n.owner_host_id) AS lease_expires_at,
(SELECT count(*) FROM sync_wanted_markers m WHERE m.source_id = s.id
AND (m.intent <> 'freshness' OR m.wanted_head IS NULL OR m.wanted_head IS DISTINCT FROM s.last_commit)) AS due_markers
FROM sources s LEFT JOIN sync_notifier_sources n ON n.source_id = s.id
@@ -144,8 +151,14 @@ export async function readNotifierBlock(engine: BrainEngine, sourceId: string, o
const stalled = row.reason === 'notifier_stalled' || row.state === 'operator_blocked';
const resident = live ? { kind: row.owner_kind ?? 'unknown', pid: remote ? null : row.owner_pid === null ? null : Number(row.owner_pid), host_id: remote ? null : row.owner_host_id, live } : null;
const holder = live ? null : await readDrainHolder(engine, sourceId).catch(() => null);
+ // #7243: the resident the row last recorded (the one its trace rows name), whose notifier lease is no longer live.
+ const recorded = !live && row.owner_kind ? { kind: row.owner_kind, pid: remote || row.owner_pid == null ? null : Number(row.owner_pid), host_id: remote ? null : row.owner_host_id,
+ seen_at: iso(row.owner_seen_at), lease_expired_at: iso(row.lease_expires_at) } : null;
const fix = !live && !holder
- ? syncNowFix(sourceId, 'No resident (gbrain serve, gbrain jobs work or the autopilot daemon) watches this source; this syncs the checkout HEAD now. A resident started later catches up on its own.')
+ ? syncNowFix(sourceId, recorded
+ ? `The ${recorded.kind} resident recorded as this source's notifier${recorded.pid ? ` (PID ${recorded.pid})` : ''} holds no live notifier lease${recorded.lease_expired_at ? ` (it lapsed at ${recorded.lease_expired_at})` : ''}, `
+ + `so nothing watches this source now; this syncs the checkout HEAD now. If that resident is still running, it is not renewing its lease: restart it, and it catches up on its own.`
+ : 'No resident (gbrain serve, gbrain jobs work or the autopilot daemon) watches this source; this syncs the checkout HEAD now. A resident started later catches up on its own.')
: !live ? (holderStalled(holder) ? syncNowFix(sourceId, `No notifier watches this source, and the ${holder!.kind} process holding its drain lease has made no commit or cursor save for ${HOLDER_STALL_MS / 60_000} min or more; `
+ 'a foreground sync follows it and takes over when its lease lapses.') : null)
: stalled ? syncNowFix(sourceId, `The notifier made no progress after ${Number(row.attempts ?? 0)} attempts (${row.last_error_code ?? row.reason ?? 'blocked'}); a foreground sync shows the error`
@@ -156,14 +169,15 @@ export async function readNotifierBlock(engine: BrainEngine, sourceId: string, o
last_error: row.last_error_code || row.last_error ? { code: row.last_error_code, message: row.last_error, at: iso(row.last_error_at), ...(remote ? {} : { trace_path: row.trace_path }) } : null,
observed_head: row.observed_head, observed_at: iso(row.observed_at),
pending_markers: markers.map(m => ({ intent: m.intent, wanted_head: m.wanted_head, first_due_at: iso(m.first_due_at)!, requested_by: m.requested_by })),
- stalled, drain_holder: remote ? publicDrainHolder(holder) : holder, fix,
+ stalled, drain_holder: remote ? publicDrainHolder(holder) : holder, recorded_resident: recorded, fix,
};
}
/** One line for the human sync status and doctor. */
export function formatNotifierBlock(sourceId: string, b: NotifierBlock): string {
const who = b.resident ? `${b.resident.kind}${b.resident.pid ? ` (PID ${b.resident.pid})` : ''}, ${b.detection_mode ?? 'not observed yet'}`
- : b.drain_holder ? `none running; ${b.drain_holder.kind}${b.drain_holder.pid ? ` (PID ${b.drain_holder.pid})` : ''} holds the drain lease and is syncing it` : 'none running';
+ : b.drain_holder ? `none running; ${b.drain_holder.kind}${b.drain_holder.pid ? ` (PID ${b.drain_holder.pid})` : ''} holds the drain lease and is syncing it`
+ : b.recorded_resident ? `none running; ${b.recorded_resident.kind}${b.recorded_resident.pid ? ` (PID ${b.recorded_resident.pid})` : ''} was recorded but holds no live lease${b.recorded_resident.lease_expired_at ? ` (lapsed ${b.recorded_resident.lease_expired_at})` : ''}` : 'none running';
const state = b.state ? `${b.state}${b.reason ? ` (${b.reason})` : ''}${b.next_retry_at && b.state === 'retry' ? `, next retry ${b.next_retry_at}` : ''}${b.attempts ? `, ${b.attempts} attempt(s)` : ''}` : 'idle';
const markers = b.pending_markers.length ? `; wanted: ${b.pending_markers.map(m => `${m.intent}${m.wanted_head ? ` ${m.wanted_head.slice(0, 8)}` : ''}`).join(', ')}` : '';
const fix = b.fix ? `. Fix: ${b.fix.argv?.join(' ')}` : '';
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 29615a2a52..05bdc997b8 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -791,6 +791,15 @@ export function deadlinePassed(deadlineAtMs: number | undefined, now = Date.now(
return deadlineAtMs !== undefined && deadlineAtMs - now <= DEADLINE_MARGIN_MS;
}
+/** #7243: a live pass round's phase line (after its level read, before its import walk), so a long round never looks dead; null for other events. */
+export function passRoundLine(event: Parameters<NonNullable<SyncOpts['onProgress']>>[0]): string | null {
+ const r = event.round;
+ if (!r) return null;
+ if (event.phase === 'managed_sync.round_level') return `[sync] pass round ${r.round}: read ${r.paths} path(s) at ${r.target.slice(0, 8)} in ${formatDuration(Math.round((r.read_ms ?? 0) / 1000))}; settling them next.`;
+ if (event.phase === 'managed_sync.round_admit') return `[sync] pass round ${r.round}: importing ${r.imports ?? 0} file(s) and deleting ${r.deletes ?? 0} page(s)${r.in_flight ? ` (${r.in_flight} write(s) already in flight)` : ''}; progress lines follow as pages commit.`;
+ return null;
+}
+
/** 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');
@@ -815,7 +824,9 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno
pass: (signal, onProgress) => {
const capacityPreflight = !preflighted;
preflighted = true;
- return performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, capacityPreflight, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) });
+ // #7243: an announcing drain prints each pass round's phase lines as the pass reaches them.
+ const rounds: typeof onProgress = event => { const line = announce ? passRoundLine(event) : null; if (line) serr(line); onProgress(event); };
+ return performManagedSync(engine, { ...opts, signal, onProgress: rounds, drainStartedAt, capacityPreflight, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) });
} });
} finally {
if (laneRun) {
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 4fddd632df..2178dafd24 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -628,6 +628,14 @@ async function envelopeCrossed(engine: BrainEngine, value: ManagedSyncPassValue,
return true;
}
+/** #7243: a round's level read, then its `managed_sync.round_level` progress event, so a long round (the legacy sweep, the import walk) says where it stands first. */
+async function readLevelReporting(engine: BrainEngine, levelInput: Parameters<typeof readShadowLevel>[1], round: number, onProgress: SyncOpts['onProgress']): Promise<Awaited<ReturnType<typeof readShadowLevel>>> {
+ const started = Date.now();
+ const level = await readShadowLevel(engine, levelInput);
+ if (level) onProgress?.({ phase: 'managed_sync.round_level', round: { round, target: level.head, paths: level.paths.length, read_ms: Date.now() - started } });
+ return level;
+}
+
export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Promise<SyncResult> {
const { opts, context, authority, assertActive } = input;
const { sourceId, incarnation } = context;
@@ -792,7 +800,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const levelInput = { sourceId, context, workingTree: mode === 'working',
pass: { noSchemaPack: processingOptions.noSchemaPack, episodeFullId: episode?.full_id ?? null, retryConsumed: round > 1 ? retryConsumed : undefined, exclude: opts.exclude, includeHidden: opts.includeHidden, strategy: opts.strategy, bootstrap: markersOwed(),
slugMode: value.obligations.slug_mode, cache: levelCache, passId, recorded: applied.recorded } };
- const level = await readShadowLevel(engine, levelInput);
+ const level = await readLevelReporting(engine, levelInput, round, opts.onProgress);
await faultPoint('sync:level_read', { sourceId, round, level: level ? { statements: level.statements, confirm: level.confirm ?? null, reused: level.reused ?? 0, shadow: level, input: levelInput } : undefined });
assertActive();
if (!level) throw new Error(`Source ${sourceId} became a company-brain source during its sync pass.`);
@@ -869,6 +877,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
value.telemetry = { ...value.telemetry, outcome: 'synced', stop_reason: configured ? null : 'selection_scoped', remaining: 0 };
return synced(false);
}
+ opts.onProgress?.({ phase: 'managed_sync.round_admit', round: { round, target: head, paths: level.paths.length, imports: imports.length, deletes: deletes.length, in_flight: inFlight.length } });
const built = await batchEntries(engine, level, deletes, imports).catch(async (error: unknown) => {
if ((error as { code?: string } | null | undefined)?.code === 'page_identity_changed') await save('blocked', 'page_identity_changed');
throw error;
diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.ts
index 666a8be82e..ea9ad523a1 100644
--- a/src/core/persistence/sync-pass-status.ts
+++ b/src/core/persistence/sync-pass-status.ts
@@ -14,7 +14,11 @@ import { NOT_CONVERGED_REPORT_STREAK, passHealth, type PassRoundSummary, type Pa
export interface PassConvergence {
schema: 'convergence/1'; dry_run: false; source_id: string;
- pass_id: string; kind: string; outcome: string; stop_reason: string | null; target: string; converged_at: string | null;
+ /**
+ * `target` is the commit the newest pass pinned (its telemetry), not a converged state. #7243: `converged_target` is the
+ * commit the stored converged obligation records (the last stamp), null while no stamp backs one (a stuck source that never converged).
+ */
+ pass_id: string; kind: string; outcome: string; stop_reason: string | null; target: string; converged_target: string | null; converged_at: string | null;
round: number; candidates: number; settled: number; remaining: number; eta_seconds: null; eta_reason: 'pass_round_local';
counts: Record<string, number>;
decisions: { both: number; unknown: number; deleted: number };
@@ -41,7 +45,7 @@ export async function passConvergence(engine: Pick<BrainEngine, 'executeRaw'>, i
const summary = t.summary ?? { db_ahead: { pending: 0, db_only: 0, unproven: 0, by_prefix: {} }, full_skipped_db_ahead: 0, legacy_unverified: 0, legacy_pageless: 0 };
const episode = o.episode;
return { schema: 'convergence/1', dry_run: false, source_id: input.sourceId, pass_id: t.pass_id, kind: t.kind, outcome: t.outcome, stop_reason: t.stop_reason, target: t.target,
- converged_at: o.converged?.at ?? null, round: t.round, candidates: t.candidates, settled: t.settled, remaining: t.remaining, eta_seconds: null, eta_reason: 'pass_round_local',
+ converged_target: o.converged?.target ?? null, converged_at: o.converged?.at ?? null, round: t.round, candidates: t.candidates, settled: t.settled, remaining: t.remaining, eta_seconds: null, eta_reason: 'pass_round_local',
counts: t.counts, decisions, db_ahead: summary.db_ahead, full_skipped_db_ahead: summary.full_skipped_db_ahead, legacy_unverified: summary.legacy_unverified,
legacy_pageless: summary.legacy_pageless, keep_db_admitted: t.counts.keep_db_admitted ?? 0, keep_db_pending: t.counts.keep_db_pending ?? 0,
deletes_withheld: withheld ? { count: withheld.count, ratio: withheld.ratio, set_hash: withheld.set_hash, samples: withheld.samples } : null,
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 26dbb9d00f..07c68112f7 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -49,6 +49,8 @@ import { SYNC_ADMISSION_SETTING_PARAMS, syncAdmissionSettingSql, syncAdmissionSt
import type { DeletesWithheld } from './sync-markers.ts';
import { listIdentityDowngrades, withIdentityRemedies } from '../sync-identity-downgrades.ts';
import { GIT_PUSH_CODES, readGitPushHolds, type GitPushHold } from './git-push-holds.ts';
+import { holderStalled, readDrainHolder, type DrainHolder } from './sync-lease.ts';
+import { syncLockId } from '../db-lock.ts';
export interface SyncStatusHold extends SyncFaultVerdict {
code: string;
@@ -87,12 +89,43 @@ export interface SyncStatusError extends SyncFaultVerdict {
/**
* #7189: this source's sync committed a page write at `at`, after the failure was last recorded, so the failure no
* longer says where the sync stands. It stays listed, but sets neither `needs_human`, `state` nor `next`.
+ * #7243: also once a later attempt got past the phase the failure stopped in (`by`, `supersededBy`); `age_seconds` is
+ * how long ago the failure was last recorded.
*/
- superseded?: { at: string };
+ superseded?: { at: string; by?: SupersededBy; age_seconds?: number };
}
+/** #7243: what a later attempt reached after a failure: its pass pinned, read the level (or verified it idle), admitted a page, or committed one. */
+export type SupersededBy = 'pin' | 'level_read' | 'admission' | 'commit';
+const PHASE_RANK: Record<ManagedSyncFailure['phase'], number> = { resume: 0, discovery: 1, freeze: 2, admission: 2, receipt: 3, checkpoint: 3 };
+const EVIDENCE_RANK: Record<SupersededBy, number> = { pin: 0, level_read: 1, admission: 2, commit: 3 };
+
+/**
+ * #7243: the latest evidence, newer than the failure's last record, that a later attempt got past the phase the failure
+ * stopped in (a commit passes every phase; an admission passes discovery and admission; a level read passes discovery;
+ * a pin passes a stop before the level read). Null: nothing later got that far, so the failure still says where sync stands.
+ */
+export function supersedingAttempt(phase: ManagedSyncFailure['phase'], failureAt: string, evidence: Partial<Record<SupersededBy, string | null>>): { at: string; by: SupersededBy } | null {
+ const after = Date.parse(failureAt);
+ const passed = (Object.entries(evidence) as Array<[SupersededBy, string | null | undefined]>)
+ .filter((entry): entry is [SupersededBy, string] => !!entry[1] && Date.parse(entry[1]) > after && EVIDENCE_RANK[entry[0]] >= (PHASE_RANK[phase] ?? 3))
+ .sort((a, b) => EVIDENCE_RANK[b[0]] - EVIDENCE_RANK[a[0]]);
+ return passed[0] ? { at: new Date(passed[0][1]).toISOString(), by: passed[0][0] } : null;
+}
+
+/** #7243: the process holding the source's drain lease (`readDrainHolder`), with the Minions job id when it is a sync job and whether it stalled. */
+export type SyncStatusLive = DrainHolder & { job_id: number | null; stalled: boolean };
+
export interface SyncStatus {
source_id: string;
+ /** #7243: the commit the source's sync applied through (`sources.last_commit`, stamped when a sync converges), or null before the first. */
+ last_commit: string | null;
+ /**
+ * #7243: the job doing the work now: the holder of the source's drain lease (a serve pass, a sync job, a CLI sync, the
+ * cycle), its heartbeat and progress, `job_id` when it is a Minions sync job, and `stalled` once it has made no commit
+ * or save for the stall window. Null when nothing holds the lease.
+ */
+ live: SyncStatusLive | null;
run_id: string | null;
cursor: { index: number; total: number; pinned_target: string | null; last_advance_at: string | null; done: boolean } | null;
/** Managed sync page requests of the source committed in the last ten minutes (waived entries are not requests). */
@@ -269,16 +302,17 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
const detail = opts.detail !== false;
// #6712 PR 4b (design §9): the pass row and the withheld-delete record ride the source read (primary-key probes), so the plain status keeps its statement budget.
const admissionSql = syncAdmissionSettingSql(4);
- const [source] = await engine.executeRaw<{ incarnation: string; pass_value: PassRow['value'] | null; pass_updated_at: Date | string | null; withheld: DeletesWithheld | null;
+ const [source] = await engine.executeRaw<{ incarnation: string; last_commit: string | null; drain_lock: boolean; pass_value: PassRow['value'] | null; pass_updated_at: Date | string | null; withheld: DeletesWithheld | null;
admission_stored: string | null; admission_row_value: string | null; admission_set_at: string | null; writeback_failed: string | null }>(
- `SELECT s.incarnation::text AS incarnation, p.completed_keys->0 AS pass_value, p.updated_at AS pass_updated_at, w.completed_keys->0 AS withheld, ${admissionSql.columns},
+ `SELECT s.incarnation::text AS incarnation, s.last_commit, EXISTS (SELECT 1 FROM gbrain_cycle_locks l WHERE l.id=$${4 + SYNC_ADMISSION_SETTING_PARAMS.length}) AS drain_lock,
+ p.completed_keys->0 AS pass_value, p.updated_at AS pass_updated_at, w.completed_keys->0 AS withheld, ${admissionSql.columns},
(SELECT r.request_id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' AND e.state='failed'
AND e.request_id IN (SELECT id::uuid FROM jsonb_array_elements_text(CASE WHEN jsonb_typeof(p.completed_keys->0->'obligations'->'converged'->'writeback')='array'
THEN p.completed_keys->0->'obligations'->'converged'->'writeback' ELSE '[]'::jsonb END) AS w(id)) ORDER BY e.id LIMIT 1) AS writeback_failed FROM sources s
LEFT JOIN op_checkpoints p ON p.op=$2 AND p.fingerprint=s.id||':'||s.incarnation::text
LEFT JOIN op_checkpoints w ON w.op=$3 AND w.fingerprint=s.id||':'||s.incarnation::text
${admissionSql.joins}
- WHERE s.id=$1 AND s.archived IS NOT TRUE`, [sourceId, MANAGED_SYNC_PASS_OP, SYNC_DELETES_WITHHELD_OP, ...SYNC_ADMISSION_SETTING_PARAMS]);
+ WHERE s.id=$1 AND s.archived IS NOT TRUE`, [sourceId, MANAGED_SYNC_PASS_OP, SYNC_DELETES_WITHHELD_OP, ...SYNC_ADMISSION_SETTING_PARAMS, syncLockId(sourceId)]);
if (!source) throw Object.assign(new Error(`Source ${sourceId} does not exist.`), { code: 'not_found' });
const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');
const selected = await cursorHeader(engine, sourceId, source.incarnation, failures[0]?.cursor_key ?? null);
@@ -316,11 +350,18 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
: retired ? { code: 'cursor_incarnation_retired', category: 'sync_fault', public_category: 'superseded', message: `An unfinished sync cursor of ${sourceId} was recorded under an incarnation the source no longer has; no current sync selects it, and it says nothing about whether the current files are imported. `
+ `Retire it with ${repairPreview.argv!.join(' ')} (preview, then --apply with the printed hash).`, phase: 'resume', first_seen: retired.first_seen, attempts: 1, ...classifySyncFault({ code: 'cursor_incarnation_retired' }) } : null;
if (failure && lastError) {
- const [seen] = await engine.executeRaw<{ failure_at: Date | string | null; committed_at: Date | string | null }>(`SELECT
+ const [seen] = await engine.executeRaw<{ failure_at: Date | string | null; committed_at: Date | string | null; admitted_at: Date | string | null; now_at: Date | string }>(`SELECT now() AS now_at,
(SELECT f.updated_at FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=$2) AS failure_at,
(SELECT max(r.completed_at) FROM persistence_source_bindings b JOIN persistence_requests r ON r.worktree_id=b.worktree_id AND r.source_incarnation=b.source_incarnation
- WHERE b.source_id=$1 AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS committed_at`, [sourceId, failure.cursor_key]);
- if (seen?.failure_at && seen.committed_at && new Date(seen.committed_at) > new Date(seen.failure_at)) lastError.superseded = { at: new Date(seen.committed_at).toISOString() };
+ WHERE b.source_id=$1 AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS committed_at,
+ (SELECT max(r.created_at) FROM persistence_source_bindings b JOIN persistence_requests r ON r.worktree_id=b.worktree_id AND r.source_incarnation=b.source_incarnation
+ WHERE b.source_id=$1 AND r.state<>'committed' AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete')) AS admitted_at`, [sourceId, failure.cursor_key]);
+ // #7243: the newest pass (its row rides the source read) is evidence too: it pinned, and it read the level unless it stopped before.
+ const pass = source.pass_value?.telemetry;
+ const levelRead = pass && (pass.outcome === 'up_to_date' || Object.keys(pass.timings_ms ?? {}).length > 0) ? pass.started_at : null;
+ const iso = (value: Date | string | null | undefined) => value == null ? null : new Date(value).toISOString();
+ const later = seen?.failure_at ? supersedingAttempt(failure.phase, iso(seen.failure_at)!, { commit: iso(seen.committed_at), admission: iso(seen.admitted_at), level_read: levelRead ?? null, pin: pass?.started_at ?? null }) : null;
+ if (later) lastError.superseded = { ...later, age_seconds: Math.max(0, Math.round((Date.parse(iso(seen!.now_at)!) - Date.parse(iso(seen!.failure_at)!)) / 1000)) };
}
const liveError = lastError?.superseded ? null : lastError;
const unfinished = !!header && !header.done;
@@ -338,7 +379,10 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
const actionable = holds.filter(hold => !hold.needs_human && hold.safe_actions[0] !== 'none');
const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };
// #6706: a live sync job already drains this cursor; the agent watches it instead of starting a second drainer beside it.
- const liveJob = unfinished && !human ? await (await import('./sync-movement.ts')).liveSyncJob(engine, sourceId) : null;
+ // #7243: whoever holds the drain lease is the job doing the work, a serve-owned pass included (one primary-key probe rode the source read).
+ const holder = source.drain_lock ? await readDrainHolder(engine, sourceId).catch(() => null) : null;
+ const holderJob = holder?.kind === 'job' && holder.id && /^\d+$/.test(holder.id) ? Number(holder.id) : null;
+ const liveJob = unfinished && !human ? holderJob ?? await (await import('./sync-movement.ts')).liveSyncJob(engine, sourceId) : null;
const next: Action | null = liveJob !== null
? { argv: ['gbrain', 'jobs', 'get', String(liveJob), '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,
why: `Sync job #${liveJob} is draining this cursor (${header!.index}/${header!.total}); it resumes the frozen manifest on its own, so watch it rather than running a second sync beside it.` }
@@ -370,9 +414,9 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
const admission = await syncAdmissionStatus(engine, sourceId, source.incarnation,
{ stored: source.admission_stored, row_value: source.admission_row_value, set_at: source.admission_set_at });
const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume, source.writeback_failed) : null;
- return { source_id: sourceId, run_id: header?.runId ?? null,
+ return { source_id: sourceId, last_commit: source.last_commit, live: holder ? { ...holder, job_id: holderJob, stalled: holderStalled(holder) } : null, run_id: header?.runId ?? null,
cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,
- committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, identity_downgrades: await withIdentityRemedies(engine, await listIdentityDowngrades(engine, [sourceId])), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
+ committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob ?? holderJob, holds, identity_downgrades: await withIdentityRemedies(engine, await listIdentityDowngrades(engine, [sourceId])), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
needs_human_from: !human ? null : 'path' in human && 'held_since' in human ? { kind: 'hold', path: human.path, slug: human.slug, code: human.code } : { kind: 'last_error', code: human.code },
resume_argv: resume, ...blockers, cursors: detail ? await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures) : [],
terminal_failures: terminal, connector_last_error: connectorLastError, git_push_holds: gitPushHolds, next: next ?? recovery_next ?? passNext ?? (stateReason === 'request_pending' && oldest.status === 'ok' && oldest.request ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,
diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.ts
index 2132d1860f..a73f32ce02 100644
--- a/src/core/serve-sync-runner.ts
+++ b/src/core/serve-sync-runner.ts
@@ -194,12 +194,17 @@ export function isDelegatedSyncRunning(): boolean {
* payload; when present the start is asynchronous (one verification read).
*/
export function startDelegatedSync(engine: BrainEngine, rawOptions: unknown, clientToken: string, opts?: { boundSourceId?: string }): SyncStartResponse;
-export function startDelegatedSync(engine: BrainEngine, rawOptions: unknown, clientToken: string, opts: { boundSourceId?: string; registration?: unknown }): SyncStartResponse | Promise<SyncStartResponse>;
+/**
+ * `opts.logLines` (in-process callers only, never the wire): also write the job's human lines to the serve log, for a
+ * run nobody polls (the resident notifier's background passes, #7243), whose phase and progress lines would otherwise
+ * reach only the job's line buffer.
+ */
+export function startDelegatedSync(engine: BrainEngine, rawOptions: unknown, clientToken: string, opts: { boundSourceId?: string; registration?: unknown; logLines?: boolean }): SyncStartResponse | Promise<SyncStartResponse>;
export function startDelegatedSync(
engine: BrainEngine,
rawOptions: unknown,
clientToken: string,
- opts: { boundSourceId?: string; registration?: unknown } = {},
+ opts: { boundSourceId?: string; registration?: unknown; logLines?: boolean } = {},
): SyncStartResponse | Promise<SyncStartResponse> {
// #6696 (A5): the client's admission origin scopes every write of the job (validated below; a client that sends none is background).
const origin = (rawOptions as { origin?: unknown } | null)?.origin;
@@ -210,7 +215,7 @@ function startDelegatedSyncScoped(
engine: BrainEngine,
rawOptions: unknown,
clientToken: string,
- opts: { boundSourceId?: string; registration?: unknown },
+ opts: { boundSourceId?: string; registration?: unknown; logLines?: boolean },
): SyncStartResponse | Promise<SyncStartResponse> {
if (typeof clientToken !== 'string' || clientToken.length === 0 || clientToken.length > 128) {
return { ok: false, protocol: 2, error: 'invalid_options:clientToken' };
@@ -287,7 +292,7 @@ function startDelegatedSyncScoped(
};
if (opts.registration !== undefined) {
- return startVerifiedDelegatedSync(engine, job, options, opts.registration as SyncStartRegistration, { settle, fail });
+ return startVerifiedDelegatedSync(engine, job, options, opts.registration as SyncStartRegistration, { settle, fail }, opts.logLines === true);
}
job.settled = withLegacySyncDelegation(async () => {
@@ -367,6 +372,7 @@ async function startVerifiedDelegatedSync(
options: DelegatedSyncOptions,
registration: SyncStartRegistration,
hooks: { settle: () => void; fail: (e: unknown) => void },
+ logLines = false,
): Promise<SyncStartResponse> {
const refuse = (e: unknown): SyncStartResponse => {
hooks.fail(e);
@@ -382,6 +388,7 @@ async function startVerifiedDelegatedSync(
}
job.managed = true;
const push = (text: string): void => {
+ if (logLines) log(`job=${job.id} ${text}`);
job.lines.push({ seq: ++job.lineSeq, text });
if (job.lines.length > LINE_BUFFER_MAX) job.lines.splice(0, job.lines.length - LINE_BUFFER_MAX);
};
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 99355e3d65..5f8e6dd80d 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -430,11 +430,13 @@ test/sync-page-identity-hold-gbra130.test.ts
test/sync-page-write-failed-gbra130.test.ts
test/sync-pass-cost-grouping-gbra130.test.ts
test/sync-pass-dirty-after-freeze-gbra130.test.ts
+test/sync-pass-phase-lines-7243.serial.test.ts
test/sync-prescreen-both-delta-6712.test.ts
test/sync-prescreen-drift-6712.test.ts
test/sync-slug-root-mode-6694.test.ts
test/sync-staged-catchup.test.ts
test/sync-status-failure-detail-6513.test.ts
+test/sync-status-truthful-7243.test.ts
test/sync-unblock-repair-error-gbra130.test.ts
test/sync-uncommitted-origin-7130.test.ts
test/sync-unreadable-file-gbra130.test.ts
diff --git a/test/sync-pass-phase-lines-7243.serial.test.ts b/test/sync-pass-phase-lines-7243.serial.test.ts
new file mode 100644
index 0000000000..3b1245ed24
--- /dev/null
+++ b/test/sync-pass-phase-lines-7243.serial.test.ts
@@ -0,0 +1,92 @@
+/**
+ * #7243 item 6: a serve-owned managed pass printed no phase line before its import walk, so a long walk looked dead.
+ * The resident notifier's background run (notifier/resident.ts runnerStart, the path serve, serve-http, jobs work and the
+ * autopilot daemon take) ran with its human lines routed to the job's line buffer only, and the pass emitted nothing
+ * between its start and the first committed page. Now each round prints "[sync] pass round N: read ..." after its level
+ * read and "... importing N file(s) ..." before its import walk, and a run nobody polls also writes its lines to the
+ * serve log ("[serve-sync] job=<id> ..."). Red on master, on PGLite and on Postgres (test/postgres-unit-arms.txt).
+ * Serial: the delegated-sync runner is process-wide.
+ */
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { runnerStart } from '../src/core/notifier/resident.ts';
+import { __resetDelegatedSyncForTests, getDelegatedSyncStatus, isDelegatedSyncRunning } from '../src/core/serve-sync-runner.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-phase-7243-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const note = (name: string) => `---\ntitle: ${name}\n---\n${name} keeps the acme-example ledger.\n`;
+
+beforeAll(async () => {
+ __resetDelegatedSyncForTests();
+ 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);
+afterEach(() => { __resetDelegatedSyncForTests(); });
+afterAll(async () => {
+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+async function until(what: string, fn: () => Promise<boolean> | boolean, timeoutMs = 120_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (!(await fn())) {
+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
+ await Bun.sleep(50);
+ }
+}
+
+test('a resident-started managed pass prints its round phase lines before the import walk, in the job lines and the serve log', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const id = `ph-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);
+ mkdirSync(root); git(root, 'init', '-q');
+ writeFileSync(join(root, 'alice-example.md'), note('Alice'));
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'fixture');
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect((await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+ for (const name of ['bob-example', 'carol-example', 'dave-example']) writeFileSync(join(root, `${name}.md`), note(name));
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'three more');
+
+ const logged: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: string | Uint8Array, ...rest: unknown[]) => { logged.push(String(chunk)); return (write as (...a: unknown[]) => boolean)(chunk, ...rest); }) as typeof process.stderr.write;
+ let jobId: string;
+ try {
+ const started = await runnerStart(engine).startSync(id, { intent: 'freshness' } as never);
+ jobId = (started as { jobId?: string }).jobId!;
+ expect(typeof jobId).toBe('string');
+ await until('the resident run to end', () => !isDelegatedSyncRunning());
+ } finally { process.stderr.write = write; }
+ const status = getDelegatedSyncStatus(jobId!);
+ expect(status).toMatchObject({ ok: true, state: 'done' });
+ const lines = (status.lines ?? []).map(line => line.text);
+ const level = lines.findIndex(line => /^\[sync\] pass round 1: read \d+ path\(s\) at [0-9a-f]{8} in /.test(line));
+ const admit = lines.findIndex(line => line.startsWith('[sync] pass round 1: importing 3 file(s) and deleting 0 page(s)'));
+ expect(level).toBeGreaterThanOrEqual(0);
+ expect(admit).toBeGreaterThan(level);
+ // Both phase lines come before the first line of the import walk itself.
+ const walk = lines.findIndex(line => line.startsWith('[sync] managed catch-up:') || /^\[sync\] \d+\/\d+ processed/.test(line));
+ if (walk >= 0) expect(walk).toBeGreaterThan(admit);
+ // Nobody polls a resident's run: its lines also reach the serve log.
+ const serveLog = logged.join('');
+ expect(serveLog).toContain(`[serve-sync] job=${jobId!} [sync] pass round 1: read `);
+ expect(serveLog).toContain(`[serve-sync] job=${jobId!} [sync] pass round 1: importing 3 file(s)`);
+ }
+}), 300_000);
diff --git a/test/sync-status-truthful-7243.test.ts b/test/sync-status-truthful-7243.test.ts
new file mode 100644
index 0000000000..330f248749
--- /dev/null
+++ b/test/sync-status-truthful-7243.test.ts
@@ -0,0 +1,238 @@
+/**
+ * #7243 (GBRA-133 PR 3a lane S): `gbrain sync status` told an agent less than the truth on a large managed source. Each
+ * case is red on master, on PGLite and on Postgres (test/postgres-unit-arms.txt):
+ * - plain --json printed every hold inline (thousands of rows); it now prints counts by code and state over every
+ * hold and the first PLAIN_STATUS_HOLDS rows, and --detail pages through the rest with a cursor;
+ * - status had no last_commit and no live block naming the drain-lease holder (a serve pass read live_job_id: null);
+ * - a last_error from a phase a later pass got past still read live with safe_actions: retry; it reads superseded
+ * with what passed it and its age;
+ * - the notifier said "No resident ... watches this source" while its row (and trace) named the resident; it names it;
+ * - convergence.target (the newest pass's pin) was the only target status printed, with no converged obligation
+ * behind it; converged_target reads the stored obligation and is null without one.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readSyncStatus, supersedingAttempt } from '../src/core/persistence/sync-status.ts';
+import { recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';
+import { writeGitHold, type GitHoldCode } from '../src/core/persistence/sync-holds.ts';
+import { withDrainLease } from '../src/core/persistence/sync-lease.ts';
+import { claimLease, writeCoverage } from '../src/core/notifier/store.ts';
+import { formatNotifierBlock, readNotifierBlock } from '../src/core/notifier/status.ts';
+import { PLAIN_STATUS_HOLDS, runSyncStatus } from '../src/commands/sync/operator.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-status-7243-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+/** A managed source with one synced commit; returns its id, root, incarnation and HEAD. */
+async function syncedSource(engine: BrainEngine) {
+ const id = `st-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);
+ mkdirSync(root); git(root, 'init', '-q');
+ writeFileSync(join(root, 'alice-example.md'), '---\ntitle: Alice Example\n---\nAlice keeps the acme-example ledger.\n');
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'fixture');
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect((await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ return { id, root, incarnation, head: git(root, 'rev-parse', 'HEAD') };
+}
+
+const CODES: GitHoldCode[] = ['concurrent_write', 'preparation_stalled', 'managed_image_sync_unsupported'];
+async function seedHolds(engine: BrainEngine, s: { id: string; incarnation: string }, count: number) {
+ const now = new Date().toISOString();
+ for (let i = 0; i < count; i++) {
+ const path = `held/note-${String(i).padStart(4, '0')}.md`;
+ await writeGitHold(engine, { source_id: s.id, incarnation: s.incarnation, path, source_path: path, slug: path.replace(/\.md$/, ''), page_id: null,
+ code: CODES[i % CODES.length]!, message: `${path} is held (fixture).`, upstream_version: null, observed_at: now, run_id: null, mode: 'managed', meta: { recovery_version: 1 } });
+ }
+}
+
+async function printed(run: () => Promise<void>): Promise<string> {
+ const out: string[] = [];
+ const log = console.log;
+ console.log = (...parts: unknown[]) => { out.push(parts.join(' ')); };
+ try { await run(); } finally { console.log = log; }
+ return out.join('\n');
+}
+type StatusJson = { holds: Array<{ path: string; code: string; needs_human: boolean }>; holds_summary?: { total: number; by_code: { counts: Record<string, number>; other: number }; by_state: { counts: Record<string, number>; other: number } };
+ holds_page?: { returned: number; limit: number | null; complete: boolean; next_cursor: string | null; next_command: string[] | null }; last_commit?: string | null; live?: unknown };
+const statusJson = async (engine: BrainEngine, args: string[]) => JSON.parse(await printed(() => runSyncStatus(engine, args))) as StatusJson;
+
+test('plain status --json bounds the holds: counts over every hold plus the first rows; --detail pages through all of them', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const big = await syncedSource(engine), bigger = await syncedSource(engine), small = await syncedSource(engine);
+ await seedHolds(engine, big, 150); await seedHolds(engine, bigger, 450); await seedHolds(engine, small, 3);
+
+ const plain = await statusJson(engine, ['--source', big.id, '--json']);
+ expect(plain.holds).toHaveLength(PLAIN_STATUS_HOLDS);
+ expect(plain.holds_summary!.total).toBe(150);
+ expect(plain.holds_summary!.by_code.counts).toEqual({ concurrent_write: 50, preparation_stalled: 50, managed_image_sync_unsupported: 50 });
+ expect(Object.values(plain.holds_summary!.by_state.counts).reduce((a, b) => a + b, 0)).toBe(150);
+ expect(plain.holds_page).toMatchObject({ returned: PLAIN_STATUS_HOLDS, complete: false, next_cursor: expect.any(String) });
+ expect(plain.holds_page!.next_command).toEqual(['gbrain', 'sync', 'status', '--source', big.id, '--json', '--cursor', plain.holds_page!.next_cursor!]);
+ // Needs-human holds come first, so the bounded page never hides the ones a person must decide.
+ if (plain.holds_summary!.by_state.counts.needs_human) expect(plain.holds[0]!.needs_human).toBe(true);
+ // The rows come last, after the summary and the page fields.
+ expect(Object.keys(plain).slice(-3)).toEqual(['holds_summary', 'holds_page', 'holds']);
+
+ // Bounded however many holds exist: three times the holds, the same rows and about the same size.
+ const plainText = await printed(() => runSyncStatus(engine, ['--source', big.id, '--json']));
+ const biggerText = await printed(() => runSyncStatus(engine, ['--source', bigger.id, '--json']));
+ expect((JSON.parse(biggerText) as StatusJson).holds).toHaveLength(PLAIN_STATUS_HOLDS);
+ expect(Math.abs(biggerText.length - plainText.length)).toBeLessThan(2_000);
+
+ // --detail pages through every hold exactly once.
+ const seen: string[] = [];
+ let args: string[] | null = ['--source', big.id, '--detail', '--limit', '40', '--json'];
+ for (let pages = 0; args && pages < 10; pages++) {
+ const page: StatusJson = await statusJson(engine, args);
+ expect(page.holds.length).toBeLessThanOrEqual(40);
+ seen.push(...page.holds.map(hold => hold.path));
+ args = page.holds_page!.next_command?.slice(3) ?? null;
+ if (!args) expect(page.holds_page).toMatchObject({ complete: true, next_cursor: null });
+ }
+ expect(seen).toHaveLength(150);
+ expect(new Set(seen).size).toBe(150);
+
+ // --all lists every hold in the earlier shape (no page fields); --hold-state lists one state.
+ const all = await statusJson(engine, ['--source', big.id, '--detail', '--all', '--json']);
+ expect(all.holds).toHaveLength(150);
+ expect(all.holds_page).toBeUndefined();
+ const held = await statusJson(engine, ['--source', big.id, '--detail', '--hold-state', 'held', '--all', '--json']);
+ expect(held.holds.length).toBe(plain.holds_summary!.by_state.counts.held ?? 0);
+
+ // A source whose holds fit on one page keeps the earlier shape.
+ const few = await statusJson(engine, ['--source', small.id, '--json']);
+ expect(few.holds).toHaveLength(3);
+ expect(few.holds_page).toBeUndefined();
+ expect(few.holds_summary!.total).toBe(3);
+
+ const text = await printed(() => runSyncStatus(engine, ['--source', big.id]));
+ expect(text).toContain(`${150 - PLAIN_STATUS_HOLDS} more not listed here`);
+ expect(text.split('\n').filter(line => line.startsWith(' held/')).length).toBe(PLAIN_STATUS_HOLDS);
+ }
+}), 600_000);
+
+test('status names last_commit and a live block for the drain-lease holder, a serve pass included', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const s = await syncedSource(engine);
+ const idle = await readSyncStatus(engine, s.id, { detail: false });
+ expect(idle.last_commit).toBe(s.head);
+ expect(idle.live).toBeNull();
+ const seen: Array<Awaited<ReturnType<typeof readSyncStatus>>> = [];
+ await withDrainLease(engine, s.id, { holder: { kind: 'serve', id: 'serve-job-example' } }, async () => { seen.push(await readSyncStatus(engine, s.id, { detail: false })); return { status: 'synced' } as never; });
+ await withDrainLease(engine, s.id, { holder: { kind: 'job', id: '4242' } }, async () => { seen.push(await readSyncStatus(engine, s.id, { detail: false })); return { status: 'synced' } as never; });
+ const [serve, job] = seen;
+ expect(serve!.live).toMatchObject({ kind: 'serve', id: 'serve-job-example', pid: process.pid, job_id: null, stalled: false });
+ expect(serve!.last_commit).toBe(s.head);
+ expect(job!.live).toMatchObject({ kind: 'job', id: '4242', job_id: 4242 });
+ expect(job!.live_job_id).toBe(4242);
+ const json = await statusJson(engine, ['--source', s.id, '--json']);
+ expect(json.last_commit).toBe(s.head);
+ expect(json).toHaveProperty('live', null);
+ expect(await printed(() => runSyncStatus(engine, ['--source', s.id]))).toContain(`last synced commit: ${s.head.slice(0, 8)}`);
+ }
+}), 300_000);
+
+test('a last error a later pass got past reads superseded with what passed it and its age; one it did not get past stays live', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const s = await syncedSource(engine);
+ // The first sync's commits and its pass happened before the failure below.
+ await engine.executeRaw("UPDATE persistence_requests SET completed_at = now() - interval '3 hours', created_at = now() - interval '3 hours' WHERE source_id=$1", [s.id]);
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,telemetry,started_at}', to_jsonb(to_char((now() - interval '3 hours') AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')))
+ WHERE op='managed-sync-pass' AND fingerprint=$1`, [`${s.id}:${s.incarnation}`]);
+ const key = `${s.id}:cursor-example`;
+ await recordManagedSyncFailure(engine, { source_id: s.id, source_incarnation: s.incarnation, path: 'alice-example.md', code: 'storage_error',
+ message: 'cannot execute the statement in a read-only transaction', request_id: null, run_id: 'run-example', target: s.head, cursor_key: key, phase: 'receipt', state: 'failed', observation_id: 'run-example:0' });
+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at = now() - interval '2 hours' WHERE op='managed-sync-failure' AND fingerprint=$1", [key]);
+ const before = await readSyncStatus(engine, s.id, { detail: false });
+ expect(before.last_error).toMatchObject({ code: 'storage_error', safe_actions: ['retry'] });
+ expect(before.last_error!.superseded).toBeUndefined();
+
+ // A later pass that commits nothing: an idle tick reads the source and stamps up_to_date.
+ expect((await performManagedSync(engine, { sourceId: s.id, noPull: true, noEmbed: true, noExtract: true })).status).toBe('up_to_date');
+ const receipt = await readSyncStatus(engine, s.id, { detail: false });
+ expect(receipt.last_error!.code).toBe('storage_error');
+ expect(receipt.last_error!.superseded).toBeUndefined();
+
+ // The same failure, recorded before its run read the level: the later pass got past that phase.
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,phase}', '"resume"') WHERE op='managed-sync-failure' AND fingerprint=$1`, [key]);
+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at = now() - interval '2 hours' WHERE op='managed-sync-failure' AND fingerprint=$1", [key]);
+ const after = await readSyncStatus(engine, s.id, { detail: false });
+ expect(after.last_error).toMatchObject({ code: 'storage_error', superseded: { at: expect.any(String), by: 'level_read' } });
+ expect(after.last_error!.superseded!.age_seconds).toBeGreaterThanOrEqual(7_190);
+ expect(after.last_error!.superseded!.age_seconds).toBeLessThan(7_200 + 600);
+ expect(after.reason).not.toBe('last_error');
+ expect(await printed(() => runSyncStatus(engine, ['--source', s.id]))).toContain('superseded: a later pass read the source at');
+ }
+}), 300_000);
+
+test('supersedingAttempt: only evidence newer than the failure and past its phase supersedes it', () => {
+ const at = '2026-01-01T10:00:00.000Z', later = '2026-01-01T11:00:00.000Z', earlier = '2026-01-01T09:00:00.000Z';
+ expect(supersedingAttempt('admission', at, { pin: later, level_read: later })).toBeNull();
+ expect(supersedingAttempt('admission', at, { admission: later })).toEqual({ at: later, by: 'admission' });
+ expect(supersedingAttempt('admission', at, { admission: earlier, commit: earlier })).toBeNull();
+ expect(supersedingAttempt('receipt', at, { admission: later })).toBeNull();
+ expect(supersedingAttempt('checkpoint', at, { commit: later })).toEqual({ at: later, by: 'commit' });
+ expect(supersedingAttempt('discovery', at, { pin: later })).toBeNull();
+ expect(supersedingAttempt('discovery', at, { pin: later, level_read: later })).toEqual({ at: later, by: 'level_read' });
+ expect(supersedingAttempt('resume', at, { pin: later })).toEqual({ at: later, by: 'pin' });
+});
+
+test('the notifier names the resident its row recorded when that resident holds no live lease, never "No resident"', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const s = await syncedSource(engine);
+ expect(await claimLease(engine, { hostId: 'host-example', ownerId: 'owner-example', kind: 'serve-http', pid: 4242, leaseMs: 60_000 })).toMatchObject({ owner: true });
+ await engine.executeRaw("UPDATE sync_notifier_leases SET expires_at = now() - interval '5 minutes' WHERE host_id='host-example'");
+ await writeCoverage(engine, s.id, { head: s.head, mode: 'poll', ownerHostId: 'host-example', ownerKind: 'serve-http', ownerPid: 4242 });
+ const block = (await readNotifierBlock(engine, s.id))!;
+ expect(block.resident).toBeNull();
+ expect(block.drain_holder).toBeNull();
+ expect(block.recorded_resident).toMatchObject({ kind: 'serve-http', pid: 4242, host_id: 'host-example', lease_expired_at: expect.any(String) });
+ expect(block.fix!.why).toContain("serve-http resident recorded as this source's notifier (PID 4242) holds no live notifier lease");
+ expect(block.fix!.why).not.toContain('No resident');
+ expect(formatNotifierBlock(s.id, block)).toContain('serve-http (PID 4242) was recorded but holds no live lease');
+ const remote = (await readNotifierBlock(engine, s.id, { remote: true }))!;
+ expect(remote.recorded_resident).toMatchObject({ kind: 'serve-http', pid: null, host_id: null });
+ await engine.executeRaw("DELETE FROM sync_notifier_leases WHERE host_id='host-example'");
+ }
+}), 300_000);
+
+test("status reports the converged target only from the stored obligation, beside the newest pass's pin", async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const s = await syncedSource(engine);
+ const stamped = await readSyncStatus(engine, s.id, { detail: false });
+ expect(stamped.convergence).toMatchObject({ target: s.head, converged_target: s.head });
+ // A stuck source's pass row: the newest pass pinned HEAD, and no stamp ever stored a converged obligation.
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,obligations}', (completed_keys->0->'obligations') - 'converged')
+ WHERE op='managed-sync-pass' AND fingerprint=$1`, [`${s.id}:${s.incarnation}`]);
+ const stuck = await readSyncStatus(engine, s.id, { detail: false });
+ expect(stuck.convergence).toMatchObject({ target: s.head, converged_target: null, converged_at: null });
+ expect(await printed(() => runSyncStatus(engine, ['--source', s.id]))).toContain(`pinned ${s.head.slice(0, 8)}; no converged stamp stored`);
+ }
+}), 300_000);