Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync): movement reader (data_moving/movement_state) on sources status, writer status and doctor; gbrain sources writer movement; next_action/last_sql/pool on running claims (#6317 lane 2, B4/I2/C1)
garrytanad1f41ae6562
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex b1a368dfa5..ce91207aed 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -728,6 +728,18 @@ More: [docs/guides/ambient-recall.md#replay-after-a-degraded-wake](../../docs/gu|---|---|---|---|---|---|---|| Commit or stash canonical skill edits before optimization. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### drain_stalled++<a id="drain_stalled"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A managed sync drain stopped `blocked` because its head write made no progress (no committed receipt and no step advance) for the whole stall window. | A renewed lease is not progress: the detector keys on the head claim's phase and step. With a live owner on this host the drain prints `stalled <N>s on <step>` from the allowance (budget plus 30 s) and keeps going; it stops only when `persistence.preparation_ceiling_ms` passes without the root being released, or when that owner's heartbeat row reads wedged (`cause: owner_wedged_here`, with the owner's kind, pid and nonce and `retry_after_ms` to the ceiling, after which the owner frees the root and the next pass holds the entry). A lapsed claim (`owner_missing`) stops at once unless this host owns the checkout and a live full consumer can reclaim it, which gets one more window. `drain.stall.cause` names which. | Inspect the writer with gbrain sources writer status --source <id> --json (read-only: the owner process, its step and what it waits on, and the next action). Before the ceiling (`next.safe_to_loop` true) rerun next.command after retry_after_ms; past it, or with a wedged owner, restart the named owner process on the brain host and rerun the same sync. Run: gbrain sources writer status --source '{source_id}' --json | host_admin | `gbrain doctor --only managed_sync_not_moving --json` | 1 | no |++Reasons: `owner_wedged_here`, `owner_missing`, `preparation_overdue`, `publication_overdue`, `no_progress`.++More: [docs/guides/write-refusals.md#drain-stalled](../../docs/guides/write-refusals.md#drain-stalled)+### dream_breaker_tripped<a id="dream_breaker_tripped"></a>@@ -1582,6 +1594,18 @@ More: [docs/guides/cron-schedule.md#dream-beside-autopilot](../../docs/guides/crMore: [docs/guides/write-refusals.md#managed_pull_skipped](../../docs/guides/write-refusals.md#managed_pull_skipped)+### managed_sync_not_moving++<a id="managed_sync_not_moving"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A managed source has unfinished sync work and a live consumer on its owner host, but no committed `managed_sync_*` receipt and no head step advance for longer than `persistence.preparation_ceiling_ms`. | Process liveness is not data movement: `/health` ok, a live pid and `sync_running: true` all held while one deployment moved nothing for weeks. `sources status --json` carries `data_moving`, `not_moving_since` and `movement_state` per source (`parked` when no drain or full consumer is live, informational), doctor warns with this code and counts it against the score, `serve` prints one notice when a source flips, and `gbrain sources writer movement` judges a window after a restart and exits 1 with this code (`reason: movement_check`) when pending work does not move. | Run gbrain sources writer status --source <id> --json (read-only): its next_action names the owner process, the step it is parked on and whether to wait or restart it. After the fix, gbrain sources writer movement proves the data moves again. Run: gbrain sources writer status --source '{source_id}' --json | host_admin | `gbrain doctor --only managed_sync_not_moving --json` | 1 | no |++Reasons: `movement_check`.++More: [docs/guides/troubleshooting.md#managed-sync-not-moving](../../docs/guides/troubleshooting.md#managed-sync-not-moving)+### manual_only_skipped<a id="manual_only_skipped"></a>diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex c68483eb58..e8b1731909 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -10,7 +10,7 @@ src/commands/embed.ts 2227 ratchet +2 agent operator wave D2: --json failure envsrc/commands/extract-conversation-facts.ts 2213 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start)src/commands/extract.ts 2580 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting pagesrc/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes-src/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts)+src/commands/serve-http.ts 931 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)src/core/ai/gateway.ts 4427 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts)src/commands/sync.ts 514 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict)src/core/cycle.ts 3283 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts)@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)src/commands/bootstrap.ts 2134 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)src/core/minions/worker.ts 1774 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler)-src/commands/sources.ts 2046 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts)+src/commands/sources.ts 2053 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help rowsrc/core/link-extraction.ts 2211 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshdiff --git a/src/commands/doctor/checks/managed-sync-movement.ts b/src/commands/doctor/checks/managed-sync-movement.tsnew file mode 100644index 0000000000..a258ac5496--- /dev/null+++ b/src/commands/doctor/checks/managed-sync-movement.ts@@ -0,0 +1,47 @@+/**+ * managed_sync_not_moving (#6317, B4): the health surface stops calling a+ * parked sync healthy. Reads `readSourceMovement` (the reader `sources+ * status`, `writer status` and `writer movement` share) and warns, with the+ * writer-status command as a structured fix, when an unfinished managed+ * cursor has had neither a committed page nor a head step advance for longer+ * than `persistence.preparation_ceiling_ms` while a drain or consumer is live.+ * A cursor left between runs with nothing live is `parked`: listed, never+ * warned. Reads the database only.+ */+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { readSourceMovement } from '../../../core/persistence/sync-movement.ts';+import { agentFix, checkError } from '../check-fix.ts';++const DOCS = 'docs/guides/troubleshooting.md#managed-sync-not-moving';++async function runManagedSyncMovementCheck(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const movement = await readSourceMovement(connectedEngine(ctx));+ const pending = movement.filter(m => m.movement_state !== 'nothing_pending');+ const stuck = pending.filter(m => m.movement_state === 'not_moving');+ const parked = pending.filter(m => m.movement_state === 'parked');+ const details = { count: stuck.length, parked: parked.length, sources: pending.map(m => ({ source_id: m.source_id, movement_state: m.movement_state, data_moving: m.data_moving,+ not_moving_since: m.not_moving_since, last_commit_at: m.last_commit_at, last_progress_at: m.last_progress_at, cursor: m.cursor, head: m.head, live: m.live, admitted: m.admitted,+ ceiling_ms: m.ceiling_ms, writer_status_command: m.writer_status_command })), docs: DOCS };+ if (stuck.length) {+ const first = stuck[0]!;+ checks.push({ name: 'managed_sync_not_moving', status: 'warn', readiness_state: 'degraded', details,+ message: `${stuck.map(m => `${m.source_id} (since ${m.not_moving_since}${m.head?.step ? `, head at step ${m.head.step}` : ''}${m.head?.owner ? `, ${m.head.owner.kind} pid ${m.head.owner.pid}` : ''})`).join('; ')}: `+ + `managed sync data has not moved for longer than the ${Math.round(first.ceiling_ms / 1000)}s ceiling while a sync or consumer is live. The health signals are green; the data is not.`,+ fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--source', first.source_id, '--json'],+ 'Read-only: names the request at the head, its step, what it waits on, the owner process and the next action on the running claim.', 'managed_sync_not_moving', { docs: DOCS }) });+ } else if (pending.length) {+ checks.push({ name: 'managed_sync_not_moving', status: 'ok', severity: 'info', details,+ message: `Managed sync data is moving${parked.length ? `; ${parked.map(m => `${m.source_id} is parked at ${m.cursor!.index}/${m.cursor!.total} (no sync or consumer live; resume: ${m.cursor!.resume_command})`).join('; ')}` : ''}.` });+ } else {+ checks.push({ name: 'managed_sync_not_moving', status: 'ok', message: 'No managed sync is pending.', details });+ }+ } catch (error) {+ checks.push(checkError('managed_sync_not_moving', 'read managed sync movement', error, { details: { health: 'unknown', docs: DOCS } }));+ }+ return checks;+}++export const managedSyncMovementEntry: DoctorEntry = { name: 'managed_sync_not_moving', emits: ['managed_sync_not_moving'], run: runManagedSyncMovementCheck };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 8219954d4e..3ef1908b13 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -100,6 +100,7 @@ import { agentContractEntry } from './checks/agent-contract.ts';import { chatFallbackChainEntry } from './checks/chat-fallback.ts';import { behaviorChangesEntry } from './checks/behavior-changes.ts';import { fenceIntegrityEntry } from './checks/fence-integrity.ts';+import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';import type { Check } from '../doctor.ts';import { infoCheck } from './check-fix.ts';@@ -176,6 +177,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [revisionBackfillEntry,coreMemoryEntry,fenceIntegrityEntry,+ managedSyncMovementEntry,searchModeEntry,];diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.tsindex 28afdc0fdf..8d799988c2 100644--- a/src/commands/persistence-admin.ts+++ b/src/commands/persistence-admin.ts@@ -16,6 +16,7 @@ import { bigintToStringReplacer } from '../core/utils.ts';export const WRITER_HELP = `Usage:gbrain sources writer status [<source>] [--probe] [--json]+ gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]gbrain sources writer retry-effects <source> --request-id <uuid> [--dry-run] [--json]gbrain sources writer claim <source> --path <directory> [administration options] [--dry-run] [--json]gbrain sources writer activate --confirm-quiesced [--cleanup-dead-local-locks] [--shared-skills] [administration options] [--dry-run] [--json]@@ -25,7 +26,10 @@ export const WRITER_HELP = `Usage:gbrain sources writer lock [--json]gbrain sources writer unlock [--json]-Inspect status first. Routine diagnosis, doctor --fix, startup, and maintenance+Inspect status first. movement proves that managed sync data moves over a window+(committed pages and the head's step, never a lease or a lock): run it after+restarting serve and the workers; see movement --help for its states and exits.+Routine diagnosis, doctor --fix, startup, and maintenancemust not change ownership or activate managed persistence. Read the operatorprocedure in docs/architecture/topologies.md before deliberate administration.Non-dry-run changes require --admin-intent <writer_claim|writer_activate|writer_deactivate|writer_transfer_prepare|writer_transfer_accept>@@ -165,7 +169,7 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {if (phase !== 'prepare' && phase !== 'accept') throw invalid(group, 'Transfer requires prepare or accept.','Run gbrain sources writer transfer prepare on the current owner host first, then gbrain sources writer transfer accept on the successor with the epoch and manifest prepare printed.');operation = phase === 'prepare' ? 'writer_transfer_prepare' : 'writer_transfer_accept';- } else throw invalid(group, 'Writer administration requires status, retry-effects, claim, activate, deactivate, transfer, lock, or unlock.',+ } else throw invalid(group, 'Writer administration requires status, movement, retry-effects, claim, activate, deactivate, transfer, lock, or unlock.',`Name the action after gbrain sources writer${verb ? ` instead of ${verb}` : ''}; start with gbrain sources writer status --json, which changes nothing.`);const source = positional.shift();if (source !== undefined) {@@ -187,6 +191,11 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {}export async function runPersistenceAdminCli(group: Group, args: string[], connected?: BrainEngine): Promise<void> {+ // #6317 (I2): the movement check waits a window on this process's own engine; it never crosses the owner IPC.+ if (group === 'writer' && args[0] === 'movement') {+ const { runWriterMovementCli } = await import('./sources-writer-movement.ts');+ return runWriterMovementCli(args.slice(1), connected);+ }if (!args.length || args.some(arg => arg === '--help' || arg === '-h')) {console.log(group === 'writer' ? WRITER_HELP : LOCAL_WRITER_HELP);return;diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex a63b4d41a6..5e0db3cdc5 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -909,13 +909,18 @@ ${bootstrapFromEnv// Automatic facts drain (Lane D): the resident HTTP serve owns a PGLite brain the way stdio serve does.const { startFactsDrainScheduler } = await import('../core/facts/drain-scheduler.ts');const factsDrain = startFactsDrainScheduler(engine, { owner: 'serve_http', log: (line) => console.error(line) });+ // #6317 (B4): one notice when a managed source's sync data stops moving (reader in persistence/sync-movement.ts).+ const { startMovementWatch } = await import('../core/persistence/sync-movement.ts');+ const movementWatch = startMovementWatch(engine, { log: (line) => console.error(line) });const deregisterEngineCleanup = registerCleanup('pglite-engine-disconnect', async () => {+ movementWatch.stop();await factsDrain.stop();await engine.disconnect();});try {await waitForHttpServerLifecycle(httpServer);} finally {+ movementWatch.stop();await factsDrain.stop();// Close the IPC listener + reap the socket file on orderly shutdown// (abnormal termination goes through the registered cleanup above).diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 4b4b49867f..9ae1e7ef97 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -9,6 +9,7 @@ import { parseTokenTtl } from './auth.ts';import { RESIDENT_POOL_FLOOR } from '../core/pg-access-classify.ts';import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';import { startFactsDrainScheduler, type FactsDrainScheduler, type FactsDrainSchedulerOpts } from '../core/facts/drain-scheduler.ts';+import { startMovementWatch, type MovementWatch } from '../core/persistence/sync-movement.ts';import { onForwardProgress } from '../core/forward-progress.ts';import { graduationHandoffRequested, writeServeGraduationEnvelope } from '../core/persistence/graduation-serve-guard.ts';import {@@ -591,9 +592,11 @@ function installStdioLifecycle(let idleSweepTimer: unknown = null;let activateIdleActivityTracking = (): void => {};let factsDrain: FactsDrainScheduler | null = null;+ let movementWatch: MovementWatch | null = null;const beginShutdown = (reason: string): void => {if (shuttingDown) return;shuttingDown = true;+ movementWatch?.stop();// Stop the parent-watchdog interval as soon as a shutdown begins so// it cannot fire a redundant 'parent-died' shutdown while the first@@ -853,6 +856,8 @@ function installStdioLifecycle(// Automatic facts drain (Lane D): see installFactsDrain.factsDrain = installFactsDrain(engine, opts, deps, () => shuttingDown);+ // #6317 (B4): one notice when a managed source's sync data stops moving (reader in persistence/sync-movement.ts).+ movementWatch = startMovementWatch(engine, { log: deps.log, setInterval: deps.setInterval as typeof setInterval, clearInterval: deps.clearInterval as typeof clearInterval });// Optional idle-timeout safety net. Default OFF; opt-in via// `--stdio-idle-timeout <seconds>`. The flag is for the rare case wherediff --git a/src/commands/sources-writer-movement.ts b/src/commands/sources-writer-movement.tsnew file mode 100644index 0000000000..b9858084bc--- /dev/null+++ b/src/commands/sources-writer-movement.ts@@ -0,0 +1,227 @@+/**+ * `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`+ * (#6317, I2): a deploy ends with data movement, not process liveness.+ *+ * It snapshots every active managed source (`readSourceMovement`: committed+ * managed receipt watermark, head step, cursor, holds, who is live), waits+ * the window (default `max(300 s, persistence.sync_preparation_ms + 60 s)`,+ * never below one sync preparation budget, so a healthy multi-wave group under+ * a raised budget reads `within_allowance`, never `not_moving`; the output+ * prints the budget it judged against), snapshots again and judges each+ * source: `moved` (a new committed publication), `within_allowance` (no commit+ * yet, but the head's step or the cursor advanced), `held` (advanced only by+ * holds: #6298's containment, routed by hold kind), `parked` (pending work and+ * nothing live to move it), `not_moving`, `nothing_pending`. The window ends+ * early once every pending source has moved.+ *+ * Exit: `not_moving` → 1 with code `managed_sync_not_moving` (`reason:+ * movement_check`) and the writer summary; `parked` → 1 with the same code+ * and `state: parked` (after a restart nothing picked the catch-up up);+ * `held`/`within_allowance`/`moved`/`nothing_pending` → 0; `--warn-only`+ * prints the same envelopes and exits 0. A read failure keeps its own code+ * (`fix.next: report`), never `managed_sync_not_moving`. `gbrain upgrade`+ * never runs this (it owns no relaunch); it prints the bare command for the+ * supervisor's step.+ */+import type { BrainEngine } from '../core/engine.ts';+import { getCliOptions } from '../core/cli-options.ts';+import { finishCliTeardown, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';+import { loadConfig, toEngineConfig } from '../core/config.ts';+import { resolveBrainId } from '../core/brain-resolver.ts';+import { loadMounts } from '../core/brain-registry.ts';+import { opError } from '../core/ops/contract.ts';+import { readFix } from '../core/ops/op-fix.ts';+import { cliRenderContext, renderAction, toAgentError, type Action, type AgentEnvelope, type RenderedAction } from '../core/agent-output.ts';+import { parseDurationSeconds } from '../core/sync-concurrency.ts';+import { persistenceConfigForBrain } from '../core/persistence/local-client.ts';+import { readPreparationPolicy } from '../core/persistence/switches.ts';+import { judgeMovement, readSourceMovement, writerStatusCommand, type MovementVerdict, type SourceMovement } from '../core/persistence/sync-movement.ts';+import { stalledHoldSteps } from '../core/persistence/sync-holds.ts';+import { adminHostConfig } from './persistence-admin.ts';+import { reportPersistenceCliError } from './persistence-delegate.ts';++export const MOVEMENT_HELP = `Usage:+ gbrain sources writer movement [<source>] [--source <id>] [--wait <dur>] [--warn-only] [--json] [--brain <id>]++Proves that managed sync data moves: snapshots every active managed source,+waits the window, and judges each one from committed pages and the head's step+(a renewed lease, a live lock or a healthy /health are not movement).+ --wait <dur> The window (30s, 5m, 1h; seconds when bare). Default: the larger of 5m and+ persistence.sync_preparation_ms + 60s, printed as the budget judged against.+ --warn-only Print the same verdicts and envelopes but exit 0 (pipelines that cannot fail).+States: moved, within_allowance (a step or cursor advanced; a multi-wave group preparing+normally), held (advanced only by holds; the hold kind's repair route is printed), parked+(pending work and nothing live to move it), not_moving, nothing_pending.+Exit 1 with code managed_sync_not_moving for not_moving and parked; 0 otherwise.+Run it after restarting serve and the workers: gbrain sources writer movement`;++/** The bare command `gbrain upgrade` and `gbrain post-upgrade` print for the supervisor's step (no flags, so it inherits the default window). */+export const MOVEMENT_SUPERVISOR_STEP = 'after restarting serve and the workers, run: gbrain sources writer movement';++export const MOVEMENT_DEFAULT_MIN_MS = 300_000;+export const MOVEMENT_BUDGET_GRACE_MS = 60_000;+const POLL_MS = 10_000;++export interface MovementArgs { sourceId?: string; waitMs?: number; warnOnly: boolean; json: boolean; brain?: string }+export function parseMovementArgs(args: string[]): MovementArgs {+ const out: MovementArgs = { warnOnly: false, json: false };+ const usage = (message: string, suggestion: string) => opError('invalid_params', message, suggestion,+ { fix: readFix('Prints the movement command\'s flags and states.', { argv: ['gbrain', 'sources', 'writer', 'movement', '--help'] }) });+ for (let i = 0; i < args.length; i++) {+ const token = args[i]!;+ const equal = token.indexOf('=');+ const flag = token.startsWith('-') && equal > 0 ? token.slice(0, equal) : token;+ const value = () => { const v = equal > 0 && token.startsWith('-') ? token.slice(equal + 1) : args[++i]; if (v === undefined || v.startsWith('--')) throw usage(`${flag} requires a value.`, `Give ${flag} its value right after it, as ${flag} <value>.`); return v; };+ if (!token.startsWith('-')) { if (out.sourceId !== undefined) throw usage('Specify the source once.', `Name the source either as the argument or with --source, not both (here ${out.sourceId} and ${token}).`); out.sourceId = token; }+ else if (flag === '--json') out.json = true;+ else if (flag === '--warn-only') out.warnOnly = true;+ else if (flag === '--source') { if (out.sourceId !== undefined) throw usage('Specify the source once.', 'Name the source either as the argument or with --source, not both.'); out.sourceId = value(); }+ else if (flag === '--brain') out.brain = value();+ else if (flag === '--wait') {+ const seconds = parseDurationSeconds(value(), '--wait');+ if (seconds === undefined || seconds === null) throw usage('--wait requires a duration.', 'Give --wait a duration such as 30s, 5m or 1h (bare numbers are seconds).');+ out.waitMs = seconds * 1000;+ }+ else throw usage(`Unknown option: ${flag}.`, 'The accepted options are --source, --wait, --warn-only, --json and --brain.');+ }+ return out;+}++/** The window the command judges against: never below one sync preparation budget, by default the larger of 5 minutes and the budget plus a minute. */+export function movementWindowMs(policy: { syncMs: number }, requested?: number): { window_ms: number; budget_ms: number; source: 'default' | '--wait' } {+ if (requested !== undefined) return { window_ms: Math.max(requested, policy.syncMs), budget_ms: policy.syncMs, source: '--wait' };+ return { window_ms: Math.max(MOVEMENT_DEFAULT_MIN_MS, policy.syncMs + MOVEMENT_BUDGET_GRACE_MS), budget_ms: policy.syncMs, source: 'default' };+}++export interface MovementReport {+ source_id: string;+ state: MovementVerdict;+ exit: 0 | 1;+ code: 'managed_sync_not_moving' | null;+ reason?: 'movement_check';+ why: string;+ fix: RenderedAction | null;+ retry_after_ms?: number;+ before: SourceMovement | undefined;+ after: SourceMovement;+}++/** The verdict, exit and agent-operator envelope for one source over the window. */+export function movementReport(before: SourceMovement | undefined, after: SourceMovement, windowMs: number): MovementReport {+ const state = judgeMovement(before, after);+ const ctx = cliRenderContext();+ const id = after.source_id;+ const status: Action = readFix('Read-only: the request at the head, its step and wait cause, the owner process and the next action on the running claim.',+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', id, '--json'] });+ const verify = { argv: ['gbrain', 'sources', 'writer', 'movement', id, '--json'] };+ const head = after.head?.step ? ` The head is at step ${after.head.step}${after.head.waiting_on && after.head.waiting_on !== 'unknown' ? ` (waiting on ${after.head.waiting_on})` : ''}${after.head.owner ? `, held by ${after.head.owner.kind} pid ${after.head.owner.pid}` : ''}.` : '';+ switch (state) {+ case 'nothing_pending':+ return { source_id: id, state, exit: 0, code: null, why: `${id}: no managed sync is pending${after.holds.count ? ` (${after.holds.count} held file(s) await their repair)` : ''}.`, fix: null, before, after };+ case 'moved':+ return { source_id: id, state, exit: 0, code: null, why: `${id}: a page committed at ${after.last_commit_at} inside the ${Math.round(windowMs / 1000)}s window; ${after.cursor ? `${after.cursor.remaining} remaining` : 'the cursor is done'}.`, fix: null, before, after };+ case 'within_allowance':+ return { source_id: id, state, exit: 0, code: null, retry_after_ms: windowMs,+ why: `${id}: no page committed yet, but the head's step or the cursor advanced inside the window (a multi-wave group commits nothing until its last wave).${head} Check again after one more window.`,+ fix: renderAction({ argv: ['gbrain', 'sources', 'writer', 'movement', id, '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'The owner is preparing normally; rerun after retry_after_ms and the next window shows the commit.', verify }, ctx), before, after };+ case 'held': {+ const kinds = after.holds;+ const route = kinds.stalled > 0 ? stalledHoldSteps(id).status : kinds.fences > 0 ? ['gbrain', 'repair', 'fences', '--source', id] : ['gbrain', 'repair', 'frontmatter', '--source', id];+ const then = kinds.stalled > 0 ? ` then ${stalledHoldSteps(id).retry.join(' ')}` : '';+ return { source_id: id, state, exit: 0, code: null,+ why: `${id}: pending work advanced only by holds inside the window (${kinds.count} held: ${kinds.stalled} preparation_stalled, ${kinds.fences} fence, ${kinds.concurrent} concurrent-write). The containment is working, not a stall; the held files need their repair route.`,+ fix: renderAction({ argv: route, consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/repair.md#held-files',+ why: kinds.stalled > 0 ? `Read-only: shows the owner the stalled preparations name;${then} once the cause is fixed.` : 'Read-only preview of the repair; it prints the apply command for the user to approve.', verify }, ctx), before, after };+ }+ case 'parked':+ return { source_id: id, state, exit: 1, code: 'managed_sync_not_moving', reason: 'movement_check',+ why: `${id}: the managed sync cursor is pending at ${after.cursor?.index ?? '?'}/${after.cursor?.total ?? '?'} and nothing live is moving it (no sync run holds the lock; ${after.admitted} admitted request(s), no live consumer on the owner host). After a restart this means the catch-up was not started again.`,+ fix: renderAction({ argv: (after.cursor?.resume_command ?? `gbrain sync --source ${id} --no-pull`).split(' '), consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Resumes the managed catch-up where its cursor stopped; the same command is safe to rerun in a loop.', verify }, ctx), before, after };+ case 'not_moving':+ return { source_id: id, state, exit: 1, code: 'managed_sync_not_moving', reason: 'movement_check',+ why: `${id}: ${after.cursor ? `${after.cursor.remaining} entries pending, ` : ''}no page committed and no step advance inside the ${Math.round(windowMs / 1000)}s window while ${after.live.drain ? `a sync (pid ${after.live.drain_pid}) holds the lock` : 'a consumer is live'}; last progress ${after.last_progress_at ?? 'unknown'}.${head}`,+ fix: renderAction({ ...status, verify }, ctx), before, after };+ }+}++export function formatMovementReport(r: MovementReport): string[] {+ const lines = [`${r.state === 'not_moving' || r.state === 'parked' ? '✗' : '✓'} ${r.source_id}: ${r.state}${r.code ? ` [${r.code}${r.reason ? `/${r.reason}` : ''}]` : ''}`, ` ${r.why}`];+ if (r.fix?.command) lines.push(` Next: ${r.fix.command}${r.retry_after_ms ? ` (after ${Math.round(r.retry_after_ms / 1000)}s)` : ''}${r.fix.next === 'tell_user_to_run' ? ' (the host operator runs it)' : ''}`);+ return lines;+}++export async function runWriterMovementCli(args: string[], connected?: BrainEngine): Promise<void> {+ if (args.some(arg => arg === '--help' || arg === '-h')) { console.log(MOVEMENT_HELP); return; }+ let owned: BrainEngine | undefined;+ let json = false;+ try {+ const parsed = parseMovementArgs(args);+ json = parsed.json;+ const brainId = resolveBrainId(parsed.brain ?? getCliOptions().brain);+ const config = adminHostConfig(persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts()), brainId, 'The movement check', 'sources writer movement');+ if (!connected) {+ const { createEngine } = await import('../core/engine-factory.ts');+ owned = await createEngine(toEngineConfig(config));+ await owned.connect(toEngineConfig(config));+ }+ const engine = connected ?? owned!;+ const result = await runMovementCheck(engine, parsed, line => { if (!json) console.error(line); });+ const exitCode = parsed.warnOnly ? 0 : result.exit_code;+ if (json) await writeStdoutFinal(JSON.stringify({ ...result, exit_code: exitCode, warn_only: parsed.warnOnly, selected_brain: brainId }, null, 2) + '\n');+ else for (const r of result.sources) for (const line of formatMovementReport(r)) console.log(line);+ if (!json && !result.sources.length) console.log('No active managed source: nothing to judge (exit 0).');+ if (!json && parsed.warnOnly && result.exit_code !== 0) console.log('--warn-only: exiting 0 despite the verdict above.');+ setCliExitVerdict(exitCode);+ } catch (error) {+ if (!await reportPersistenceCliError(error, json)) {+ console.error(error instanceof Error ? error.message : String(error));+ setCliExitVerdict(1);+ }+ } finally { if (owned) await finishCliTeardown({ engine: owned, drainTimeoutMs: 1000 }); }+}++export interface MovementCheckResult {+ schema_version: 1;+ window_ms: number;+ budget_ms: number;+ window_source: 'default' | '--wait';+ waited_ms: number;+ sources: MovementReport[];+ exit_code: 0 | 1;+ /** The envelope of the first failing source (what a caller reads first), when any. */+ error?: AgentEnvelope;+}++/** Snapshot, wait (ending early once every pending source moved), snapshot, judge. `note` receives the human progress lines. */+export async function runMovementCheck(engine: BrainEngine, opts: { sourceId?: string; waitMs?: number; pollMs?: number; sleep?: (ms: number) => Promise<void> }, note: (line: string) => void = () => {}): Promise<MovementCheckResult> {+ const policy = await readPreparationPolicy(engine);+ const window = movementWindowMs(policy, opts.waitMs);+ const scope = opts.sourceId ? { sourceIds: [opts.sourceId] } : {};+ const before = await readSourceMovement(engine, scope);+ const pendingBefore = before.filter(m => m.movement_state !== 'nothing_pending');+ note(`[movement] window ${Math.round(window.window_ms / 1000)}s (${window.source === 'default' ? `default: max(300s, sync preparation budget ${Math.round(window.budget_ms / 1000)}s + 60s)` : `--wait, floored at the ${Math.round(window.budget_ms / 1000)}s sync preparation budget`}); `+ + `${before.length} managed source(s), ${pendingBefore.length} with pending work.`);+ const byId = new Map(before.map(m => [m.source_id, m]));+ let after = before, waited = 0;+ if (pendingBefore.length) {+ const sleep = opts.sleep ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms)));+ const poll = Math.max(1, Math.min(opts.pollMs ?? POLL_MS, window.window_ms));+ const started = Date.now();+ for (;;) {+ await sleep(Math.min(poll, window.window_ms - waited));+ waited = Date.now() - started;+ after = await readSourceMovement(engine, scope);+ const settled = after.every(m => { const v = judgeMovement(byId.get(m.source_id), m); return v === 'moved' || v === 'nothing_pending'; });+ if (settled || waited >= window.window_ms) break;+ note(`[movement] ${Math.round(waited / 1000)}s: ${after.map(m => `${m.source_id} ${judgeMovement(byId.get(m.source_id), m)}`).join(', ')}`);+ }+ }+ const sources = after.map(m => movementReport(byId.get(m.source_id), m, window.window_ms));+ const failing = sources.find(r => r.exit !== 0);+ const error = failing ? toAgentError(opError('managed_sync_not_moving', failing.why, `Run ${writerStatusCommand(failing.source_id)} and follow the running claim's next_action; verify with gbrain sources writer movement ${failing.source_id}.`,+ { reason: failing.reason, fix: readFix('Read-only: the request at the head, its step, wait cause, owner and next action.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', failing.source_id, '--json'] }) }),+ { transport: 'cli', command: 'sources writer movement', render: cliRenderContext() }) : undefined;+ return { schema_version: 1, window_ms: window.window_ms, budget_ms: window.budget_ms, window_source: window.source, waited_ms: waited, sources, exit_code: failing ? 1 : 0, ...(error ? { error } : {}) };+}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex add8e650fc..5f767eff8a 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1250,6 +1250,9 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {const sharedSkills = new Map(await Promise.all(sources.map(async source => [source.id, await sharedSkillsView.readSharedSkillsSourceView(engine, source.id).catch(() => null)] as const)));const uncommittedView = await import('../core/fence-repair/uncommitted.ts');const uncommitted = await uncommittedView.uncommittedFenceRepairsBySource(engine, sources.map(source => source.id));+ // #6317 (B4): whether managed sync data moves, beside sync_running (a live lock is not progress); the writer-status command rides along.+ const movementView = await import('../core/persistence/sync-movement.ts');+ const movement = new Map((await movementView.readSourceMovement(engine, { sourceIds: sources.map(source => source.id) }).catch(() => [])).map(m => [m.source_id, m]));if (json) {const enriched = metrics.map((m) => ({...m,@@ -1258,6 +1261,8 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {...(ingestion.get(m.source_id) ? { ingestion: ingestion.get(m.source_id) } : {}),...(connectors.get(m.source_id) ? { connector: connectors.get(m.source_id) } : {}),...(backlog.get(m.source_id) ? { managed_backlog: backlog.get(m.source_id) } : {}),+ ...(movement.get(m.source_id) ? { data_moving: movement.get(m.source_id)!.data_moving, not_moving_since: movement.get(m.source_id)!.not_moving_since,+ movement_state: movement.get(m.source_id)!.movement_state, movement: movement.get(m.source_id) } : {}),...(gitHolds.get(m.source_id) ? { git_holds: gitHolds.get(m.source_id) } : {}),...(sharedSkills.get(m.source_id) ? { shared_skills: sharedSkills.get(m.source_id) } : {}),...(uncommitted.get(m.source_id) ? { fence_repairs_uncommitted: uncommitted.get(m.source_id) } : {}),@@ -1301,6 +1306,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {for (const [sourceId, status] of connectors) for (const line of statusView.connectorStatusLines(sourceId, status)) console.log(line);for (const [sourceId, status] of gitHolds) for (const line of statusView.gitHoldStatusLines(sourceId, status)) console.log(line);for (const b of backlog.values()) console.log(` ${drainMod.formatManagedSyncBacklog(b)}`);+ for (const m of movement.values()) { const line = movementView.formatSourceMovement(m); if (line) console.log(` ${line}`); }for (const [sourceId, notices] of uncommitted) for (const line of uncommittedView.uncommittedFenceRepairLines(sourceId, notices)) console.log(line);for (const view of sharedSkills.values()) if (view && (only || view.configured === false || view.parked)) for (const line of sharedSkillsView.sharedSkillsStatusLines(view)) console.log(` ${line}`);for (const m of metrics) {@@ -1943,7 +1949,7 @@ Subcommands:Register a new source. --path must be a git repowith committed files; --force skips that check.list [--json] List registered sources with page counts.- writer status|claim|activate|transfer Inspect, activate or transfer canonical ownership (see writer --help).+ writer status|movement|claim|activate|transfer Inspect ownership, prove data moves, activate or transfer (see writer --help).reconcile <id> <slug> --brain <id> Preview or apply a guarded file/database repair (see reconcile --help).remove <id> [--confirm-destructive] [--dry-run]Permanently delete a source and all its data.diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 1b13c7c4e4..cd21c86ab1 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -290,6 +290,8 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string}console.log(`Binary: installed ${newVersion || 'a new version (could not verify)'}`);console.log(migrationsLine);+ // #6317 (I2): upgrade owns no relaunch, so the supervisor proves data movement after it restarts serve and the workers.+ console.log(`Next: ${(await import('./sources-writer-movement.ts')).MOVEMENT_SUPERVISOR_STEP}`);}/**@@ -888,6 +890,8 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {} catch {// Fail-open per A18: never crash post-upgrade from the banner.}+ // #6317 (I2): the supervisor's step; bare, so the check inherits its default window.+ (json ? console.error : console.log)(`Next: ${(await import('./sources-writer-movement.ts')).MOVEMENT_SUPERVISOR_STEP}`);if (json) await writeJsonDocument(JSON.stringify(report));}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex bfd7d368ed..4c273aa043 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -18,7 +18,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--prefer-postgres', '--probe', '--require-db', '--skip-verify', '--source', '--uninstall', '--url', '--yes'],- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--probe', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],@@ -90,7 +90,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--older-than', '--source', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],- 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--provenance', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],@@ -108,7 +108,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--only', '--probe', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--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', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait-drain', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait', '--wait-drain', '--warn-only', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -121,7 +121,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--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', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait', '--wait-drain', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait', '--wait-drain', '--warn-only', '--yes'],'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--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-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],@@ -129,7 +129,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--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', '--wait'],- 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 0343dd14a7..8e75001361 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -248,6 +248,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['persistence_request_growth','persistence_request_indexes','persistence_write_stall',+ 'managed_sync_not_moving','persistence_session_timeouts','stale_embedding_effects','vector_plan',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 11f5189066..c2990c04b4 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -132,6 +132,14 @@ export const CODES = {demo_verification_failed: { class: 'server', summary: "Expected ownership or decision provenance is missing." },derived_cap_exhausted: { class: 'server', summary: "Paid work stopped at the cost cap derived from its estimate; the run is resumable." },destination_not_ready: { class: 'host_only', summary: "The destination brain is not initialized for this operation." },+ drain_stalled: { class: 'server', retryable: false, actor: 'host_admin',+ summary: "A managed sync drain stopped `blocked` because its head write made no progress (no committed receipt and no step advance) for the whole stall window.",+ why: "A renewed lease is not progress: the detector keys on the head claim's phase and step. With a live owner on this host the drain prints `stalled <N>s on <step>` from the allowance (budget plus 30 s) and keeps going; it stops only when `persistence.preparation_ceiling_ms` passes without the root being released, or when that owner's heartbeat row reads wedged (`cause: owner_wedged_here`, with the owner's kind, pid and nonce and `retry_after_ms` to the ceiling, after which the owner frees the root and the next pass holds the entry). A lapsed claim (`owner_missing`) stops at once unless this host owns the checkout and a live full consumer can reclaim it, which gets one more window. `drain.stall.cause` names which.",+ reasons: ['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress'],+ docs: 'docs/guides/write-refusals.md#drain-stalled',+ suggestion: 'Inspect the writer with gbrain sources writer status --source <id> --json (read-only: the owner process, its step and what it waits on, and the next action). Before the ceiling (`next.safe_to_loop` true) rerun next.command after retry_after_ms; past it, or with a wedged owner, restart the named owner process on the brain host and rerun the same sync.',+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: names the owner process holding the head write (kind, pid), its step and wait cause, and ends in a next_action.", requires_exclusive: false,+ verify: { argv: ['gbrain', 'doctor', '--only', 'managed_sync_not_moving', '--json'] } } },dream_breaker_tripped: { class: 'unavailable', summary: "A dream synthesize or patterns submission died (or, for patterns, was cancelled at its timeout after paid work) the breaker limit of times within 24 hours, so it was not submitted again.", why: "A run that keeps dying keeps paying; the breaker stops resubmitting until the cause is fixed and the key is reset. Patterns count per source (`dream:patterns:source:<id>`) whatever reflections each run read, and a completed run resets that count.", docs: 'docs/operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions', fix: { argv: ['gbrain', 'doctor', '--only', 'dream_paid_loop', '--json'], consent: [], actor: 'agent', why: 'Shows the tripped dream keys with their counts and reset commands, read-only.', requires_exclusive: false } },dirty_tree: { class: 'caller', summary: "Commit or stash canonical skill edits before optimization." },effect_not_failed: { class: 'caller', summary: "Only a failed, non-running embedding effect can be explicitly retried." },@@ -225,6 +233,13 @@ export const CODES = {maintenance_backpressure: { class: 'retryable', summary: "Managed maintenance stopped admitting requests because this writer's outstanding requests, reserved receipt bytes or permanent request ids would pass 80% of their limit; nothing more was submitted.", why: "Each page of a maintenance run publishes as its own request under the local CLI writer the user's own CLI writes share. Stopping at 80% leaves room for those writes: reserved receipt bytes free only when receipts compact, request ids never.", docs: 'docs/guides/write-refusals.md#maintenance_backpressure', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the pending requests holding this writer's capacity, read-only.", requires_exclusive: false }, exit: 12 },maintenance_lock_busy: { class: 'retryable', summary: "A source-scoped dream cycle skipped its brain-wide phases because another cycle (usually autopilot maintenance) holds the shared gbrain-cycle lease; its source phases still ran.", why: 'Brain-wide phases (synthesize, patterns, embed, purge and the other mixed or global phases) must not run twice at once, so a cycle that cannot take gbrain-cycle runs only the phases its own source lease covers.', docs: 'docs/guides/cron-schedule.md#dream-beside-autopilot', suggestion: 'Nothing is lost: the holder runs those phases itself. To run one now, wait until the lease is released, then re-run `gbrain dream --phase <phase>` (LLM-backed phases spend; ask the user first).', fix: { argv: ['gbrain', 'status', '--section', 'locks', '--json'], consent: [], actor: 'agent', why: 'Shows who holds gbrain-cycle and when its lease expires, read-only.', requires_exclusive: false } },managed_pull_skipped: { class: 'retryable', summary: "The managed pull was skipped." },+ managed_sync_not_moving: { class: 'server', retryable: false, actor: 'host_admin',+ summary: "A managed source has unfinished sync work and a live consumer on its owner host, but no committed `managed_sync_*` receipt and no head step advance for longer than `persistence.preparation_ceiling_ms`.",+ why: "Process liveness is not data movement: `/health` ok, a live pid and `sync_running: true` all held while one deployment moved nothing for weeks. `sources status --json` carries `data_moving`, `not_moving_since` and `movement_state` per source (`parked` when no drain or full consumer is live, informational), doctor warns with this code and counts it against the score, `serve` prints one notice when a source flips, and `gbrain sources writer movement` judges a window after a restart and exits 1 with this code (`reason: movement_check`) when pending work does not move.",+ reasons: ['movement_check'],+ docs: 'docs/guides/troubleshooting.md#managed-sync-not-moving',+ suggestion: 'Run gbrain sources writer status --source <id> --json (read-only): its next_action names the owner process, the step it is parked on and whether to wait or restart it. After the fix, gbrain sources writer movement proves the data moves again.',+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: the owner process, the head write\'s step and wait cause, and a next_action (wait with retry_after_ms, or restart the named pid).', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'managed_sync_not_moving', '--json'] } } },manual_only_skipped: { class: 'consent', summary: "An automatic remediation run (`gbrain onboard --auto`, `doctor --remediate`, MCP `run_onboard`, autopilot) did not submit a manual-only step: the schema-pack upgrade (`unify-types`) or the paid takes bootstrap (`extract-takes-from-pages`).", why: "A pack upgrade retypes pages and switches the brain's schema pack, and the takes bootstrap pays a model per page; both are the user's one-time decision, so only the user submits them. A job of that kind an earlier run already queued is listed in `queued_jobs` and still runs unless cancelled.", actor: 'user', suggestion: 'Show the user the step and its `fix.command` (`gbrain jobs submit <job> --follow`, with `--params` when the step has them); the user runs it after reviewing `gbrain onboard --check`. Cancel a listed queued job with `gbrain jobs cancel <id>` if the user does not want it.', fix: { argv: ['gbrain', 'jobs', 'list', '--status', 'waiting'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists queued jobs, including any manual-only job an earlier run queued.' } },membership_inactive: { class: 'caller', summary: "The shared-skills enrollment epoch was left or superseded.", docs: 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment' },membership_not_found: { class: 'caller', summary: "This principal has no shared-skills membership with that installation id.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex 1c30196e57..42296a7d66 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -228,7 +228,9 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatiohost_id: existingLocalHostId(), local_host_id: existingLocalHostId(), bindings, admin_state: adminState,admin_lock: { locked: adminLock.locked, set_at: adminLock.set_at, host_id: adminLock.host_id }, blocking_effects: blockingEffects,writer_versions: writerVersions, onboarding, shared_skills: sharedSkills, ...(native ? { native_lock: native } : {}),- worktree_refreshes: await (await import('./worktree-refresh.ts')).activeWorktreeRefreshes(engine, params.source_id as string | undefined) };+ worktree_refreshes: await (await import('./worktree-refresh.ts')).activeWorktreeRefreshes(engine, params.source_id as string | undefined),+ // #6317 (B4): per managed source, whether sync data moves (shares the reader of sources status, doctor and writer movement).+ movement: await (await import('./sync-movement.ts')).readSourceMovement(engine, params.source_id === undefined ? {} : { sourceIds: [source(params.source_id)] }).catch(() => []) };}if (operation === 'writer_claim') {keys(params, ['source_id', 'path', 'dry_run', 'admin_intent', 'expected_state']);diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.tsindex d94fdc0cab..20336f2294 100644--- a/src/core/persistence/diagnostics.ts+++ b/src/core/persistence/diagnostics.ts@@ -4,7 +4,10 @@ import type { JournalLimits } from './model.ts';import { publicationConcurrency } from './pool-capacity.ts';import { WRITER_INSPECTION_HINT } from './admin-intent.ts';import { writeHealth } from './health.ts';-import { claimStall, claimStateOf, type ClaimRow } from './claim-phase.ts';+import { claimStall, claimStateOf, isOwnerThisProcess, type ClaimRow, type ClaimState, type ClaimStall } from './claim-phase.ts';+import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';+import { enginePoolStats, type DriverPoolStats } from '../postgres-engine/pool-stats.ts';+import { consumerLive, listHostConsumers, type ConsumerRow } from './consumer-heartbeat.ts';import type { WriteRequestState } from './types.ts';import { preparationBudgetMs } from './preparation-budget.ts';import { readWriteSwitchSnapshot } from './switches.ts';@@ -35,6 +38,44 @@ export const WRITER_NEXT_ACTIONS: Record<string, string> = {export function writerNextAction(reason: string | null | undefined): string {return reason && WRITER_NEXT_ACTIONS[reason] || 'Inspect the sanitized receipt and owner diagnostics before retrying with the same request_id.';}++/**+ * #6317 (C1): the one `next_action` envelope a running claim ends with, so the two-call journey (sources status → writer+ * status) ends in an action: inside the allowance the agent reruns status after `retry_after_ms` (`next: run`); past the+ * ceiling or on `restart_required` the host admin restarts the named owner (`tell_user_to_run`); a lapsed claim resumes+ * on its own once its transaction ends or the owner exits, so the fix is the resume (`run`).+ */+export interface ClaimNextAction { code: 'claim_running' | 'claim_overdue' | 'claim_lapsed'; why: string; retry_after_ms: number | null; fix: RenderedAction }+export function claimNextAction(claim: ClaimState, stall: ClaimStall | null, policy: { budgetMs: number | null; ceilingMs: number }, sourceId: string | null,+ owner: { row: ConsumerRow | null; live: boolean | null }, now = Date.now()): ClaimNextAction {+ const ctx = cliRenderContext();+ const status = ['gbrain', 'sources', 'writer', 'status', ...(sourceId ? ['--source', sourceId] : []), '--json'];+ const who = claim.owner ? `${claim.owner.kind} pid ${claim.owner.pid}` : 'the owner';+ const where = `${claim.step ? ` at step ${claim.step}` : ''}${claim.waiting_on !== 'unknown' ? ` (waiting on ${claim.waiting_on})` : ''}${claim.last_sql ? `, last statement ${claim.last_sql.label}` : ''}`;+ if (claim.phase === 'publication_transaction') {+ return { code: 'claim_lapsed', retry_after_ms: null, why: `The claim lapsed while running; the request is requeued once the transaction holding its row ends or the owner exits, and the next consumer claims it.`,+ fix: renderAction({ argv: status, consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: rerun to see the request requeued or claimed again.', verify: { argv: status } }, ctx) };+ }+ const age = claim.phase_age_ms ?? claim.claim_age_ms ?? 0;+ const pastCeiling = claim.phase === 'preparing' && age >= policy.ceilingMs;+ const wedged = owner.row?.restart_required === true || (owner.row?.root_barrier_age_ms ?? -1) > policy.ceilingMs;+ if (pastCeiling || wedged) {+ return { code: 'claim_overdue', retry_after_ms: 0,+ why: `${who} has held this claim${where} for ${Math.round(age / 1000)}s${pastCeiling ? `, past the ${Math.round(policy.ceilingMs / 1000)}s ceiling` : ''}${owner.row?.restart_required ? ' and reports restart_required' : wedged ? ' and reports a root barrier past the ceiling' : ''}; only restarting that process ends the work it is parked in.`,+ fix: renderAction({ argv: status, consent: [], actor: 'host_admin', requires_exclusive: false, why: 'Restart the named process on this host, then rerun status (read-only) to see the claim released.',+ user_message: `Restart the gbrain ${claim.owner?.kind ?? 'owner'} process${claim.owner ? ` (pid ${claim.owner.pid})` : ''} on the brain host.`, verify: { argv: status } }, ctx) };+ }+ const budgetLeft = stall ? Math.max(0, policy.ceilingMs - age) : policy.budgetMs === null ? null : Math.max(0, policy.budgetMs - age);+ return { code: 'claim_running', retry_after_ms: budgetLeft,+ why: stall ? `${who} is past the ${Math.round(stall.budget_ms / 1000)}s preparation budget${where}; its own budget cuts the preparation off and frees the root by the ${Math.round(policy.ceilingMs / 1000)}s ceiling (${Math.round((budgetLeft ?? 0) / 1000)}s left). Nothing to do yet.`+ : `${who} is ${claim.phase === 'publishing' ? 'publishing' : 'preparing'} this write${where}${owner.live === false ? '; its heartbeat row is not live' : ''}. Nothing to do yet.`,+ fix: renderAction({ argv: status, consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: rerun after retry_after_ms to see the step advance or the claim settle.', verify: { argv: status } }, ctx) };+}+/** #6317 (C1): the pool numbers for a running claim: this process's driver when it owns the claim, else the owner's heartbeat row. */+function claimPool(engine: BrainEngine, claim: ClaimState, row: ConsumerRow | null): { pool: DriverPoolStats | null; pool_source: 'driver' | 'heartbeat' | null } {+ if (isOwnerThisProcess(claim.owner)) return { pool: enginePoolStats(engine), pool_source: enginePoolStats(engine) ? 'driver' : null };+ return { pool: row?.pool ?? null, pool_source: row?.pool ? 'heartbeat' : null };+}interface Counter { key: string; outstanding_count: string | number; intent_bytes: string | number;lifetime_ids: string | number; terminal_bytes: string | number; recovery_bytes: string | number; }export function capacityDiagnostics(counters: Counter[], limits: JournalLimits) {@@ -69,9 +110,9 @@ export async function readWriterDiagnostics(engine: BrainEngine) {GROUP BY w.id ORDER BY w.id`);const counters = await engine.executeRaw<Counter>(`SELECT key,outstanding_count::text,intent_bytes::text,lifetime_ids::text,terminal_bytes::text,recovery_bytes::text FROM persistence_counters ORDER BY key`);// #6278: the operation and intent kind say which budget applies and tell a sync member from a maintenance write; the owner process comes from the live claim's stamp.- const blockers = await engine.executeRaw<{ request_id: string; worktree_id: string | null; state: WriteRequestState; created_at: Date | string; blocked_reason: string | null; error_code: string | null;+ const blockers = await engine.executeRaw<{ request_id: string; worktree_id: string | null; source_id: string | null; state: WriteRequestState; created_at: Date | string; blocked_reason: string | null; error_code: string | null;operation: string; intent_kind: string | null; preparation_attempts: number | null } & Omit<ClaimRow, 'state'>>(- `SELECT request_id,worktree_id,state,blocked_reason,error_code,created_at,claim_phase,execution_token,claim_expires_at<now() AS claim_lapsed,publication_started,+ `SELECT request_id,worktree_id,source_id,state,blocked_reason,error_code,created_at,claim_phase,execution_token,claim_expires_at<now() AS claim_lapsed,publication_started,operation,intent->>'kind' AS intent_kind,preparation_attemptsFROM persistence_requests WHERE state IN ('queued','running','recovering') OR blocked_reason IS NOT NULL ORDER BY sequence LIMIT 100`);const queue = await engine.executeRaw(`SELECT state,COUNT(*)::integer AS count,COALESCE(SUM(intent_bytes),0)::text AS intent_bytes,@@ -92,6 +133,11 @@ export async function readWriterDiagnostics(engine: BrainEngine) {const preparation_policy = snapshot ? { deadlines: snapshot.switches.preparation_deadlines, sync_preparation_ms: snapshot.preparation.syncMs,maintenance_preparation_ms: snapshot.preparation.maintenanceMs, preparation_ceiling_ms: snapshot.preparation.ceilingMs, max_preparation_attempts: snapshot.preparation.maxAttempts } : null;const { persistenceConsumerStatus } = await import('./service.ts');+ // #6317 (C1): the heartbeat rows of this host, read once, so each running claim can name its owner's liveness and pool.+ const { existingLocalHostId } = await import('./identity.ts');+ const hostId = existingLocalHostId();+ const consumerRows = hostId ? await listHostConsumers(engine, hostId) : [];+ const tracked = (engine as { getPoolDiagnostics?: () => { tracked?: unknown } | null }).getPoolDiagnostics?.()?.tracked ?? null;// C-NEW-4: the consumer is per process, so this is the answering process's own ingress, never proof the brain's owner is down.const local = persistenceConsumerStatus(engine);const local_process_ingress = { ...local, scope: local.state === 'not_running'@@ -108,7 +154,12 @@ export async function readWriterDiagnostics(engine: BrainEngine) {const state = claimStateOf({ state: row.state, claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started });const budget = snapshot ? preparationBudgetMs({ operation: row.operation, intent: row.intent_kind ? { kind: row.intent_kind } : null }, snapshot.preparation, 30_000) : null;const stall = state && budget !== null ? claimStall(state, budget) : null;- const claim = state ? { ...state, ...(budget === null ? {} : { budget_ms: budget }), stall } : undefined;+ // #6317 (C1): the owner's heartbeat row (liveness, pool), the last statement, and the one next_action envelope per running claim.+ const ownerRow = state?.owner ? consumerRows.find(r => r.pid === state.owner!.pid && (state.owner!.nonce === undefined || r.nonce === state.owner!.nonce)) ?? null : null;+ const ceilingMs = snapshot?.preparation.ceilingMs ?? 600_000;+ const claim = state ? { ...state, ...(budget === null ? {} : { budget_ms: budget }), stall, ...claimPool(engine, state, ownerRow), pool_tracked_subset: tracked,+ owner_live: ownerRow ? consumerLive(ownerRow) : null, owner_mode: ownerRow?.mode ?? null,+ next_action: claimNextAction(state, stall, { budgetMs: budget, ceilingMs }, row.source_id, { row: ownerRow, live: ownerRow ? consumerLive(ownerRow) : null }) } : undefined;return { ...row, preparation_attempts: row.preparation_attempts ?? 0, ...health, ...(claim ? { claim } : {}), next_action: health.diagnostic?.next_action === 'inspect_owner' && advice !== WRITER_INSPECTION_HINT? `${WRITER_INSPECTION_HINT} ${advice}` : advice };}) };diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 6d2458ed61..0c0dabad76 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -617,7 +617,11 @@ export interface DrainNext {rate_pages_per_min: number | null;why: string;docs?: string;- /** #6317: the stop's code and cause, and its agent-operator fix (`next: wait` while the ceiling is ahead, `tell_user_to_run` once it passed). */+ /**+ * #6317: the stop's code and cause, and its agent-operator fix: while the ceiling is ahead the agent reruns the same command after+ * `retry_after_ms` (`next: run`, `safe_to_loop: true`; `wait` is reserved for provider-side work, agent-output.ts deriveNext);+ * once it passed, `tell_user_to_run` names the owner process to restart.+ */code?: string;cause?: DrainStall['cause'];fix?: RenderedAction;@@ -675,8 +679,8 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: sconst where = `${stall.step ? ` at step ${stall.step}` : ''}${stall.waiting_on && stall.waiting_on !== 'unknown' ? `, waiting on ${stall.waiting_on}` : ''}${stall.last_sql ? `, last statement ${stall.last_sql.label}` : ''}`;const ahead = !stall.past_ceiling && (d.retry_after_ms ?? 0) > 0;const action: Action = ahead- ? { argv: resumeCommand.split(' '), consent: [], actor: 'provider', requires_exclusive: false,- why: `The ${owner} on this host still renews the claim; its own budget frees the root at the ceiling in ${formatDuration(Math.ceil((d.retry_after_ms ?? 0) / 1000))}, after which the same command resumes and holds the entry if it stalls again.`,+ ? { argv: resumeCommand.split(' '), consent: [], actor: 'agent', requires_exclusive: false,+ why: `The ${owner} on this host still renews the claim; its own budget frees the root at the ceiling in ${formatDuration(Math.ceil((d.retry_after_ms ?? 0) / 1000))}. Rerun this after retry_after_ms (safe in a loop): it resumes the cursor and holds the entry if it stalls again.`,verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] } }: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'host_admin', requires_exclusive: false,why: `The ${owner} on this host holds the claim past the ceiling${stall.owner_row?.restart_required ? ' and reports restart_required' : ''}; only restarting that process ends the preparation it is parked in. Status names the request, step and owner, read-only.`,@@ -738,6 +742,8 @@ export interface ManagedSyncBacklog {rate_pages_per_min: number | null;eta_seconds: number | null;last_progress_at: string | null;+ /** #6317: entries this cursor advanced past as holds (no page committed for them). */+ held: number;resume_command: string;/** #6278: the arguments after `gbrain sync` that resume this cursor with its stored options. */resume_args: string[];@@ -749,7 +755,7 @@ export interface ManagedSyncBacklog {*/export async function readManagedSyncBacklog(engine: BrainEngine, sourceIds?: string[]): Promise<ManagedSyncBacklog[]> {const rows = await engine.executeRaw<{ header: { sourceId: string; index: number; total: number; done?: boolean; progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };- processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean }; syncOptions?: Parameters<typeof managedSyncResumeArgs>[0]['syncOptions'] } }>(+ counts?: { held?: number }; processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean }; syncOptions?: Parameters<typeof managedSyncResumeArgs>[0]['syncOptions'] } }>(`SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'`);return rows.map(({ header }) => header).filter(h => h?.sourceId && (!sourceIds || sourceIds.includes(h.sourceId))).map(h => {const remaining = Math.max(0, Number(h.total) - Number(h.index));@@ -757,7 +763,7 @@ export async function readManagedSyncBacklog(engine: BrainEngine, sourceIds?: stconst estimate = p ? drainEstimate(remaining, p.lastIndex - p.startIndex, p.lastAt - p.startedAt) : { rate_pages_per_min: null, eta_seconds: null };const args = managedSyncResumeArgs({ sourceId: h.sourceId, processingOptions: h.processingOptions, syncOptions: h.syncOptions });return { source_id: h.sourceId, index: Number(h.index), total: Number(h.total), remaining, ...estimate,- last_progress_at: p ? new Date(p.lastAt).toISOString() : null, resume_command: syncResumeCommand(args), resume_args: args };+ last_progress_at: p ? new Date(p.lastAt).toISOString() : null, held: Number(h.counts?.held ?? 0), resume_command: syncResumeCommand(args), resume_args: args };});}diff --git a/src/core/persistence/sync-movement.ts b/src/core/persistence/sync-movement.tsnew file mode 100644index 0000000000..79a2c7761a--- /dev/null+++ b/src/core/persistence/sync-movement.ts@@ -0,0 +1,211 @@+/**+ * #6317 (B4, I2): does managed sync data move? One reader behind+ * `gbrain sources status`, `gbrain sources writer status --json`, the doctor+ * check `managed_sync_not_moving`, the `serve` notice and+ * `gbrain sources writer movement`, so no surface can call a parked sync+ * healthy while another calls it stuck.+ *+ * Per active managed source the snapshot carries the unfinished cursor+ * (`readManagedSyncBacklog`: index, total, held, the drain's last advance),+ * the movement watermark (the newest `completed_at` of a committed+ * `managed_sync_*` receipt in the current source incarnation, read through+ * the partial index on `(worktree_id, completed_at DESC) WHERE+ * state='committed'`; never a count, since compaction nulls `intent`), the+ * head request's claim stamp (`step_since` moving is progress too: a+ * multi-wave group commits nothing until its last wave), the newest hold, and+ * who could move it: a live drain (the per-source sync lock) or a live+ * consumer on the owner host (a renewing claim, this process's own consumer,+ * or a live heartbeat row).+ *+ * The verdict: `nothing_pending` (no unfinished cursor), `parked` (pending,+ * but neither a drain nor a consumer with admitted work is live: a cursor left+ * between cron runs; informational, never scored), `held` (the newest activity+ * is a hold: #6298's containment, not a stall), `moving` (a commit or a step+ * advance within `persistence.preparation_ceiling_ms`), `not_moving` (none for+ * longer than the ceiling while something live should have produced one).+ * `data_moving` is true/false for the live states and null otherwise;+ * `not_moving_since` is the last watermark. `judgeMovement` compares two+ * snapshots over a window for the standalone command (`moved`,+ * `within_allowance`, `held`, `parked`, `not_moving`, `nothing_pending`).+ * `startMovementWatch` is the serve's unref'd ticker that prints one+ * `[gbrain notice managed_sync_not_moving]` when a source flips to not moving+ * and one line when it moves again.+ */+import type { BrainEngine } from '../engine.ts';+import { readManagedSyncBacklog, type ManagedSyncBacklog } from './sync-drain.ts';+import { claimStateOf, type ClaimState } from './claim-phase.ts';+import { readPreparationPolicy } from './switches.ts';+import { consumerLive, listHostConsumers } from './consumer-heartbeat.ts';++export type MovementState = 'moving' | 'held' | 'parked' | 'not_moving' | 'nothing_pending';+export interface MovementHead {+ request_id: string;+ state: string;+ phase: ClaimState['phase'] | null;+ step: string | null;+ step_since: string | null;+ step_age_ms: number | null;+ waiting_on: ClaimState['waiting_on'] | null;+ owner: ClaimState['owner'];+ last_sql: ClaimState['last_sql'];+ lapsed: boolean;+}+export interface MovementHolds { count: number; stalled: number; fences: number; concurrent: number; last_hold_at: string | null }+export interface SourceMovement {+ source_id: string;+ sampled_at: string;+ movement_state: MovementState;+ data_moving: boolean | null;+ not_moving_since: string | null;+ /** The newest committed managed receipt of this incarnation. */+ last_commit_at: string | null;+ /** The watermark the verdict used: the newest of a commit, a head step advance and the drain's cursor advance. */+ last_progress_at: string | null;+ cursor: (Pick<ManagedSyncBacklog, 'index' | 'total' | 'remaining' | 'held' | 'last_progress_at' | 'resume_command'>) | null;+ head: MovementHead | null;+ holds: MovementHolds;+ /** Managed requests admitted on the worktree and not yet settled (queued or running). */+ admitted: number;+ live: { drain: boolean; drain_pid: number | null; consumer: 'claim' | 'local' | 'heartbeat' | null };+ ceiling_ms: number;+ owner_is_this_host: boolean | null;+ writer_status_command: string;+}++export const MOVEMENT_WATCH_MS = 60_000;++const iso = (value: unknown): string | null => {+ if (value === null || value === undefined) return null;+ const ms = value instanceof Date ? value.getTime() : typeof value === 'number' ? value : Date.parse(String(value));+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;+};+const newest = (...values: Array<string | null | undefined>): string | null => values.reduce<string | null>((best, value) => value && (!best || value > best) ? value : best, null);++export function writerStatusCommand(sourceId: string): string { return `gbrain sources writer status --source ${sourceId} --json`; }++interface BindingRow { source_id: string; worktree_id: string; source_incarnation: string; owner_host_id: string | null }+interface WatermarkRow { last_commit_at: unknown; admitted: number | string }+interface HeadRow { request_id: string; state: string; claim_phase: unknown; execution_token: string | null; claim_lapsed: boolean | null; publication_started: boolean | null }+interface HoldRow { count: number | string | null; stalled: number | string | null; fences: number | string | null; concurrent: number | string | null; updated_at: unknown }++/** The movement of every active managed source (or of `sourceIds`), one bounded read each; sources without a binding are omitted. */+export async function readSourceMovement(engine: BrainEngine, opts: { sourceIds?: string[]; now?: number } = {}): Promise<SourceMovement[]> {+ const now = opts.now ?? Date.now();+ const bindings = await engine.executeRaw<BindingRow>(`SELECT b.source_id, b.worktree_id::text AS worktree_id, b.source_incarnation::text AS source_incarnation, w.owner_host_id::text AS owner_host_id+ FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation+ JOIN persistence_worktrees w ON w.id=b.worktree_id WHERE ($1::text[] IS NULL OR b.source_id=ANY($1::text[])) ORDER BY b.source_id`, [opts.sourceIds ?? null]);+ if (!bindings.length) return [];+ const backlog = new Map((await readManagedSyncBacklog(engine, bindings.map(b => b.source_id)).catch(() => [])).map(b => [b.source_id, b]));+ const policy = await readPreparationPolicy(engine);+ const { localHostId } = await import('./identity.ts');+ const { persistenceConsumerStatus } = await import('./service.ts');+ const { liveSyncStatus } = await import('../db-lock.ts');+ const host = localHostId();+ const localConsumer = persistenceConsumerStatus(engine).state === 'open';+ let heartbeat: Promise<boolean> | undefined;+ const liveHeartbeat = () => heartbeat ??= listHostConsumers(engine, host).then(rows => rows.some(row => (row.mode === 'full' || row.mode === 'promoted') && consumerLive(row, now)));+ const out: SourceMovement[] = [];+ for (const binding of bindings) {+ const [mark] = await engine.executeRaw<WatermarkRow>(`SELECT+ (SELECT r.completed_at FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state='committed' AND r.source_incarnation=$2::uuid+ AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%' ORDER BY r.completed_at DESC LIMIT 1) AS last_commit_at,+ (SELECT count(*) FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running') AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS admitted`,+ [binding.worktree_id, binding.source_incarnation]);+ const [headRow] = await engine.executeRaw<HeadRow>(`SELECT request_id::text AS request_id, state, claim_phase, execution_token::text AS execution_token,+ (claim_expires_at IS NOT NULL AND claim_expires_at < now()) AS claim_lapsed, publication_started+ FROM persistence_requests WHERE worktree_id=$1::uuid AND state IN ('queued','running','recovering') ORDER BY (state <> 'running'), sequence LIMIT 1`, [binding.worktree_id]);+ const [holdRow] = await engine.executeRaw<HoldRow>(`SELECT (completed_keys->0->>'count')::int AS count, (completed_keys->0->>'stalled')::int AS stalled,+ (completed_keys->0->>'fences')::int AS fences, (completed_keys->0->>'concurrent')::int AS concurrent, updated_at+ FROM op_checkpoints WHERE op='sync-hold-summary' AND completed_keys->0->>'source_id'=$1 AND completed_keys->0->>'incarnation'=$2 LIMIT 1`, [binding.source_id, binding.source_incarnation]);+ const claim = headRow ? claimStateOf({ state: headRow.state, claim_phase: headRow.claim_phase, execution_token: headRow.execution_token, claim_lapsed: headRow.claim_lapsed, publication_started: headRow.publication_started }, now) : null;+ const stampSince = (() => {+ const raw = typeof headRow?.claim_phase === 'string' ? safeJson(headRow.claim_phase) : headRow?.claim_phase;+ const stamp = raw && typeof raw === 'object' ? raw as Record<string, unknown> : null;+ return stamp && headRow && stamp.token === headRow.execution_token ? iso(stamp.step_since ?? stamp.since) : null;+ })();+ const head: MovementHead | null = headRow ? { request_id: headRow.request_id, state: headRow.state, phase: claim?.phase ?? null, step: claim?.step ?? null, step_since: stampSince,+ step_age_ms: claim?.step_age_ms ?? null, waiting_on: claim?.waiting_on ?? null, owner: claim?.owner ?? null, last_sql: claim?.last_sql ?? null, lapsed: headRow.claim_lapsed === true } : null;+ const drain = await liveSyncStatus(engine, binding.source_id);+ const ownerHere = binding.owner_host_id === null ? null : binding.owner_host_id === host;+ const claimLive = !!claim && (claim.phase === 'preparing' || claim.phase === 'publishing');+ const consumer: SourceMovement['live']['consumer'] = claimLive ? 'claim' : ownerHere !== false && localConsumer ? 'local' : ownerHere !== false && await liveHeartbeat() ? 'heartbeat' : null;+ const cursor = backlog.get(binding.source_id) ?? null;+ const holds: MovementHolds = { count: Number(holdRow?.count ?? 0), stalled: Number(holdRow?.stalled ?? 0), fences: Number(holdRow?.fences ?? 0), concurrent: Number(holdRow?.concurrent ?? 0), last_hold_at: iso(holdRow?.updated_at) };+ const lastCommitAt = iso(mark?.last_commit_at);+ const admitted = Number(mark?.admitted ?? 0);+ const progressAt = newest(lastCommitAt, claimLive ? head?.step_since : null, cursor?.last_progress_at);+ const sampledAt = new Date(now).toISOString();+ const base = { source_id: binding.source_id, sampled_at: sampledAt, last_commit_at: lastCommitAt, last_progress_at: progressAt,+ cursor: cursor ? { index: cursor.index, total: cursor.total, remaining: cursor.remaining, held: cursor.held, last_progress_at: cursor.last_progress_at, resume_command: cursor.resume_command } : null,+ head, holds, admitted, live: { drain: !!drain, drain_pid: drain?.holder_pid ?? null, consumer }, ceiling_ms: policy.ceilingMs, owner_is_this_host: ownerHere,+ writer_status_command: writerStatusCommand(binding.source_id) };+ out.push({ ...base, ...verdict(base, now) });+ }+ return out;+}++function verdict(m: Omit<SourceMovement, 'movement_state' | 'data_moving' | 'not_moving_since'>, now: number): Pick<SourceMovement, 'movement_state' | 'data_moving' | 'not_moving_since'> {+ if (!m.cursor) return { movement_state: 'nothing_pending', data_moving: null, not_moving_since: null };+ const driving = m.live.drain || (m.admitted > 0 && m.live.consumer !== null);+ if (!driving) return { movement_state: 'parked', data_moving: null, not_moving_since: null };+ if (m.holds.last_hold_at && (!m.last_commit_at || m.holds.last_hold_at > m.last_commit_at) && m.last_progress_at && m.holds.last_hold_at >= m.last_progress_at) {+ return { movement_state: 'held', data_moving: true, not_moving_since: null };+ }+ const since = m.last_progress_at ? Date.parse(m.last_progress_at) : NaN;+ if (Number.isFinite(since) && now - since > m.ceiling_ms) return { movement_state: 'not_moving', data_moving: false, not_moving_since: m.last_progress_at };+ return { movement_state: 'moving', data_moving: true, not_moving_since: null };+}+function safeJson(text: string): unknown { try { return JSON.parse(text); } catch { return null; } }++/** One human line per source for `gbrain sources status`; null for a source with nothing pending. */+export function formatSourceMovement(m: SourceMovement): string | null {+ if (m.movement_state === 'nothing_pending') return null;+ const where = m.head?.step ? ` head at step ${m.head.step}${m.head.waiting_on && m.head.waiting_on !== 'unknown' ? ` (waiting on ${m.head.waiting_on})` : ''}${m.head.owner ? `, ${m.head.owner.kind} pid ${m.head.owner.pid}` : ''};` : '';+ switch (m.movement_state) {+ case 'not_moving': return `${m.source_id}: managed sync NOT MOVING since ${m.not_moving_since} (no committed page or step advance for longer than ${Math.round(m.ceiling_ms / 1000)}s while a ${m.live.drain ? 'sync' : 'consumer'} is live);${where} inspect: ${m.writer_status_command}`;+ case 'parked': return `${m.source_id}: managed sync parked at ${m.cursor!.index}/${m.cursor!.total} (no sync or consumer is live; informational). Resume: ${m.cursor!.resume_command}`;+ case 'held': return `${m.source_id}: managed sync advancing by holds only (${m.holds.count} held, newest ${m.holds.last_hold_at}); the containment is working, not a stall.`;+ default: return `${m.source_id}: managed sync moving (last progress ${m.last_progress_at ?? 'unknown'}, ${m.cursor!.remaining} remaining).`;+ }+}++/** The command's verdict over a window: what changed between two snapshots of one source. */+export type MovementVerdict = 'moved' | 'within_allowance' | 'held' | 'parked' | 'not_moving' | 'nothing_pending';+export function judgeMovement(before: SourceMovement | undefined, after: SourceMovement): MovementVerdict {+ if (after.movement_state === 'nothing_pending') return 'nothing_pending';+ if (!before) return after.movement_state === 'moving' ? 'moved' : after.movement_state;+ if (after.last_commit_at && (!before.last_commit_at || after.last_commit_at > before.last_commit_at)) return 'moved';+ if (after.holds.last_hold_at && (!before.holds.last_hold_at || after.holds.last_hold_at > before.holds.last_hold_at)) return 'held';+ if (after.movement_state === 'parked') return 'parked';+ const stepAdvanced = after.head?.step_since && (!before.head || before.head.request_id !== after.head.request_id || before.head.step_since !== after.head.step_since);+ if (stepAdvanced || (after.cursor && before.cursor && after.cursor.index > before.cursor.index)) return 'within_allowance';+ return 'not_moving';+}++export interface MovementWatch { stop(): void; tick(): Promise<void> }+/**+ * The serve's ticker: reads movement every `everyMs` and logs one notice when a source flips to `not_moving`+ * (and one recovery line when it moves again). Read failures are swallowed; the timer never keeps the process alive.+ */+export function startMovementWatch(engine: BrainEngine, opts: { log: (line: string) => void; everyMs?: number; setInterval?: typeof setInterval; clearInterval?: typeof clearInterval } ): MovementWatch {+ const flipped = new Set<string>();+ let inflight = false;+ const tick = async () => {+ if (inflight) return;+ inflight = true;+ try {+ for (const m of await readSourceMovement(engine)) {+ if (m.movement_state === 'not_moving' && !flipped.has(m.source_id)) {+ flipped.add(m.source_id);+ opts.log(`[gbrain notice managed_sync_not_moving kind=degraded] ${formatSourceMovement(m)}\nnext: run ${m.writer_status_command} (read-only) and act on the running claim's next_action.`);+ } else if (m.movement_state !== 'not_moving' && flipped.delete(m.source_id)) {+ opts.log(`[gbrain notice managed_sync_not_moving kind=info] ${m.source_id}: managed sync data is moving again (${m.movement_state}).`);+ }+ }+ } catch { /* a diagnostic read never disturbs the serve */ } finally { inflight = false; }+ };+ const every = opts.everyMs ?? MOVEMENT_WATCH_MS;+ const timer = (opts.setInterval ?? setInterval)(() => { void tick(); }, every);+ (timer as { unref?: () => void }).unref?.();+ return { tick, stop: () => { (opts.clearInterval ?? clearInterval)(timer); } };+}diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 67bc112862..186d89ea1e 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1794,6 +1794,18 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#managed-sync-not-moving",+ "parked": 0,+ "sources": []+ },+ "message": "No managed sync is pending.",+ "name": "managed_sync_not_moving",+ "status": "ok"+ },{"category": "ops","message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 9816694ecb..3aee99d387 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1871,6 +1871,18 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#managed-sync-not-moving",+ "parked": 0,+ "sources": []+ },+ "message": "No managed sync is pending.",+ "name": "managed_sync_not_moving",+ "status": "ok"+ },{"category": "ops","message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 12c25cb20b..070539d6e7 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -705,6 +705,10 @@"category": "brain","name": "fence_integrity"},+ {+ "category": "ops",+ "name": "managed_sync_not_moving"+ },{"category": "ops","name": "search_mode"diff --git a/test/sync-drain-claims.test.ts b/test/sync-drain-claims.test.tsindex 3c1cd621b7..df8ffe58b1 100644--- a/test/sync-drain-claims.test.ts+++ b/test/sync-drain-claims.test.ts@@ -108,7 +108,7 @@ describe('claim-aware no-progress window', () => {expect(drainJsonFields(result, RESUME, 's')).toMatchObject({ outcome: 'blocked', next: { fix: { next: 'tell_user_to_run' } } });});- test('an owner whose heartbeat row is wedged stops the drain before the ceiling with retry_after_ms to it and fix.next wait (safe to loop)', async () => {+ test('an owner whose heartbeat row is wedged stops the drain before the ceiling with retry_after_ms to it and a rerunnable fix (safe to loop)', async () => {const owner = async () => ({ kind: 'serve', pid: process.pid + 1, nonce: 'other-nonce', mode: 'full', live: true, restart_required: true, root_barrier_age_ms: null });const result = await runDrain({ pass: async () => pending(2), probe: probeWith(claim({ step_age_ms: 160_000, claim_age_ms: 200_000, ...other }), 'same', { owner }), pauseMs: 1, stallMs: 20 });expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'owner_wedged_here', past_ceiling: false, owner_row: { restart_required: true } } });@@ -116,7 +116,9 @@ describe('claim-aware no-progress window', () => {expect(result.drain!.retry_after_ms).toBeLessThanOrEqual(400_000);const next = drainNext(result, RESUME, 's')!;expect(next).toMatchObject({ safe_to_loop: true, command: RESUME, cause: 'owner_wedged_here' });- expect(next.fix).toMatchObject({ next: 'wait', actor: 'provider' });+ // `wait` derives only from a provider actor (agent-output.ts deriveNext); a wedged owner is not one, so the agent reruns after retry_after_ms.+ expect(next.fix).toMatchObject({ next: 'run', actor: 'agent', command: RESUME });+ expect(next.fix!.verify?.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', 's', '--json']);expect(next.why).toContain('reports restart_required');// A live, healthy row keeps the drain running.let passes = 0;