Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/capy/6317-reliability-contract (lanes 1, 3, 4 + master v0.60.114.0) into capy/6317-lane-2: lane 1's heartbeat module replaces the stub, pool numbers wired into the heartbeat row, pooler check folded into persistence_session_timeouts

garrytan3048aa8d7042
diff --cc scripts/module-size-limits.tsv
index 992a3665f9,68ec1bf115..c9360d1a7e
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -21,7 -21,7 +21,7 @@@ src/core/import-file.ts 2202 ratchet +2
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row
src/core/pglite-engine.ts 2998 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move)
- src/core/postgres-engine.ts 2956 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +2 #6317: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts); +1 #6317: getPoolDiagnostics().prepare (the pooler-mode mark the doctor check reads)
-src/core/postgres-engine.ts 2976 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed
++src/core/postgres-engine.ts 2979 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark
src/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts
src/core/types.ts 2239 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --cc src/commands/doctor/registry.ts
index 430336594a,7d8fc86cb9..cadb021ed2
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@@ -100,8 -101,6 +101,7 @@@ import { agentContractEntry } from './c
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 { persistencePoolerEntry } from './checks/persistence-pooler.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
import type { Check } from '../doctor.ts';
import { infoCheck } from './check-fix.ts';
@@@ -178,8 -177,7 +178,8 @@@ export const DOCTOR_CHECK_REGISTRY: rea
revisionBackfillEntry,
coreMemoryEntry,
fenceIntegrityEntry,
+ managedSyncMovementEntry,
- persistencePoolerEntry,
+ persistenceConsumersEntry,
searchModeEntry,
];
diff --cc src/core/cli-flag-registry.generated.ts
index 60269e1cf1,bfd7d368ed..053998dcd6
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@@ -47,7 -47,7 +47,7 @@@ export const CLI_FLAG_REGISTRY: Record<
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
++ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--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', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@@ -79,7 -79,7 +79,7 @@@
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
-- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-capture', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
++ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--full', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
diff --cc src/core/doctor-categories.ts
index 3ed2a11a54,7150197be3..fb3a58d4e7
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@@ -248,9 -248,11 +248,12 @@@ export const OPS_CHECK_NAMES: ReadonlyS
'persistence_request_growth',
'persistence_request_indexes',
'persistence_write_stall',
+ 'managed_sync_not_moving',
- 'persistence_pooler_transaction_mode',
'persistence_session_timeouts',
+ // #6317: consumer heartbeat rows and host identity (doctor/checks/persistence-consumers.ts).
+ 'two_consumers_on_host',
+ 'consumers_without_heartbeat',
+ 'host_identity_mismatch',
'stale_embedding_effects',
'vector_plan',
'writer_version',
diff --cc src/core/persistence/administration.ts
index 42296a7d66,6503390b45..773c6bfa06
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@@ -228,9 -228,9 +228,11 @@@ export async function runPersistenceAdm
host_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 } : {}),
+ // #6317 (B3): every process holding a consumer on this host, from the heartbeat rows (kind, pid, nonce, mode, age, wedge report).
+ host: { host_id: existingLocalHostId(), ...await (await import('./consumer-diagnostics.ts')).hostConsumersReport(engine, existingLocalHostId()) },
- 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 --cc src/core/persistence/claim-phase.ts
index 38788b9a00,d29660ac85..97a0cc93dd
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@@ -67,13 -58,12 +67,16 @@@ export interface ClaimPhaseClock
* Absent with the deadlines switch off.
*/
deadlineAt?: number;
+ /** #6317: the last raw statement the preparation issued (label only) and when. */
+ lastSql?: { label: string; at: number };
}
- /** The process that holds a claim, as the stamp records it (`nonce`/`pid_ns` absent on stamps from an owner older than #6317). */
+ /**
+ * The process that holds a claim, as the stamp records it. #6317: `nonce` (random per process) and `pid_ns` (the pid
+ * namespace where readable) tell a reused pid or another container's pid from this process; an older owner stamps neither.
+ */
export interface ClaimOwner { kind: string; pid: number; version: string; nonce?: string; pid_ns?: string | null }
+/** #6317: the step / waiting_on / last_sql triple of a claim, as stamped and as read back. */
+export interface ClaimLastSql { label: string; age_ms: number | null }
export function startClaimPhase(now = Date.now(), signal?: AbortSignal, budgetMs?: number): ClaimPhaseClock {
return { phase: 'preparing', claimedAt: now, since: now, step: null, stepSince: now, waitingOn: 'unknown', ...(signal ? { signal } : {}),
@@@ -100,28 -90,6 +103,27 @@@ export function enterClaimStep(clock: C
if (clock.step !== step) { clock.step = step; clock.stepSince = now; }
clock.waitingOn = waitingOn;
}
+/** #6317: the label of a raw statement for the stamp: its first keyword and the first table it names; never text or parameters. */
+export function sqlLabel(sql: string): string {
+ const text = sql.replace(/\s+/g, ' ').trim();
+ const keyword = /^[A-Za-z]+/.exec(text)?.[0]?.toUpperCase() ?? 'SQL';
+ const table = /\b(?:FROM|INTO|UPDATE|JOIN)\s+(?:ONLY\s+)?("?[A-Za-z_][\w.]*"?)/i.exec(text)?.[1]?.replaceAll('"', '');
+ return table ? `${keyword} ${table}` : keyword;
+}
+/** #6317: records the statement a preparer is about to issue on its clock (`boundedReads` calls it at every raw read). */
+export function recordClaimSql(clock: ClaimPhaseClock | undefined, sql: string, now = Date.now()): void {
+ if (clock) clock.lastSql = { label: sqlLabel(sql), at: now };
+}
+/** #6317: the ` step=… waiting_on=… last_sql=…` text every `[persistence]` cut-off and hold line carries (C3). */
+export function claimTripleText(clock: Pick<ClaimPhaseClock, 'step' | 'waitingOn' | 'lastSql'> | undefined, now = Date.now()): string {
+ if (!clock) return ' step=none waiting_on=unknown last_sql=none';
+ const last = clock.lastSql ? `${clock.lastSql.label.replaceAll(' ', '_')}@${Math.round((now - clock.lastSql.at) / 1000)}s` : 'none';
+ return ` step=${clock.step ?? 'none'} waiting_on=${clock.waitingOn} last_sql=${last}`;
+}
+/** #6317: whether a stamped owner is this process: the pid, and the nonce when the stamp carries one (a reused pid is another process). */
+export function isOwnerThisProcess(owner: Pick<ClaimOwner, 'pid' | 'nonce'> | null | undefined): boolean {
- if (!owner || owner.pid !== process.pid) return false;
- return owner.nonce === undefined || owner.nonce === consumerIdentity().nonce;
++ return claimOwnerIsThisProcess(owner);
+}
const OWNER_COMMANDS = new Set(['sync', 'serve', 'jobs', 'autopilot', 'mcp', 'dream', 'cycle', 'sources', 'migrate-graduation', 'put', 'import']);
let ownerOverride: ClaimOwner | undefined;
diff --cc src/core/persistence/consumer.ts
index e85361f631,0b059c8c16..081a745d55
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@@ -689,8 -763,8 +763,8 @@@ export class PersistenceConsumer implem
this.zombies.set(row.id, { request_id: row.request_id, operation: row.operation, step: clock.step, waiting_on: clock.waitingOn,
claimed_at: new Date(clock.claimedAt).toISOString(), abandoned_at: at, outlived_ceiling_at: at });
void settled.then(() => { this.zombies.delete(row.id); });
- this.log('preparation', 'ceiling_exceeded', `request ${row.request_id} step=${clock.step ?? 'none'} waiting_on=${clock.waitingOn}${this.restartRequired() ? ' restart_required' : ''}`);
+ this.log('preparation', 'ceiling_exceeded', `request ${row.request_id}${claimTripleText(clock)}${this.restartRequired() ? ' restart_required' : ''}`);
- await floorPreparationAttempts(this.engine, row.id, this.policy.maxAttempts).catch(error => this.report(error));
+ await floorPreparationAttempts(this.statements, row.id, this.policy.maxAttempts).catch(error => this.report(error));
});
}
private async execute(row: WriteRequest, root: RootHold): Promise<boolean> {
@@@ -734,14 -808,14 +808,14 @@@
// The budget passed (on the timer, or reported by a bounded read the server ended): the claim is released now, charged,
// whether or not the preparer settles; its late result never publishes (#6278).
const deadline = async (): Promise<boolean> => {
- root.until = this.abandonedRootBlock(row, clock, this.keepAbandoned(prep.work));
- if (!lease.held || this.stopping) { await releaseUnpublishedClaim(this.engine, row, releaseReason()); return false; }
+ root.until = this.abandonedRootBlock(row, clock, this.keepAbandoned(prep.work, clock.claimedAt));
+ if (!lease.held || this.stopping) { await releaseUnpublishedClaim(this.statements, row, releaseReason()); return false; }
if ((row.preparation_attempts ?? 0) + 1 >= policy.maxAttempts) {
const done = await finishPreparationStalled(this.engine, row, stallInfo(), true);
- this.log('preparation', 'preparation_stalled', failureLogText(done));
+ this.log('preparation', 'preparation_stalled', `${failureLogText(done)}${claimTripleText(clock)}`);
return this.settled(done);
}
- await releaseUnpublishedClaim(this.engine, row, 'preparation_deadline', { charge: true });
+ await releaseUnpublishedClaim(this.statements, row, 'preparation_deadline', { charge: true });
return false;
};
try {
diff --cc src/core/persistence/diagnostics.ts
index b96f2cf9c7,d94fdc0cab..45b542ac97
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@@ -4,10 -4,7 +4,10 @@@ import type { JournalLimits } from './m
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, sqlLabel, 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 { listHostConsumers, type ListedConsumer } from './consumer-heartbeat.ts';
import type { WriteRequestState } from './types.ts';
import { preparationBudgetMs } from './preparation-budget.ts';
import { readWriteSwitchSnapshot } from './switches.ts';
@@@ -38,81 -35,6 +38,81 @@@ export const WRITER_NEXT_ACTIONS: Recor
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` envelope (`claim.next`: code, why, retry_after_ms, fix) 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 {
++ owner: { row: ListedConsumer | 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 (reporter ask 3): the owner process's database backends from `pg_stat_activity`, matched on the `application_name`
+ * every gbrain pool starts its connections with (`gbrain <kind>:<pid>:<nonce8>`, db.ts), so a round-trip that never
+ * returns (backend `active`, `wait_event` ClientRead, an old transaction) is visible in one command. Statement text never
+ * leaves: only its label (first keyword plus table). Through a transaction-mode pooler the server connection is shared
+ * and carries the pooler's own name or another client's, so the mapping is partial (`backend_visibility: 'pooled'`).
+ */
+export interface OwnerBackend { pid: number; state: string | null; wait_event_type: string | null; wait_event: string | null; statement: string | null;
+ query_age_ms: number | null; xact_age_ms: number | null; state_age_ms: number | null; application_name: string }
+export type BackendVisibility = 'session' | 'pooled' | 'unavailable';
+export async function readOwnerBackends(engine: BrainEngine, owners: Array<Pick<ClaimState['owner'] & object, 'kind' | 'pid' | 'nonce'>>): Promise<{ visibility: BackendVisibility; byOwner: Map<string, OwnerBackend[]> }> {
+ const byOwner = new Map<string, OwnerBackend[]>();
+ if (engine.kind !== 'postgres' || !owners.length) return { visibility: 'unavailable', byOwner };
+ const diagnostics = (engine as { getPoolDiagnostics?: () => { prepare?: boolean | null } | null }).getPoolDiagnostics?.();
+ const visibility: BackendVisibility = diagnostics?.prepare === false ? 'pooled' : 'session';
+ const names = owners.map(owner => `gbrain ${owner.kind}:${owner.pid}:${(owner.nonce ?? '').slice(0, 8)}`);
+ try {
+ const rows = await engine.executeRaw<{ pid: number; state: string | null; wait_event_type: string | null; wait_event: string | null; query: string | null;
+ query_age_ms: string | number | null; xact_age_ms: string | number | null; state_age_ms: string | number | null; application_name: string }>(
+ `SELECT pid, state, wait_event_type, wait_event, left(query, 300) AS query, application_name,
+ (EXTRACT(EPOCH FROM (now() - query_start)) * 1000)::bigint AS query_age_ms,
+ (EXTRACT(EPOCH FROM (now() - xact_start)) * 1000)::bigint AS xact_age_ms,
+ (EXTRACT(EPOCH FROM (now() - state_change)) * 1000)::bigint AS state_age_ms
+ FROM pg_stat_activity WHERE datname = current_database() AND backend_type = 'client backend' AND application_name = ANY($1::text[]) ORDER BY pid`,
+ [names], { timeoutMs: 2_000 });
+ for (const row of rows) {
+ const list = byOwner.get(row.application_name) ?? [];
+ list.push({ pid: Number(row.pid), state: row.state, wait_event_type: row.wait_event_type, wait_event: row.wait_event, statement: row.query ? sqlLabel(row.query) : null,
+ query_age_ms: row.query_age_ms === null ? null : Number(row.query_age_ms), xact_age_ms: row.xact_age_ms === null ? null : Number(row.xact_age_ms),
+ state_age_ms: row.state_age_ms === null ? null : Number(row.state_age_ms), application_name: row.application_name });
+ byOwner.set(row.application_name, list);
+ }
+ return { visibility, byOwner };
+ } catch {
+ return { visibility: 'unavailable', byOwner };
+ }
+}
+/** #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 } {
++function claimPool(engine: BrainEngine, claim: ClaimState, row: ListedConsumer | 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) {
@@@ -170,13 -92,6 +170,13 @@@ export async function readWriterDiagnos
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 consumerRows = hostId ? await listHostConsumers(engine, hostId).catch(() => []) : [];
+ const tracked = (engine as { getPoolDiagnostics?: () => { tracked?: unknown } | null }).getPoolDiagnostics?.()?.tracked ?? null;
+ const claimStates = blockers.map(row => claimStateOf({ state: row.state, claim_phase: row.claim_phase, execution_token: row.execution_token, claim_lapsed: row.claim_lapsed, publication_started: row.publication_started }));
+ const backends = await readOwnerBackends(engine, claimStates.flatMap(state => state?.owner ? [state.owner] : []));
// 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'
@@@ -191,17 -105,10 +191,17 @@@
const advice = writerNextAction(row.blocked_reason ?? row.error_code);
// #6176: a running request names the phase its claim is in and how long it has held it; #6278: its step, wait cause, owner
// process and, past its budget, the `preparation_overdue` verdict (the running state; `preparation_stalled` is only the terminal give-up).
- const state = claimStateOf({ state: row.state, claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started });
+ const state = claimStates[index] ?? null;
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 ownerBackends = state?.owner ? backends.byOwner.get(`gbrain ${state.owner.kind}:${state.owner.pid}:${(state.owner.nonce ?? '').slice(0, 8)}`) ?? [] : [];
+ const claim = state ? { ...state, ...(state.owner ? { owner: { ...state.owner, backend: ownerBackends, backend_visibility: backends.visibility } } : {}),
+ ...(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: claimNextAction(state, stall, { budgetMs: budget, ceilingMs }, row.source_id, { row: ownerRow, live: ownerRow ? consumerLive(ownerRow) : null }) } : undefined;
++ owner_live: ownerRow ? ownerRow.liveness === 'live' : null, owner_mode: ownerRow?.mode ?? null,
++ next: claimNextAction(state, stall, { budgetMs: budget, ceilingMs }, row.source_id, { row: ownerRow, live: ownerRow ? ownerRow.liveness === 'live' : 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 --cc src/core/persistence/service.ts
index 332f9ddce1,c5e2add7a9..3e524a2769
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@@ -1,7 -1,10 +1,11 @@@
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { OperationError } from '../ops/contract.ts';
- import { LANE_BUSY, PersistenceConsumer, type PrepareMutation } from './consumer.ts';
+ import { LANE_BUSY, PersistenceConsumer, type PersistenceConsumerLike, type PrepareMutation } from './consumer.ts';
+ import { WaiterOnlyConsumer, type ElectedOwner } from './consumer-election.ts';
+ import { RESIDENT_CONSUMER_KINDS, startConsumerHeartbeat, type ConsumerHeartbeat } from './consumer-heartbeat.ts';
++import { enginePoolStats } from '../postgres-engine/pool-stats.ts';
+ import { claimOwnerKind } from './claim-phase.ts';
import { preparePageMutation } from './page-prepare.ts';
import { prepareSemanticPageMutation } from './semantic-pages.ts';
import { getWriteRequestById, getWriteRequestProgress, receiptFor, type WriteRequestProgress } from './journal.ts';
@@@ -94,9 -104,14 +105,15 @@@ export function startPersistenceConsume
}
return prior.consumer;
}
- const consumer = new PersistenceConsumer(engine, config, preparePersistedMutation,
+ const full = () => new PersistenceConsumer(engine, config, preparePersistedMutation,
{ onSettled: row => { recordSettlement(engine); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });
- const service: Service = { consumer, stopping: false };
+ const kind = claimOwnerKind();
+ const service: Service = kind !== 'serve' && RESIDENT_CONSUMER_KINDS.includes(kind) && engine.kind === 'postgres'
- ? { consumer: new WaiterOnlyConsumer(engine, config, full, { kind, hostId: localHostId() }), stopping: false }
++ ? { consumer: new WaiterOnlyConsumer(engine, config, full, { kind, hostId: localHostId(), pool: () => enginePoolStats(engine) }), stopping: false }
+ : (() => { const consumer = full(); return { consumer, stopping: false, heartbeat: startConsumerHeartbeat(engine, consumer.hostId,
- { kind, mode: 'full', report: () => ({ restart_required: consumer.restartRequired(), root_barrier_age_ms: consumer.oldestRootBarrierAgeMs() }) }) }; })();
++ // #6317 (C1): the row's pool numbers come from the vendored driver's own queues (postgres-engine/pool-stats.ts).
++ { kind, mode: 'full', report: () => ({ restart_required: consumer.restartRequired(), root_barrier_age_ms: consumer.oldestRootBarrierAgeMs(), pool: enginePoolStats(engine) }) }) }; })();
+ const { consumer } = service;
services.set(engine, service);
const lifecycle = engine as BrainEngine & { registerBeforeDisconnect?: (run: () => Promise<void>) => unknown };
const unregister = lifecycle.registerBeforeDisconnect?.(() => stopPersistenceConsumer(engine));
diff --cc src/core/persistence/sync-drain.ts
index 0c0dabad76,29345b8260..6fd3516365
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@@ -526,22 -455,6 +526,22 @@@ export function engineStallProbe(engine
return { key: [row.state, row.blocked_reason, row.head_id, row.head_state, claim?.phase ?? '', claim?.step ?? '', stamp?.since ?? '', row.head_lapsed ? 'lapsed' : ''].join('|'),
stall: await describe(found.requestId, row), claim };
},
+ // #6317: the owner's heartbeat row by pid (and nonce when both sides have one); a consumer here that could reclaim a lapsed head.
+ async owner(claim) {
+ if (claim.owner_pid === null) return null;
+ const { localHostId } = await import('./identity.ts');
- const { listHostConsumers, consumerLive } = await import('./consumer-heartbeat.ts');
- const rows = await listHostConsumers(engine, localHostId());
++ const { listHostConsumers } = await import('./consumer-heartbeat.ts');
++ const rows = await listHostConsumers(engine, localHostId()).catch(() => []);
+ const row = rows.find(r => r.pid === claim.owner_pid && (claim.owner_nonce === null || r.nonce === claim.owner_nonce));
- return row ? { kind: row.kind, pid: row.pid, nonce: row.nonce, mode: row.mode, live: consumerLive(row), restart_required: row.restart_required, root_barrier_age_ms: row.root_barrier_age_ms } : null;
++ return row ? { kind: row.kind, pid: row.pid, nonce: row.nonce, mode: row.mode, live: row.liveness === 'live', restart_required: row.restart_required, root_barrier_age_ms: row.root_barrier_age_ms } : null;
+ },
+ async reclaimableHere() {
+ const { persistenceConsumerStatus } = await import('./service.ts');
+ if (persistenceConsumerStatus(engine).state === 'open') return true;
+ const { localHostId } = await import('./identity.ts');
- const { listHostConsumers, consumerLive } = await import('./consumer-heartbeat.ts');
- return (await listHostConsumers(engine, localHostId())).some(row => (row.mode === 'full' || row.mode === 'promoted') && consumerLive(row));
++ const { listHostConsumers } = await import('./consumer-heartbeat.ts');
++ return (await listHostConsumers(engine, localHostId()).catch(() => [])).some(row => (row.mode === 'full' || row.mode === 'promoted') && row.liveness === 'live');
+ },
...(sourceId ? { async head() {
const [row] = await engine.executeRaw<{ head_state: string; head_claim_phase: unknown; head_token: string | null; head_lapsed: boolean | null; head_kind: string | null }>(
`SELECT h.state AS head_state, h.claim_phase AS head_claim_phase, h.execution_token::text AS head_token,
diff --cc src/core/persistence/sync-movement.ts
index e72ff1a0a2,0000000000..9dfe61eba2
mode 100644,000000..100644
--- a/src/core/persistence/sync-movement.ts
+++ b/src/core/persistence/sync-movement.ts
@@@ -1,211 -1,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';
++import { 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 liveHeartbeat = () => heartbeat ??= listHostConsumers(engine, host).then(rows => rows.some(row => (row.mode === 'full' || row.mode === 'promoted') && row.liveness === 'live'), () => false);
+ 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 step.`);
+ } 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 --cc test/fixtures/goldens/doctor/json-postgres-fresh.json
index 3d2c07726f,aca0db8d7e..96bf809629
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@@ -502,7 -502,7 +502,7 @@@
},
{
"category": "ops",
-- "message": "RLS enabled on 120/120 public tables",
++ "message": "RLS enabled on 121/121 public tables",
"name": "rls",
"status": "ok"
},
@@@ -514,7 -514,7 +514,7 @@@
},
{
"category": "meta",
-- "message": "992 column(s) verified against live schema",
++ "message": "1007 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
@@@ -1861,31 -1861,6 +1861,54 @@@
"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",
+ "details": {
- "direct_host": null,
- "docs": "docs/guides/troubleshooting.md#persistence-pooler-transaction-mode",
- "pool_max": 10,
- "pool_mode": "single (non-supabase)",
- "prepare": true
++ "consumers": [],
++ "count": 0,
++ "docs": "docs/guides/troubleshooting.md#two-consumers-on-host",
++ "min_age_ms": "<volatile>"
++ },
++ "message": "No persistence consumer is running on this host.",
++ "name": "two_consumers_on_host",
++ "status": "ok"
++ },
++ {
++ "category": "ops",
++ "details": {
++ "count": 0,
++ "docs": "docs/guides/troubleshooting.md#two-consumers-on-host",
++ "owners": []
++ },
++ "message": "Every owner of a live running claim on this host has a consumer heartbeat row.",
++ "name": "consumers_without_heartbeat",
++ "status": "ok"
++ },
++ {
++ "category": "ops",
++ "details": {
++ "count": 0,
++ "docs": "docs/guides/troubleshooting.md#host-identity-mismatch",
++ "host_id": "<uuid>",
++ "host_json_path": "<home>/.gbrain/persistence/host.json",
++ "mismatches": []
+ },
- "message": "The ordinary pool runs with prepared statements (a session-mode pooler or a direct connection).",
- "name": "persistence_pooler_transaction_mode",
++ "message": "This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.",
++ "name": "host_identity_mismatch",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --cc test/fixtures/goldens/doctor/registry-build-checks.json
index 32614cff85,ac0e22ded9..4e7b7bcf66
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@@ -705,13 -705,17 +705,21 @@@
"category": "brain",
"name": "fence_integrity"
},
+ {
+ "category": "ops",
+ "name": "managed_sync_not_moving"
+ },
{
"category": "ops",
- "name": "persistence_pooler_transaction_mode"
+ "name": "two_consumers_on_host"
+ },
+ {
+ "category": "ops",
+ "name": "consumers_without_heartbeat"
+ },
+ {
+ "category": "ops",
+ "name": "host_identity_mismatch"
},
{
"category": "ops",
diff --cc test/writer-status-owner-backends.test.ts
index 557ede94bf,0000000000..fc7588abac
mode 100644,000000..100644
--- a/test/writer-status-owner-backends.test.ts
+++ b/test/writer-status-owner-backends.test.ts
@@@ -1,160 -1,0 +1,144 @@@
+/**
+ * #6317 (C1, reporter ask 3): `writer status --json` shows, per running
+ * claim, the owner process's database backends from `pg_stat_activity`,
+ * matched on the `application_name` every gbrain pool starts its connections
+ * with (`gbrain <kind>:<pid>:<nonce8>`), with the statement label, ages,
+ * state and wait event, and says how far the mapping can be trusted
+ * (`backend_visibility`: session, pooled, unavailable). The running claim also
+ * ends with one `next` envelope, carries `last_sql` from the stamp and the
+ * pool numbers from the vendored driver when this process owns the claim.
- * The doctor check `persistence_pooler_transaction_mode` fires from the
- * engine's own `prepare: false` mark (the port-6543 convention), never a probe.
+ *
+ * PGLite: the fields exist and read `unavailable`/empty. Postgres
+ * (DATABASE_URL): this process's own connection appears under its name.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { readWriterDiagnostics, readOwnerBackends, claimNextAction } from '../src/core/persistence/diagnostics.ts';
+import { claimOwner, claimPhaseStamp, startClaimPhase, recordClaimSql, sqlLabel, claimTripleText, isOwnerThisProcess, claimStateOf } from '../src/core/persistence/claim-phase.ts';
+import { boundedReads } from '../src/core/persistence/bounded-reads.ts';
+import { consumerIdentity } from '../src/core/persistence/consumer-heartbeat.ts';
+import { gbrainApplicationName } from '../src/core/db.ts';
+import { driverPoolStats } from '../src/core/postgres-engine/pool-stats.ts';
- import { persistencePoolerEntry } from '../src/commands/doctor/checks/persistence-pooler.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const engines: Array<{ engine: BrainEngine; close?: () => Promise<void> }> = [];
+beforeAll(async () => {
+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push({ engine: lite }); }
+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push({ engine: pg.engine, close: pg.close }); }
+}, 120_000);
+afterAll(async () => { for (const e of engines) { if (e.close) await e.close(); else await e.engine.disconnect(); } });
+
+async function runningClaim(engine: BrainEngine, stamp: string): Promise<string> {
+ const id = `wb-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, `/tmp/${id}`]);
+ const [wt] = await engine.executeRaw<{ id: string }>('INSERT INTO persistence_worktrees(owner_host_id) VALUES(gen_random_uuid()) RETURNING id::text AS id');
+ const [src] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ const token = JSON.parse(stamp).token as string, requestId = randomUUID();
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,worktree_id,digest,authority,intent,intent_bytes,terminal_reservation,
+ state,execution_token,claim_expires_at,claim_phase)
+ VALUES('local_cli','cli:example',$1::uuid,'submit_job',$2,$3::uuid,'notes/p',$4::uuid,'d','{}'::jsonb,'{"kind":"managed_sync_import","path":"notes/p.md"}'::jsonb,1,16384,'running',$5::uuid,now()+interval '30 seconds',$6::text::jsonb)`,
+ [requestId, id, src!.incarnation, wt!.id, token, stamp]);
+ return requestId;
+}
+
+describe('claim stamp identity and last_sql', () => {
+ test('the owner carries the nonce and pid namespace; the stamp carries last_sql; the triple text and the same-process check read them', () => {
+ const owner = claimOwner();
+ expect(owner).toMatchObject({ pid: process.pid, nonce: consumerIdentity().nonce });
+ expect(gbrainApplicationName()).toBe(`gbrain ${owner.kind}:${process.pid}:${owner.nonce!.slice(0, 8)}`);
+ expect(gbrainApplicationName().length).toBeLessThanOrEqual(63);
+ expect(sqlLabel('SELECT r.id FROM persistence_requests r WHERE ...')).toBe('SELECT persistence_requests');
+ expect(sqlLabel(' update "pages" set x=1')).toBe('UPDATE pages');
+ expect(sqlLabel('WITH expired AS (SELECT 1) UPDATE persistence_requests SET state=$1')).toBe('WITH persistence_requests');
+ expect(sqlLabel('SELECT 1')).toBe('SELECT');
+ const clock = startClaimPhase(1_000, undefined, 30_000);
+ recordClaimSql(clock, 'SELECT * FROM pages WHERE slug=$1', 5_000);
+ expect(clock.lastSql).toEqual({ label: 'SELECT pages', at: 5_000 });
+ expect(claimTripleText({ step: 'origin_check', waitingOn: 'db', lastSql: clock.lastSql }, 9_000)).toBe(' step=origin_check waiting_on=db last_sql=SELECT_pages@4s');
+ expect(claimTripleText(undefined)).toBe(' step=none waiting_on=unknown last_sql=none');
+ const state = claimStateOf({ state: 'running', claim_phase: claimPhaseStamp(clock, 'tok'), execution_token: 'tok' }, 9_000);
+ expect(state).toMatchObject({ phase: 'preparing', owner: { pid: process.pid, nonce: owner.nonce }, last_sql: { label: 'SELECT pages', age_ms: 4_000 } });
+ expect(isOwnerThisProcess({ pid: process.pid })).toBe(true);
+ expect(isOwnerThisProcess({ pid: process.pid, nonce: owner.nonce })).toBe(true);
+ expect(isOwnerThisProcess({ pid: process.pid, nonce: 'reused-pid-other-process' })).toBe(false);
+ expect(isOwnerThisProcess({ pid: process.pid + 1 })).toBe(false);
+ });
+
+ test('boundedReads records the statement label on the clock before issuing it (Postgres path with a deadline)', async () => {
+ const seen: string[] = [];
+ const fake = { kind: 'postgres', executeRaw: async (sql: string) => { seen.push(sql); return []; } } as unknown as BrainEngine;
+ const clock = startClaimPhase(Date.now(), undefined, 30_000);
+ await boundedReads(fake, clock).executeRaw('SELECT 1 FROM persistence_requests');
+ expect(seen).toHaveLength(1);
+ expect(clock.lastSql?.label).toBe('SELECT persistence_requests');
+ });
+
+ test('driverPoolStats reads the vendored driver\'s queues and reports null for a driver without the accessor', () => {
+ expect(driverPoolStats({ pool: { max: 10, open: 6, busy: 2, full: 1, reserved: 1, connecting: 0, closed: 0, ended: 0, queued: 3 } })).toEqual({ checked_out: 4, max: 10, waiters: 3 });
+ expect(driverPoolStats({})).toBeNull();
+ expect(driverPoolStats(null)).toBeNull();
+ });
+});
+
+describe('writer status running claims', () => {
+ test('owner.backend[], backend_visibility, next, last_sql and pool per engine', async () => {
+ for (const { engine } of engines) {
+ const clock = startClaimPhase(Date.now() - 20_000, undefined, 120_000);
+ recordClaimSql(clock, 'SELECT id FROM pages WHERE slug=$1', Date.now() - 3_000);
+ clock.step = 'import_screen'; clock.waitingOn = 'db';
+ const requestId = await runningClaim(engine, claimPhaseStamp(clock, randomUUID()));
+ const status = await readWriterDiagnostics(engine);
+ const blocker = (status.blockers as Array<Record<string, any>>).find(b => b.request_id === requestId)!;
+ expect(blocker).toBeDefined();
+ const claim = blocker.claim;
+ expect(claim).toMatchObject({ phase: 'preparing', step: 'import_screen', waiting_on: 'db', last_sql: { label: 'SELECT pages' }, owner: { pid: process.pid, nonce: consumerIdentity().nonce } });
+ expect(claim.next).toMatchObject({ code: 'claim_running', fix: { next: 'run', argv: ['gbrain', 'sources', 'writer', 'status', '--source', blocker.source_id, '--json'] } });
+ expect(claim.next.retry_after_ms).toBeGreaterThan(0);
+ expect(claim.next.why).toContain(`pid ${process.pid}`);
+ expect(typeof blocker.next_action).toBe('string');
+ if (engine.kind === 'postgres') {
+ expect(status.backend_visibility).toBe('session');
+ expect(claim.owner.backend_visibility).toBe('session');
+ // This process's own connection is one of the owner's backends: named, labelled, with a state and an age, never the SQL text.
+ const mine = claim.owner.backend as Array<Record<string, unknown>>;
+ expect(mine.length).toBeGreaterThanOrEqual(1);
+ expect(mine[0]!.application_name).toBe(gbrainApplicationName());
+ expect(mine.every(b => typeof b.pid === 'number' && typeof b.state === 'string')).toBe(true);
+ expect(mine.some(b => String(b.statement ?? '').startsWith('SELECT'))).toBe(true);
+ expect(JSON.stringify(mine)).not.toContain('pg_stat_activity WHERE');
+ expect(claim.pool).toMatchObject({ max: expect.any(Number), checked_out: expect.any(Number), waiters: expect.any(Number) });
+ expect(claim.pool_source).toBe('driver');
+ // An owner that is not this process has no backend here and no pool (no heartbeat row yet).
+ const other = await readOwnerBackends(engine, [{ kind: 'serve', pid: 999_999, nonce: 'nope' }]);
+ expect(other.visibility).toBe('session');
+ expect(other.byOwner.size).toBe(0);
+ } else {
+ expect(status.backend_visibility).toBe('unavailable');
+ expect(claim.owner.backend).toEqual([]);
+ expect(claim.pool).toBeNull();
+ }
+ }
+ }, 60_000);
+
+ test('next: past the ceiling or a wedged owner tells the host admin to restart the named pid; a lapsed claim resumes on its own', () => {
+ const base = claimStateOf({ state: 'running', claim_phase: claimPhaseStamp({ ...startClaimPhase(Date.now() - 700_000), step: 'raw_hash', waitingOn: 'pool' }, 't'), execution_token: 't' })!;
+ const overdue = claimNextAction(base, { reason: 'preparation_overdue', step: 'raw_hash', step_age_ms: 700_000, waiting_on: 'pool', budget_ms: 120_000 }, { budgetMs: 120_000, ceilingMs: 600_000 }, 's', { row: null, live: null });
+ expect(overdue).toMatchObject({ code: 'claim_overdue', retry_after_ms: 0, fix: { next: 'tell_user_to_run', actor: 'host_admin' } });
+ expect(overdue.fix.user_message).toContain(`pid ${process.pid}`);
+ expect(overdue.why).toContain('past the 600s ceiling');
+ const young = claimStateOf({ state: 'running', claim_phase: claimPhaseStamp({ ...startClaimPhase(Date.now() - 10_000), step: 'raw_hash', waitingOn: 'db' }, 't'), execution_token: 't' })!;
+ const wedged = claimNextAction(young, null, { budgetMs: 120_000, ceilingMs: 600_000 }, 's',
- { row: { host_id: 'h', pid: process.pid, nonce: 'n', pid_ns: null, kind: 'serve', mode: 'full', started_at: '', renewed_at: new Date().toISOString(), restart_required: true, root_barrier_age_ms: null, pool: null, host_json_path: null, persistence_home: null, minted_under: null, version: null }, live: true });
++ { row: { host_id: 'h', pid: process.pid, nonce: 'n', pid_ns: null, kind: 'serve', mode: 'full', started_at: '', renewed_at: new Date().toISOString(), restart_required: true, root_barrier_age_ms: null, pool: null, host_json_path: '/tmp/host.json', persistence_home: '/tmp', minted_under: null, version: 'test', renewed_age_ms: 0, age_ms: 0, liveness: 'live', self: false }, live: true });
+ expect(wedged).toMatchObject({ code: 'claim_overdue', fix: { next: 'tell_user_to_run' } });
+ expect(wedged.why).toContain('restart_required');
+ const running = claimNextAction(young, null, { budgetMs: 120_000, ceilingMs: 600_000 }, 's', { row: null, live: null });
+ expect(running).toMatchObject({ code: 'claim_running', fix: { next: 'run' } });
+ expect(running.retry_after_ms).toBeGreaterThan(100_000);
+ const lapsed = claimStateOf({ state: 'running', claim_phase: null, execution_token: 't', claim_lapsed: true })!;
+ expect(claimNextAction(lapsed, null, { budgetMs: null, ceilingMs: 600_000 }, null, { row: null, live: null })).toMatchObject({ code: 'claim_lapsed', retry_after_ms: null, fix: { next: 'run', argv: ['gbrain', 'sources', 'writer', 'status', '--json'] } });
+ });
+});
+
- describe('doctor persistence_pooler_transaction_mode', () => {
- const ctxFor = (engine: unknown) => ({ engine } as unknown as Parameters<typeof persistencePoolerEntry.run>[0]);
- test('fires from the engine\'s prepare:false mark with a host-admin fix; ok with prepared statements; not applicable on PGLite', async () => {
- const pooled = { kind: 'postgres', getPoolDiagnostics: () => ({ prepare: false, poolMax: 10 }), connectionManager: { describeMode: () => ({ mode: 'split', direct_host: 'db.example:5432' }) } };
- const [warn] = await persistencePoolerEntry.run(ctxFor(pooled)) as unknown as Array<Record<string, any>>;
- expect(warn).toMatchObject({ name: 'persistence_pooler_transaction_mode', status: 'warn', readiness_state: 'degraded', details: { prepare: false, pool_mode: 'split' },
- fix: { actor: 'host_admin', consent: [], argv: ['gbrain', 'sources', 'writer', 'status', '--json'], verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_pooler_transaction_mode', '--json'] } } });
- expect(warn!.message).toContain('ClientRead');
- const session = { kind: 'postgres', getPoolDiagnostics: () => ({ prepare: true, poolMax: 10 }) };
- expect((await persistencePoolerEntry.run(ctxFor(session)) as unknown as Array<Record<string, any>>)[0]).toMatchObject({ status: 'ok' });
- expect((await persistencePoolerEntry.run(ctxFor({ kind: 'pglite' })) as unknown as Array<Record<string, any>>)[0]).toMatchObject({ status: 'ok', readiness_state: 'not_applicable' });
- });
- });