Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(maintenance): shared 30 s publish wait, one wait per job; defer pending synthesis publishes (#5854)
garrytan7daf9ab137be
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex ca0131259e..0467f06d2a 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -34,14 +34,14 @@ src/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (src/core/context-engine.ts createGBrainContextEngine 519 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle.ts runCycle 1236 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder-src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 822 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes+src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 823 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker)src/core/cycle/extract-atoms.ts runPhaseExtractAtoms>withBudgetTracker(#1) 316 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +11 #5809/#5832: per-item and pre-commit abort checks, chat-call signal, abortable pacing, catch-side stopsrc/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/patterns.ts runPhasePatterns 303 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/propose-takes.ts ProposeTakesPhase.process 427 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 447 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1043 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)+src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1046 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phasesrc/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/import-file.ts importFromContent 857 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 377 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 7a8df14bb3..1ae5ee1b8f 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -14,8 +14,8 @@ src/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-src/core/ai/gateway.ts 4391 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge)src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)src/core/cycle.ts 3192 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set-src/core/cycle/synthesize.ts 3293 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option)-src/core/cycle/extract-atoms.ts 1834 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize+src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)+src/core/cycle/extract-atoms.ts 1844 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)src/core/engine.ts 2674 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance optionsrc/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.tsindex 1aaadf4cba..4e6a628d36 100644--- a/src/core/cycle/synthesize-postprocess.ts+++ b/src/core/cycle/synthesize-postprocess.ts@@ -8,6 +8,8 @@ import { getWriteRequest } from '../persistence/journal.ts';import type { WriteRequest } from '../persistence/model.ts';import { publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { writeResponse } from '../persistence/service.ts';+import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';+import type { PhaseResult } from '../cycle.ts';import type { DiscoveredTranscript } from './transcript-discovery.ts';import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPrior, verifyDreamPage, type GroundedSource, type GroundingPass } from './synthesize-verify.ts';@@ -26,7 +28,8 @@ export async function postprocessManagedSynthesis(const stats = emptyQuoteVerifyStats();const writtenRefs: OutputRef[] = [];const finalizedRefs: OutputRef[] = [];- if (!refs.length) return { writtenRefs, finalizedRefs, stats };+ let pending = 0;+ if (!refs.length) return { writtenRefs, finalizedRefs, stats, pending };const outputs = await engine.executeRaw<RetainedOutput>(`SELECT t.job_id,j.idempotency_key AS job_key,row_to_json(p) AS requestFROM subagent_tool_executions t JOIN minion_jobs j ON j.id=t.job_id@@ -89,10 +92,29 @@ export async function postprocessManagedSynthesis(content = serializePageToMarkdown(page, snapshot.tags);}throwIfAborted(opts.signal, '[dream] synthesis postprocessing');- await publishMaintenancePage(engine, authority, ref.slug, content, { requestId, expectedRevision: revision });+ try {+ await publishMaintenancePage(engine, authority, ref.slug, content, { requestId, expectedRevision: revision });+ } catch (error) {+ if (!acceptedPendingReceipt(error)) throw error;+ pending++;+ continue;+ }writtenRefs.push(finalizedRef);finalizedRefs.push(finalizedRef);await new Promise(resolve => setTimeout(resolve, 0));}- return { writtenRefs, finalizedRefs, stats };+ return { writtenRefs, finalizedRefs, stats, pending };+}++export const SYNTH_PUBLISH_DEFERRED = 'publish deferred (writer busy); finishes next cycle, no action needed';++/**+ * #5854: an output publish still pending after its wait is deferred, never+ * counted as written: the phase warns, the cooldown stays unstamped, and the+ * next cycle resumes the same request id.+ */+export function withPublishPending(pending: number, result: PhaseResult): PhaseResult {+ if (!pending) return result;+ return { ...result, status: 'warn', summary: `${result.summary}; ${SYNTH_PUBLISH_DEFERRED}`,+ details: { ...result.details, publish_pending: pending, publish_deferred: SYNTH_PUBLISH_DEFERRED } };}diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 6c15cdf18a..208d1bbca2 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -1,5 +1,6 @@import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';-import { postprocessManagedSynthesis } from './synthesize-postprocess.ts';+import { postprocessManagedSynthesis, withPublishPending } from './synthesize-postprocess.ts';+import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';/*** Synthesize phase (v0.23; #4152 two-stage cascade) — conversation-to-brain* pipeline. Cheap-model triage gates frontier-model synthesis:@@ -477,7 +478,7 @@ async function runPhaseSynthesizeInner();}- const maintenance = opts.dryRun ? null : await maintenancePreflight(engine, opts.sourceId ?? 'default', opts.brainDir);+ const maintenance = opts.dryRun ? null : await maintenancePreflight(engine, opts.sourceId ?? 'default', opts.brainDir, { deadlineAtMs: opts.deadlineAtMs });// v0.32.6 M2: pre-fetch prior contradictions from the most recent probe// run (if any). Surfaced as an informational block to the synthesize@@ -1143,6 +1144,7 @@ async function runPhaseSynthesizeInner(// chunks or the markdown body. Fail-open (abort still unwinds); kill// switch: dream.synthesize.quote_verify=false.let quoteVerifyStats: QuoteVerifyStats | null = null;+ let publishPending = 0;const sinceByTranscript = await loadChildWriteEpochs(engine, childIds, jobRawSource, verifySince);const grounding = config.quoteVerify ? await resolveGroundingDecide(engine) : undefined;if (maintenance) {@@ -1150,6 +1152,7 @@ async function runPhaseSynthesizeInner(worthProcessing, { cycleDate: summaryDate, quoteVerify: config.quoteVerify, sinceByTranscript, signal: opts.signal, grounding });writtenRefs = processed.writtenRefs;finalizedRefs = processed.finalizedRefs;+ publishPending = processed.pending;quoteVerifyStats = config.quoteVerify ? processed.stats : null;} else if (config.quoteVerify && writtenRefs.length > 0) {const transcriptsForVerify = new Map<string, TranscriptForVerify>(worthProcessing.map(t => [t.filePath, { content: t.content }]));@@ -1170,9 +1173,10 @@ async function runPhaseSynthesizeInner(const summarySlug = buildDreamSummarySlug(config.outputRoot, summaryDate);const writtenSlugs = writtenRefs.map(r => r.slug);- if (SUMMARY_SLUG_RE.test(summarySlug)) {+ if (SUMMARY_SLUG_RE.test(summarySlug) && !publishPending) {const preserveSummary = maintenance && !writtenRefs.length && await engine.readPageSnapshot(summarySlug, { sourceId: cycleSourceId });- if (!preserveSummary) await writeSummaryPage(engine, opts.brainDir, summarySlug, summaryDate, finalizedRefs.map(r => r.slug), childOutcomes, cycleSourceId, opts.signal, maintenance);+ if (!preserveSummary) await writeSummaryPage(engine, opts.brainDir, summarySlug, summaryDate, finalizedRefs.map(r => r.slug), childOutcomes, cycleSourceId, opts.signal, maintenance)+ .catch((e: unknown) => { if (!acceptedPendingReceipt(e)) throw e; publishPending++; });}// #4077: nothing below runs for a cancelled cycle — no phase-end embed@@ -1325,11 +1329,11 @@ async function runPhaseSynthesizeInner(// still-unknown keys) AND nothing was budget-deferred (#4168 adversarial:// "deferred transcripts retry next cycle" is a lie if the next cycle is// cooldown-skipped for half a day).- if (failedChildren.length === 0 && budgetExhaustedDeferrals.length === 0 && pass.deferred === 0) {+ if (failedChildren.length === 0 && budgetExhaustedDeferrals.length === 0 && pass.deferred === 0 && publishPending === 0) {await engine.setConfig('dream.synthesize.last_completion_ts', new Date().toISOString());} else {process.stderr.write(- `[dream] synthesize: ${failedChildren.length}/${childOutcomes.length} child job(s) incomplete + ${budgetExhaustedDeferrals.length} synthesis-budget deferred + ${pass.deferred} triage-deferred — cooldown NOT stamped so the next run retries them.\n`,+ `[dream] synthesize: ${failedChildren.length}/${childOutcomes.length} child job(s) incomplete + ${budgetExhaustedDeferrals.length} synthesis-budget deferred + ${pass.deferred} triage-deferred + ${publishPending} publish-deferred — cooldown NOT stamped so the next run retries them.\n`,);}@@ -1343,7 +1347,7 @@ async function runPhaseSynthesizeInner(const turnsSamples = childOutcomes.filter((o): o is { jobId: number; status: string; turns: number } => typeof o.turns === 'number',);- return ok(`${submittedTranscripts} transcript(s) synthesized in ${(ms / 1000).toFixed(1)}s${deferralSuffix}`, {+ return withPublishPending(publishPending, ok(`${submittedTranscripts} transcript(s) synthesized in ${(ms / 1000).toFixed(1)}s${deferralSuffix}`, {transcripts_discovered: transcripts.length,transcripts_processed: submittedTranscripts,pages_written: writtenSlugs.length,@@ -1409,7 +1413,7 @@ async function runPhaseSynthesizeInner(// child counters + triage pass usage). cost_usd null when unpriced.spend: spendBlock,},- });+ }));} catch (e) {return failed(makeError('InternalError', 'SYNTH_PHASE_FAIL',e instanceof Error ? (e.message || 'synthesize phase threw') : String(e)));diff --git a/src/core/persistence/maintenance-wait.ts b/src/core/persistence/maintenance-wait.tsnew file mode 100644index 0000000000..014aef6d4a--- /dev/null+++ b/src/core/persistence/maintenance-wait.ts@@ -0,0 +1,34 @@+/**+ * #5854: how long a maintenance publisher waits for its accepted write to+ * commit before the receipt reports `write_pending`. One budget per job:+ * every wait is `MAINTENANCE_WRITE_WAIT_MS`, capped by the job's remaining+ * deadline (no wait at or past it), and once one publish is still pending+ * after its wait the job's later publishes do not wait; they return+ * `write_pending` at once and are deferred like it. A pending write keeps its+ * request identity and commits later; it is never reported as committed.+ */+import { isTerminal, type WriteRequest } from './model.ts';++export const MAINTENANCE_WRITE_WAIT_MS = 30_000;++let testWaitMs: number | null = null;+/** Test seam: replace the 30 s base wait (null restores it). */+export function __setMaintenanceWriteWaitForTests(ms: number | null): void { testWaitMs = ms; }++export class MaintenanceWriteWait {+ private pending = false;+ constructor(private readonly deadlineAtMs: number | null = null, private readonly now: () => number = Date.now) {}++ /** The wait for the job's next publish. */+ ms(): number {+ if (this.pending) return 0;+ const base = testWaitMs ?? MAINTENANCE_WRITE_WAIT_MS;+ return this.deadlineAtMs == null ? base : Math.max(0, Math.min(base, this.deadlineAtMs - this.now()));+ }++ /** Record a publish after its wait; a row still pending stops the job's later waits. */+ observe(row: WriteRequest): WriteRequest {+ if (!isTerminal(row)) this.pending = true;+ return row;+ }+}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 2947d62d08..c951dc4f1a 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -20,10 +20,13 @@ import { authorizePageVisibility } from './page-visibility.ts';import { nativeLockCapability } from './native-lock.ts';import { assertPhysicalRoot } from './physical-root.ts';import { isConnectorSourceKind } from './connector-identity.ts';+import { MaintenanceWriteWait } from './maintenance-wait.ts';export interface MaintenanceAuthority {writer: WriteAuthority;binding: WorktreeBinding | null;+ /** #5854: the job's publish wait (one wait per job, bounded by its deadline); a fresh 30 s budget when absent. */+ wait?: MaintenanceWriteWait;}function maintenanceRequestId(value: unknown): string {@@ -31,7 +34,8 @@ function maintenanceRequestId(value: unknown): string {return `${key.slice(0, 8)}-${key.slice(8, 12)}-4${key.slice(13, 16)}-a${key.slice(17, 20)}-${key.slice(20, 32)}`;}-export async function maintenancePreflight(engine: BrainEngine, sourceId: string, root?: string): Promise<MaintenanceAuthority | null> {+export async function maintenancePreflight(engine: BrainEngine, sourceId: string, root?: string,+ opts: { deadlineAtMs?: number | null } = {}): Promise<MaintenanceAuthority | null> {if (!await managedPersistenceEnabled(engine)) return null;assertPersistenceAccepting(engine);const job = currentSubmissionAuthority();@@ -51,7 +55,7 @@ export async function maintenancePreflight(engine: BrainEngine, sourceId: string// (its local_path is the connector's state directory, not a canonical checkout).if (!binding && isConnectorSourceKind(source.kind)) {writer.databaseOnlyReason = 'connector_database';- return { writer, binding: null };+ return { writer, binding: null, wait: new MaintenanceWriteWait(opts.deadlineAtMs) };}const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');const configuredRoot = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);@@ -68,7 +72,7 @@ export async function maintenancePreflight(engine: BrainEngine, sourceId: string}if (!writeThrough) writer.databaseOnlyReason = 'disabled_by_config';else if (!binding) writer.databaseOnlyReason = 'no_repo_configured';- return { writer, binding: writeThrough ? binding : null };+ return { writer, binding: writeThrough ? binding : null, wait: new MaintenanceWriteWait(opts.deadlineAtMs) };}async function validateMaintenance(engine: BrainEngine, authority: MaintenanceAuthority, slug: string): Promise<void> {@@ -88,11 +92,12 @@ async function validateMaintenance(engine: BrainEngine, authority: MaintenanceAuasync function submitMaintenance(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,intent: Record<string, unknown>, requestId: string, file = true): Promise<Record<string, unknown>> {await validateMaintenance(engine, authority, slug);+ const wait = authority.wait ??= new MaintenanceWriteWait();const prior = await getWriteRequest(engine, authority.writer.principal, requestId);if (prior) {await authorizeStoredRequest(engine, prior);assertReplayIntent(prior, intentDigest({ operation: 'submit_job', sourceId: authority.writer.sourceId, slug, callerIntent: intent }));- return writeResponse(await waitForWrite(engine, prior, loadConfig() ?? { engine: engine.kind }));+ return writeResponse(wait.observe(await waitForWrite(engine, prior, loadConfig() ?? { engine: engine.kind }, wait.ms())));}const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId, includeDeleted: true });if (snapshot?.page.deleted_at) throw new OperationError('page_not_found', 'Maintenance cannot restore a deleted page.');@@ -101,7 +106,7 @@ async function submitMaintenance(engine: BrainEngine, authority: MaintenanceAuthsourceId: authority.writer.sourceId, sourceIncarnation: authority.writer.sourceIncarnation, slug,pageId: snapshot?.page.id ?? null, authority: authority.writer, callerIntent: intent, intent,worktreeId: file ? authority.binding?.worktree_id : null, topologyGeneration: file ? authority.binding?.topology_generation : null });- return writeResponse(await waitForWrite(engine, row, loadConfig() ?? { engine: engine.kind }));+ return writeResponse(wait.observe(await waitForWrite(engine, row, loadConfig() ?? { engine: engine.kind }, wait.ms())));}/** #5523: a Life Chronicle timeline row projected onto the depth page in the same publication. */diff --git a/test/e2e/maintenance-write-wait.test.ts b/test/e2e/maintenance-write-wait.test.tsnew file mode 100644index 0000000000..eb014534b4--- /dev/null+++ b/test/e2e/maintenance-write-wait.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../maintenance-write-wait.test.ts'));diff --git a/test/extract-atoms-accepted-pending.test.ts b/test/extract-atoms-accepted-pending.test.tsindex 60bd5329c8..9d9dc5818d 100644--- a/test/extract-atoms-accepted-pending.test.ts+++ b/test/extract-atoms-accepted-pending.test.ts@@ -10,6 +10,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';import type { WriteRequest } from '../src/core/persistence/model.ts';import { withEnv } from './helpers/with-env.ts';+import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';// #5601: an atom batch the owner accepted but has not published yet is// progress. extract_atoms reports it as pending, counts no failure and no@@ -18,10 +19,11 @@ import { withEnv } from './helpers/with-env.ts';let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-atoms-pending-'));beforeAll(async () => {+ __setMaintenanceWriteWaitForTests(5_000);configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();}, 60_000);-afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); resetGateway(); rmSync(home, { recursive: true, force: true }); });+afterAll(async () => { __setMaintenanceWriteWaitForTests(null); await disposePersistenceConsumer(engine); await engine.disconnect(); resetGateway(); rmSync(home, { recursive: true, force: true }); });test('#5601: extract_atoms with a slow owner reports accepted-pending, not failed, and resumes without a second model call', async () => withEnv({ GBRAIN_HOME: home }, async () => {const sourceId = 'atoms-pending';diff --git a/test/maintenance-write-wait.test.ts b/test/maintenance-write-wait.test.tsnew file mode 100644index 0000000000..e7c6eedaff--- /dev/null+++ b/test/maintenance-write-wait.test.ts@@ -0,0 +1,142 @@+/**+ * #5854: managed maintenance publishes wait one shared 30 s budget per job+ * (bounded by the job deadline), and after the first publish that is still+ * pending the job's later publishes do not wait.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { maintenancePreflight, publishMaintenancePage } from '../src/core/persistence/prepared-maintenance.ts';+import { MAINTENANCE_WRITE_WAIT_MS, MaintenanceWriteWait, __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-maintenance-wait-db-'));+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });+});++async function fixture(run: (engine: BrainEngine, sourceId: string) => Promise<void>) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-maintenance-wait-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `wait-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await run(engine, sourceId);+ });+ } finally {+ __setMaintenanceWriteWaitForTests(null);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}++const page = (n: number) => `---\ntitle: Maintenance ${n}\ntype: note\n---\nMaintenance output ${n}.`;++async function pendingAfter(publish: Promise<unknown>): Promise<{ ms: number; code: string | null }> {+ const started = performance.now();+ const code = await publish.then(() => null, (error: unknown) => error instanceof OperationError ? error.code : String(error));+ return { ms: performance.now() - started, code };+}++test('the wait is 30 s, bounded by the job deadline, and zero after a pending publish', () => {+ expect(MAINTENANCE_WRITE_WAIT_MS).toBe(30_000);+ let now = 1_000;+ expect(new MaintenanceWriteWait().ms()).toBe(30_000);+ const bounded = new MaintenanceWriteWait(now + 12_000, () => now);+ expect(bounded.ms()).toBe(12_000);+ now += 13_000;+ expect(bounded.ms()).toBe(0);+ const wait = new MaintenanceWriteWait();+ wait.observe({ state: 'committed' } as WriteRequest);+ expect(wait.ms()).toBe(30_000);+ wait.observe({ state: 'queued' } as WriteRequest);+ expect(wait.ms()).toBe(0);+});++test('a maintenance publish commits when the writer frees up after 6.5 s (the old 5 s wait returned write_pending)', async () => {+ await fixture(async (engine, sourceId) => {+ const authority = (await maintenancePreflight(engine, sourceId))!;+ const lock = (await acquireWorktree((await getWorktreeBinding(engine, sourceId))!, 1000))!;+ const release = setTimeout(() => { void lock.release(); }, 6_500);+ try {+ const receipt = await publishMaintenancePage(engine, authority, 'wiki/maintenance-wait', page(1), { expectedRevision: null });+ expect((receipt.write_request as { state: string }).state).toBe('committed');+ } finally { clearTimeout(release); await lock.release(); }+ expect((await engine.getPage('wiki/maintenance-wait', { sourceId }))?.compiled_truth).toContain('Maintenance output 1.');+ });+}, 60_000);++test('after the first pending publish, the job\'s later publishes do not wait; both commit once the writer frees up', async () => {+ await fixture(async (engine, sourceId) => {+ __setMaintenanceWriteWaitForTests(600);+ const authority = (await maintenancePreflight(engine, sourceId))!;+ const lock = (await acquireWorktree((await getWorktreeBinding(engine, sourceId))!, 1000))!;+ let first: Awaited<ReturnType<typeof pendingAfter>>, second: Awaited<ReturnType<typeof pendingAfter>>;+ try {+ first = await pendingAfter(publishMaintenancePage(engine, authority, 'wiki/wait-first', page(1), { expectedRevision: null }));+ second = await pendingAfter(publishMaintenancePage(engine, authority, 'wiki/wait-second', page(2), { expectedRevision: null }));+ } finally { await lock.release(); }+ expect(first.code).toBe('write_pending');+ expect(first.ms).toBeGreaterThanOrEqual(550);+ expect(second.code).toBe('write_pending');+ expect(second.ms).toBeLessThan(300);+ const fresh = (await maintenancePreflight(engine, sourceId))!;+ for (const [slug, n] of [['wiki/wait-first', 1], ['wiki/wait-second', 2]] as const) {+ const receipt = await publishMaintenancePage(engine, fresh, slug, page(n), { expectedRevision: null });+ expect((receipt.write_request as { state: string }).state).toBe('committed');+ }+ expect(await engine.executeRaw("SELECT slug FROM persistence_requests WHERE source_id=$1 AND state='committed' ORDER BY slug", [sourceId]))+ .toEqual([{ slug: 'wiki/wait-first' }, { slug: 'wiki/wait-second' }]);+ });+}, 60_000);++test('a job at its deadline publishes without waiting and defers the write', async () => {+ await fixture(async (engine, sourceId) => {+ const authority = (await maintenancePreflight(engine, sourceId, undefined, { deadlineAtMs: Date.now() - 1 }))!;+ const lock = (await acquireWorktree((await getWorktreeBinding(engine, sourceId))!, 1000))!;+ let result: Awaited<ReturnType<typeof pendingAfter>>;+ let states: Array<{ state: string }>;+ try {+ result = await pendingAfter(publishMaintenancePage(engine, authority, 'wiki/wait-deadline', page(3), { expectedRevision: null }));+ states = await engine.executeRaw("SELECT state FROM persistence_requests WHERE source_id=$1 AND slug='wiki/wait-deadline'", [sourceId]);+ } finally { await lock.release(); }+ expect(result.code).toBe('write_pending');+ expect(result.ms).toBeLessThan(300);+ expect(states).toHaveLength(1);+ expect(states[0].state).not.toBe('committed');+ });+}, 60_000);diff --git a/test/managed-maintenance.test.ts b/test/managed-maintenance.test.tsindex c6870e92a6..b2e01db4ec 100644--- a/test/managed-maintenance.test.ts+++ b/test/managed-maintenance.test.ts@@ -26,12 +26,14 @@ import { withEnv } from './helpers/with-env.ts';import { withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';import type { WriteRequest } from '../src/core/persistence/model.ts';import { testBackends } from './helpers/test-backends.ts';+import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';const backends = testBackends();const engines: BrainEngine[] = [];const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-maintenance-db-'));let closePostgres: (() => Promise<void>) | undefined;beforeAll(async () => {+ __setMaintenanceWriteWaitForTests(5_000);configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });if (backends.includes('pglite')) {const engine = new PGLiteEngine();@@ -43,6 +45,7 @@ beforeAll(async () => {}}, 120_000);afterAll(async () => {+ __setMaintenanceWriteWaitForTests(null);for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });});@@ -455,7 +458,8 @@ test('managed synthesis drives real children and publishes repaired provenance pconst rows = await engine.executeRaw("SELECT id FROM minion_jobs WHERE status='completed' AND data->>'source_id'=$1 LIMIT 1", [sourceId]);if (rows.length) await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [binding.worktree_id]);} });- expect(pending.status).toBe('fail');+ expect(pending.status).toBe('warn');+ expect(pending.details.publish_pending).toBe(1);expect(await engine.getConfig('dream.synthesize.last_completion_ts')).toBe(completion);const retainedCalls = calls;await disposePersistenceConsumer(engine);diff --git a/test/managed-synthesis-postprocess.test.ts b/test/managed-synthesis-postprocess.test.tsindex 4abf4c7ffc..585ac4f4a9 100644--- a/test/managed-synthesis-postprocess.test.ts+++ b/test/managed-synthesis-postprocess.test.ts@@ -2,11 +2,12 @@ import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';import { randomUUID } from 'node:crypto';import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { basename, join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runPhaseSynthesize } from '../src/core/cycle/synthesize.ts';-import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';@@ -354,3 +355,45 @@ test('partial multi-output recovery indexes every finalized output without repub}}, 2);}, 120_000);++test('#5854: a postprocess publish still pending after its wait is deferred, then finished by the next ordinary cycle', async () => {+ await fixture(async ({ engine, sourceId, root, opts, calls }) => {+ const corpus = join(root, '..', 'corpus');+ mkdirSync(corpus);+ writeFileSync(join(corpus, basename(opts.inputFile)), readFileSync(opts.inputFile));+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ const ordinary = { brainDir: root, sourceId, dryRun: false };+ await interruptAfterChild(engine, sourceId, ordinary);+ const slug = await outputSlug(engine, sourceId);+ await engine.executeRaw("DELETE FROM config WHERE key='dream.synthesize.last_completion_ts'");+ const jobsBefore = await engine.executeRaw('SELECT id FROM minion_jobs ORDER BY id');+ const spent = calls();+ const lock = (await acquireWorktree((await getWorktreeBinding(engine, sourceId))!, 1000))!;+ __setMaintenanceWriteWaitForTests(300);+ let deferred: Awaited<ReturnType<typeof runPhaseSynthesize>>;+ try { deferred = await runPhaseSynthesize(engine, ordinary); }+ finally { __setMaintenanceWriteWaitForTests(null); await lock.release(); }+ expect(deferred.status).toBe('warn');+ expect(deferred.details.publish_pending).toBe(1);+ expect(deferred.details.publish_deferred).toBe('publish deferred (writer busy); finishes next cycle, no action needed');+ expect(deferred.details.pages_written).toBe(0);+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).toBeNull();+ const [pending] = await engine.executeRaw<{ request_id: string }>(+ "SELECT request_id::text FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent->>'kind'='managed_maintenance_page'", [sourceId, slug]);+ expect(pending).toBeDefined();+ await disposePersistenceConsumer(engine);+ const next = await runPhaseSynthesize(engine, ordinary);+ expect(next.status).toBe('ok');+ expect(next.details.publish_pending).toBeUndefined();+ expect(next.details.written_slugs).toEqual([slug]);+ expect(calls()).toBe(spent);+ expect(await engine.executeRaw('SELECT id FROM minion_jobs ORDER BY id')).toEqual(jobsBefore);+ expect(await engine.executeRaw<{ request_id: string; state: string }>(+ "SELECT request_id::text, state FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent->>'kind'='managed_maintenance_page'", [sourceId, slug]))+ .toEqual([{ request_id: pending.request_id, state: 'committed' }]);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ expect(snapshot.page.frontmatter.dream_generated).toBe(true);+ expect(snapshot.page.compiled_truth).not.toContain('"an entirely invented');+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).not.toBeNull();+ });+}, 120_000);