Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(g6): synthesis outputs are verified and stamped before the child writes them (one commit, no invented quote in history); a covered world concept publishes once; put_pages fences a subagent's slugs per page (GBRA-60)
garrytan32b2f72258d1
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex dcdf02a6bb..004a48ac4c 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -35,12 +35,12 @@ src/core/cycle/extract-facts.ts runExtractFacts 382 seed: W5 baseline, refactorsrc/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/propose-takes.ts ProposeTakesPhase.process 430 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout); +1 #5425 [UC4]: the one attribution-check call after the extractor returns (logic in propose-takes-attribution.ts)src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 510 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts); +8 #6643 PR B: drifted concepts skipped before spend (state and the live check in persistence/drift-conflicts.ts ConceptDriftSkips), with the warn status, summary clause and skipped_file_drift details; +10 #7269 (GBRA-161 PR 4): a T3 group hashes without the synthesis model, and a rewrite that would leave a deterministic-tier page at its current template body and visibility is skipped unchanged-src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1055 +1 #5575 I2: output refs take their transcript taint before the provenance stamp (the stamp line stays the signal-guarded literal cycle-abort pins); 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 phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +6 GBRA-161 PR 4 (#7065): the synthesis generation activation after postprocess (logic in cycle/synthesize-generations.ts), its file holds and details.synthesis_generations; +1 GBRA-161 PR 5 (S-2): the summary revision read before the children are submitted+src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1056 +1 #5575 I2: output refs take their transcript taint before the provenance stamp (the stamp line stays the signal-guarded literal cycle-abort pins); 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 phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +6 GBRA-161 PR 4 (#7065): the synthesis generation activation after postprocess (logic in cycle/synthesize-generations.ts), its file holds and details.synthesis_generations; +1 GBRA-161 PR 5 (S-2): the summary revision read before the children are submitted; +1 GBRA-60: a managed child carries dream_output, so it writes each page verified and stamped (logic in cycle/synthesize-child-verify.ts)src/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 692 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition; +4 TODO: large-pages A6/T33: a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors and embeds through the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); +16 Wave B lane 1d (TODO wave-b PR 1): a body above the inline threshold takes the segmented stage and generation flip at the storage step (logic in persistence/segmented-apply.ts); +3 Wave B review: reuseSegments option (a rename re-preparation reuses the staged segmented body) and the remote fence merge over fenceBody; +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting itsrc/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: the oneshot sub-budget is passed as the call timeoutMs so the 300 s gateway backstop cannot cut it-src/core/minions/handlers/subagent.ts makeSubagentHandler 887 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loop-src/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 817 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loop+src/core/minions/handlers/subagent.ts makeSubagentHandler 889 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loop; +2 GBRA-60: a trusted dream child gets the put_pages batch tool (buildBrainPutPagesTool) from the oneshot tool options+src/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 819 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loop; +2 GBRA-60: a trusted dream child gets the put_pages batch tool (buildBrainPutPagesTool) from the oneshot tool optionssrc/core/minions/handlers/subagent.ts runSubagentViaGateway 329 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: turnTimeoutMs forwarded to gateway.toolLoopsrc/core/minions/queue.ts MinionQueue.add 498 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/minions/queue.ts MinionQueue.add>result=this.engine.transaction(#0) 359 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 552ff45c07..79f99d2406 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -14,7 +14,7 @@ src/commands/serve-http.ts 937 ratchet refactor wave 1 W4 split into serve-http-src/core/ai/gateway.ts 4530 ratchet +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts)src/commands/sync.ts 550 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor engine; +2 #7167: SyncResult.writer interface field (a managed dry run reports the writer instead of waiting on it; the read lives in persistence/sync-dry-run-writer.ts)src/core/cycle.ts 3338 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress; +1 GBRA-133: the extract phase passes the stale-drain budget to its targeted pass when sync gave no slug list-src/core/cycle/synthesize.ts 3240 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); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites); +2 GBRA-161 PR 4 (#7065): the synthesize phase activates each synthesized transcript's outputs as its generation (activateSynthesisGenerations import and call site; logic in cycle/synthesize-generations.ts); +8 GBRA-161 PR 5 (S-2): the dream summary publishes as a single-item dream_summary generation bound to its pre-run revision (publishSinglePage with a generation_fenced skip)+src/core/cycle/synthesize.ts 3241 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); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites); +2 GBRA-161 PR 4 (#7065): the synthesize phase activates each synthesized transcript's outputs as its generation (activateSynthesisGenerations import and call site; logic in cycle/synthesize-generations.ts); +8 GBRA-161 PR 5 (S-2): the dream summary publishes as a single-item dream_summary generation bound to its pre-run revision (publishSinglePage with a generation_fenced skip); +1 GBRA-60: a managed synthesis child carries dream_output (verify and stamp before put_page; cycle/synthesize-child-verify.ts)src/core/cycle/extract-atoms.ts 1658 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); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +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); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guardsrc/core/engine.ts 2858 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 option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +1 GBRA-161 PR 2: deprecation notes on insertFacts({ deleteForPageFirst }), deleteFactsForPage and expireFact (interface docs cannot move); +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move; +2 GBRA-156: TransactionOptions.readOnly (search read transactions open BEGIN READ ONLY; 2858 measured)src/core/import-file.ts 2075 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +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); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection); merge v0.60.332.0: #7172 and master growth compose at 2075diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 5900356daf..5f28d05f6b 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -153,6 +153,9 @@ src/core/cycle/phantom-redirect.ts tryRedirectPhantom field SEGW canonical targesrc/core/cycle/propose-takes.ts ProposeTakesPhase.process call:contentHash METAsrc/core/cycle/propose-takes.ts ProposeTakesPhase.process field STREAMsrc/core/cycle/propose-takes.ts listCandidatePages sql STREAM+src/core/cycle/synthesize-child-verify.ts readTranscript field INLINE a segmented conversation transcript is skipped: the child writes unverified and postprocessing verifies+src/core/cycle/synthesize-child-verify.ts verifyChildPages call:serializeMarkdown INLINE serializes the child's own model output, never a stored body+src/core/cycle/synthesize-child-verify.ts verifyChildPages field INLINE a segmented page it would replace skips child verification: postprocessing verifiessrc/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts field INLINEsrc/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts sql INLINEsrc/core/cycle/synthesize-generations.ts pages sql INLINE reads the synthesis outputs of one re-synthesized transcript for the predecessor coverage match (generations/synthesis-coverage.ts); segmented pages are excluded in SQL, so a segmented earlier output is never compared and stays live as an unreadable unmatched predecessor@@ -329,7 +332,7 @@ src/core/mentions/pass.ts pagesMatchingNames sql STREAM segmented pages are selesrc/core/mentions/pass.ts reconcileSource sql INLINE reads body_storage; a segmented row is scanned block by block (pageMentions)src/core/mentions/pass.ts refreshAliases sql STREAM segmented pages excluded in SQLsrc/core/minions/handlers/facts-absorb.ts makeFactsAbsorbHandler field STREAM-src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot call:serializeMarkdown SEGW+src/core/minions/handlers/subagent-oneshot.ts planOneshotWrites call:serializeMarkdown SEGWsrc/core/ops/admin.ts get_versions field SEGW lane 1e: segmented versions return metadata onlysrc/core/ops/attribution.ts get_write_attribution field NONE not the page body: timeline entry id paramsrc/core/ops/attribution.ts rowTarget field NONE not the page body: timeline entry id paramdiff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.tsindex 4810b4a24c..dea90e254d 100644--- a/src/core/cycle/concept-publication.ts+++ b/src/core/cycle/concept-publication.ts@@ -4,7 +4,9 @@* On a managed brain the phase publishes each concept page through the* maintenance coordinator (`publishMaintenancePage`) instead of the legacy* `importFromContent` writer, which a managed brain refuses. The caller keeps- * the #5525 order: publish private, bank provenance edges, then promote.+ * the #5525 order: publish private, bank provenance edges, then promote; a+ * concept whose banked edges already cover every member publishes once, at+ * world (GBRA-60).*/import type { BrainEngine, LinkBatchInput } from '../engine.ts';import { preservedConceptSections, stripPreservedConceptSections } from './concept-sections.ts';@@ -73,6 +75,20 @@ export async function publishManagedConcept(engine: BrainEngine, authority: Mainreturn typeof receipt.revision === 'string' ? receipt.revision : null;}+/**+ * #5525: whether the concept's `synthesized_from` provenance edges reach every member atom, the condition for publishing+ * it at world. Read before publication too (GBRA-60): edges a prior run banked let a republished concept go straight to+ * world instead of committing a private intermediate.+ */+export async function conceptProvenanceCovers(engine: BrainEngine, sourceId: string, conceptSlug: string, atomSlugs: readonly string[]): Promise<boolean> {+ const members = [...new Set(atomSlugs)];+ const [{ linked }] = await engine.executeRaw<{ linked: number }>(`SELECT COUNT(DISTINCT a.slug)::int AS linked FROM links l+ JOIN pages c ON c.id=l.from_page_id JOIN pages a ON a.id=l.to_page_id+ WHERE c.source_id=$1 AND c.slug=$2 AND a.slug=ANY($3::text[]) AND l.link_source='concept-provenance' AND l.link_type='synthesized_from'`,+ [sourceId, conceptSlug, members]);+ return Number(linked) === members.length;+}+/*** A published concept's provenance edges (#4589; GBRA-161 PR 5, C-4): banks `links` and retires the concept-provenance* edges to atoms that left the member group, in one transaction (coordinated on a managed brain) and only while the conceptdiff --git a/src/core/cycle/synthesize-child-verify.ts b/src/core/cycle/synthesize-child-verify.tsnew file mode 100644index 0000000000..f107222b4e--- /dev/null+++ b/src/core/cycle/synthesize-child-verify.ts@@ -0,0 +1,93 @@+/**+ * GBRA-60 (git-canonical memory, G6): a managed dream synthesis child verifies and stamps each page before it writes+ * it, so a strict source commits each output once, holding its verified body. The quote-verify repair and provenance+ * stamp are the ones postprocessing applies (synthesize-postprocess.ts): `verifyDreamPage` plus the S8 grounding pass+ * against the transcript, then `dream_generated`, the cycle dates, `raw_source` and `seat` on a page that is dream output.+ * Postprocessing then finds nothing to change and skips its publish; it stays the backstop for a child that could not+ * verify (a job queued by an older build, or a transcript this worker cannot read with the hash the cycle discovered).+ */+import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import type { BrainEngine } from '../engine.ts';+import type { DreamOutputSpec } from '../minions/types.ts';+import { parseMarkdown, serializeMarkdown } from '../markdown.ts';+import { withoutOffPeriodTurns } from '../context/capture-consent.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';+import { CONVERSATION_PAGE_URI_PREFIX } from './transcript-discovery.ts';+import { emptyQuoteVerifyStats, groundSource, verifyDreamPage, type QuoteVerifyStats, type VerifiablePage } from './synthesize-verify.ts';+import { attributionChecksEnabled } from './attribution-checks.ts';+import { resolveGroundingDecide } from './grounding-decide.ts';++/** What a child's ledger row records about the page it wrote: the transcript it verified against, and that page's stats. */+export interface ChildVerification { transcript_hash: string; quote_verify: boolean; stats: QuoteVerifyStats }++const sha256 = (text: string) => createHash('sha256').update(text, 'utf8').digest('hex');++/**+ * The transcript the cycle discovered at `spec.raw_source`, read the way discovery read it (a conversation page's body,+ * or the corpus file with or without its off-period turns), or null when no reading has the discovered hash.+ */+async function readTranscript(engine: BrainEngine, spec: DreamOutputSpec): Promise<string | null> {+ const candidates: Array<string | null> = [];+ if (spec.raw_source.startsWith(CONVERSATION_PAGE_URI_PREFIX)) {+ const rest = spec.raw_source.slice(CONVERSATION_PAGE_URI_PREFIX.length);+ const cut = rest.indexOf('/');+ const page = (await engine.readPageSnapshot(rest.slice(cut + 1), { sourceId: rest.slice(0, cut) }))?.page;+ candidates.push(page && !isSegmentedPage(page) ? page.compiled_truth : null);+ } else if (spec.raw_source.startsWith('/')) {+ try {+ const raw = readFileSync(spec.raw_source, 'utf8');+ candidates.push(raw, spec.raw_source.endsWith('.txt') ? withoutOffPeriodTurns(spec.raw_source, raw) : null);+ } catch { /* unreadable on this worker: postprocessing verifies */ }+ }+ return candidates.find((content): content is string => content !== null && sha256(content) === spec.transcript_hash) ?? null;+}++/**+ * The verified, stamped markdown for each planned page, with what the child's ledger row records; null when the+ * transcript cannot be read with the discovered hash, or a page it would replace is segmented (the pages are written as+ * planned and postprocessing verifies them).+ */+export async function verifyChildPages(engine: BrainEngine, spec: DreamOutputSpec, sourceId: string,+ pages: Array<{ slug: string; content: string }>): Promise<Array<{ content: string; verification: ChildVerification }> | null> {+ const transcript = await readTranscript(engine, spec);+ if (transcript === null) return null;+ const source = groundSource(spec.raw_source, transcript);+ const supersession = spec.quote_verify ? await attributionChecksEnabled(engine) : false;+ const grounding = spec.quote_verify ? await resolveGroundingDecide(engine) : undefined;+ const out: Array<{ content: string; verification: ChildVerification }> = [];+ for (const { slug, content } of pages) {+ const stats = emptyQuoteVerifyStats();+ const parsed = parseMarkdown(content, slug);+ const existing = (await engine.readPageSnapshot(slug, { sourceId }))?.page ?? null;+ if (existing && isSegmentedPage(existing)) return null;+ let page: VerifiablePage = { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline ?? '', frontmatter: { ...parsed.frontmatter } };+ if (!existing || existing.frontmatter?.dream_generated === true) {+ const firstDate = page.frontmatter.dream_created_cycle_date || page.frontmatter.dream_cycle_date || spec.cycle_date;+ page.frontmatter = { ...page.frontmatter, dream_generated: true, dream_cycle_date: firstDate, dream_created_cycle_date: firstDate,+ raw_source: spec.raw_source, ...(spec.seat ? { seat: spec.seat } : {}) };+ }+ if (spec.quote_verify) {+ if (existing && existing.compiled_truth.trim() === page.compiled_truth.trim() && (existing.timeline ?? '').trim() === page.timeline.trim()) stats.skipped_unchanged++;+ else {+ const prior = existing ? { compiled_truth: existing.compiled_truth, timeline: existing.timeline ?? '', frontmatter: existing.frontmatter ?? {} } : null;+ if (prior) stats.preexisting_diffed++;+ const mechanical = verifyDreamPage(page, [source], { prior, checkedAt: spec.cycle_date, supersession }, stats);+ const verified = grounding ? await grounding.apply(mechanical, [source], `page:${sourceId}:${slug}`, spec.cycle_date) : mechanical;+ if (verified.changed) stats.pages_repaired++;+ page = { compiled_truth: verified.compiled_truth, timeline: verified.timeline, frontmatter: verified.frontmatter };+ }+ }+ out.push({ content: serializeMarkdown(page.frontmatter, page.compiled_truth, page.timeline, { type: parsed.type, title: parsed.title, tags: parsed.tags }),+ verification: { transcript_hash: spec.transcript_hash, quote_verify: spec.quote_verify, stats } });+ }+ return out;+}++/** Adds one child page's verify stats into the phase's. */+export function addVerifyStats(into: QuoteVerifyStats, from: Partial<QuoteVerifyStats>): void {+ for (const key of Object.keys(into) as Array<keyof QuoteVerifyStats>) {+ const value = from[key];+ if (typeof value === 'number' && Number.isFinite(value)) into[key] += value;+ }+}diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex f5d8a363cd..f0e0fb46c5 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -45,7 +45,7 @@ import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';import { derivedWriteThrough, reportFileHolds } from './derived-write-through.ts';import { addSpellingRedirects, canonicalConceptStem, loadConceptRedirects, loadLiveConceptStems } from './concept-redirects.ts';import {- replaceConceptProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, conceptPublicationHold, publishClassicConcept, publishManagedConcept, stripFenceSections,+ conceptProvenanceCovers, replaceConceptProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, conceptPublicationHold, publishClassicConcept, publishManagedConcept, stripFenceSections,} from './concept-publication.ts';import { readPhaseConfigNumber, SYNTHESIZE_CONCEPTS_BUDGET_KEY, SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD } from './phase-config-values.ts';import { ConceptRetryBound, MAX_CONCEPT_ATTEMPTS } from './concept-retry-bound.ts';@@ -534,7 +534,11 @@ export async function runPhaseSynthesizeConcepts(};// #5525: a world concept stays private until every member's provenance// edge is durable, because a later private flip reaches it through them.- if (!await publishOrRecord('private')) continue;+ // GBRA-60: one whose edges already cover every member publishes once, at+ // world, so a strict source never commits an intermediate private page.+ const src = opts.sourceId ?? 'default';+ const covered = visibility === 'world' && await conceptProvenanceCovers(engine, src, conceptSlug, group.atomSlugs);+ if (!await publishOrRecord(covered ? 'world' : 'private')) continue;if (synthesisMode === 'llm') retries.succeed(`${opts.sourceId ?? 'default'}:${conceptSlug}`);// #4589: bank concept<->member-atom provenance edges. The prompt forbids// enumerating atoms in the body and no frontmatter field maps to a link@@ -544,7 +548,6 @@ export async function runPhaseSynthesizeConcepts(// another source drops out of the batch JOIN — no cross-source edge).// ON CONFLICT DO NOTHING makes re-runs idempotent, so a failure here is// best-effort: recorded as a warn, the page write stands. Mirrors #3961.- const src = opts.sourceId ?? 'default';const provenanceLinks: LinkBatchInput[] = [...new Set(group.atomSlugs)].flatMap((atomSlug) => [{ from_slug: conceptSlug, to_slug: atomSlug, link_type: 'synthesized_from', link_source: 'concept-provenance', context: 'member atom', from_source_id: src, to_source_id: src },{ from_slug: atomSlug, to_slug: conceptSlug, link_type: 'synthesizes', link_source: 'concept-provenance', context: 'concept synthesized from this atom', from_source_id: src, to_source_id: src },@@ -568,14 +571,7 @@ export async function runPhaseSynthesizeConcepts(linkWarnings.push({ concept: group.conceptSlug, warning: `provenance links failed: ${msg}` });console.error(`[synthesize_concepts] provenance links failed for ${conceptSlug} (non-fatal): ${msg}`);}- if (visibility === 'world') {- const members = [...new Set(group.atomSlugs)];- const [{ linked }] = await engine.executeRaw<{ linked: number }>(`SELECT COUNT(DISTINCT a.slug)::int AS linked FROM links l- JOIN pages c ON c.id=l.from_page_id JOIN pages a ON a.id=l.to_page_id- WHERE c.source_id=$1 AND c.slug=$2 AND a.slug=ANY($3::text[]) AND l.link_source='concept-provenance' AND l.link_type='synthesized_from'`,- [src, conceptSlug, members]);- if (Number(linked) === members.length && !await publishOrRecord('world')) continue;- }+ if (visibility === 'world' && !covered && await conceptProvenanceCovers(engine, src, conceptSlug, group.atomSlugs) && !await publishOrRecord('world')) continue;}conceptsWritten++;// v0.41.19.0 (T4): one tick per concept group with running count.diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.tsindex 7f8abecfa0..f9e4b13614 100644--- a/src/core/cycle/synthesize-postprocess.ts+++ b/src/core/cycle/synthesize-postprocess.ts@@ -18,6 +18,8 @@ import type { PhaseResult } from '../cycle.ts';import type { DiscoveredTranscript } from './transcript-discovery.ts';import { transcriptDerivation } from './dream-taint.ts';import { declareDerivation, readDerivationDeclaration } from '../trust/taint.ts';+import { addVerifyStats, type ChildVerification } from './synthesize-child-verify.ts';+import { storedPageTier } from '../trust/page-write.ts';import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPrior, verifyDreamPage, type GroundedSource, type GroundingPass } from './synthesize-verify.ts';import { attributionChecksEnabled } from './attribution-checks.ts';import { resolveGroundingDecide } from './grounding-decide.ts';@@ -26,7 +28,8 @@ import { DEFERRED_READ_LABEL, isPostprocessReadTimeout, pendingOutputsFor, readPtype DeferredRead, type PendingOutput, type PostprocessDeferral } from './synthesize-postprocess-deferral.ts';interface OutputRef { slug: string; source_id: string; raw_source?: string; seat?: string; first_write_at?: Date; }-export interface RetainedOutput { job_id: number | bigint; job_key: string; input_slug: string; request: WriteRequest; }+/** `verification` (GBRA-60): the child verified and stamped the page it wrote (synthesize-child-verify.ts). */+export interface RetainedOutput { job_id: number | bigint; job_key: string; input_slug: string; request: WriteRequest; verification?: ChildVerification }/*** An output postprocessing leaves alone for good and reports once (GBRA-130 A-4): a later non-maintenance write* moved its page (#6360, revision_conflict), its postprocess request ended without committing (the request's@@ -74,7 +77,7 @@ export async function loadCommittedSynthesisOutputs(engine: BrainEngine, authorireturn committedRequestsFor(engine, authority, await retainedPutPageCalls(engine, childIds));}-interface RetainedCall { job_id: number | bigint; job_key: string; input_slug: string; slug: string; requestId: string; revision: string; started_at?: string }+interface RetainedCall { job_id: number | bigint; job_key: string; input_slug: string; slug: string; requestId: string; revision: string; started_at?: string; verification?: ChildVerification }async function retainedPutPageCalls(engine: BrainEngine, childIds: number[]): Promise<RetainedCall[]> {if (!childIds.length) return [];@@ -88,9 +91,11 @@ async function retainedPutPageCalls(engine: BrainEngine, childIds: number[]): Prlet requestId: string | undefined;try { requestId = parseWriteRequestId(t.input?.request_id); } catch { return []; }const startedAt = t.started_at ? new Date(t.started_at) : null;+ const verification = t.input?.dream_verify as ChildVerification | undefined;return requestId && typeof inputSlug === 'string' && typeof revision === 'string'? [{ job_id: t.job_id, job_key: t.job_key, input_slug: inputSlug, slug: journaledPageSlug(inputSlug), requestId, revision,- ...(startedAt && !Number.isNaN(startedAt.getTime()) ? { started_at: startedAt.toISOString() } : {}) }] : [];+ ...(startedAt && !Number.isNaN(startedAt.getTime()) ? { started_at: startedAt.toISOString() } : {}),+ ...(typeof verification?.transcript_hash === 'string' ? { verification } : {}) }] : [];});}@@ -109,7 +114,7 @@ async function committedRequestsFor(engine: BrainEngine, authority: MaintenanceA[[...new Set(calls.map(c => c.requestId))], authority.writer.sourceId, authority.writer.sourceIncarnation]);return requests.flatMap(({ request }) => calls.filter(c => c.requestId === String(request.request_id) && c.slug === request.slug && c.revision === request.outcome?.revision)- .map(c => ({ job_id: c.job_id, job_key: c.job_key, input_slug: c.input_slug, request })));+ .map(c => ({ job_id: c.job_id, job_key: c.job_key, input_slug: c.input_slug, request, ...(c.verification ? { verification: c.verification } : {}) })));}/** Child outputs for postprocessing, or the outputs to carry when the committed-outputs read hit the statement timeout (#6757). */@@ -297,7 +302,7 @@ export async function postprocessManagedSynthesis(}}await authorizeStoredRequest(engine, output.request);- let content: string;+ let content: string, unchanged = false;if (prior) {if (prior.intent?.kind !== 'managed_maintenance_page' || prior.intent.expected_revision !== base || typeof prior.intent.content !== 'string') {settled.push(outputRequestId);@@ -311,11 +316,15 @@ export async function postprocessManagedSynthesis(if (!snapshot) throw new Error(`synthesis postprocess: no snapshot for ${ref.slug}`);const firstDate = snapshot.page.frontmatter.dream_created_cycle_date || snapshot.page.frontmatter.dream_cycle_date || opts.cycleDate;const since = ref.first_write_at ?? opts.sinceByTranscript.get(transcript.filePath);- let page = isDreamOwnedPage(snapshot.page, since) ? { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,+ // GBRA-60: the child stamped (and, with quote_verify, verified) this page against the same transcript and nothing+ // moved it since, so its stamp stands, as a committed postprocess would on a replay, and its stats count.+ const child = output.verification?.transcript_hash === hash && snapshot.revision === revision ? output.verification : undefined;+ let page = !child && isDreamOwnedPage(snapshot.page, since) ? { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, raw_source: path, ...(transcript.seat ? { seat: transcript.seat } : {}) } } : snapshot.page;if (opts.quoteVerify) {- const prior = since ? await resolveVerifyPrior(engine, snapshot.page, ref.source_id, since) : null;- if (prior === 'unchanged') stats.skipped_unchanged++;+ const prior = child?.quote_verify ? 'child' : since ? await resolveVerifyPrior(engine, snapshot.page, ref.source_id, since) : null;+ if (prior === 'child') addVerifyStats(stats, child!.stats);+ else if (prior === 'unchanged') stats.skipped_unchanged++;else {if (prior) stats.preexisting_diffed++;const source = grounded?.path === transcript.filePath ? grounded : (grounded = groundSource(transcript.filePath, transcript.content));@@ -326,12 +335,21 @@ export async function postprocessManagedSynthesis(}}content = serializePageToMarkdown(page, snapshot.tags);+ unchanged = content === serializePageToMarkdown(snapshot.page, snapshot.tags);}throwIfAborted(opts.signal, '[dream] synthesis postprocessing');// #5575 I2: the page publishes at its transcript's tier (lowered even when the content is unchanged), with its input edges.// A retained request replays the declaration it was admitted with (none for one admitted before tiers).const derivation = prior ? readDerivationDeclaration(prior.intent?.derivation) ?? undefined: await transcriptDerivation(engine, transcript, opts.meetingTranscriptsDir).then(d => declareDerivation(d.trust, d.inputs));+ // GBRA-60: a page the child already wrote verified and stamped, at the transcript's tier with no input edges to+ // record, has nothing left to publish; skipping keeps a strict source at one commit per output.+ if (unchanged && derivation && !derivation.inputs.length && await storedPageTier(engine, ref.source_id, ref.slug) === derivation.tier) {+ settled.push(outputRequestId);+ writtenRefs.push(finalizedRef);+ finalizedRefs.push(finalizedRef);+ return;+ }try {await publishMaintenancePage(engine, authority, ref.slug, content, { requestId, expectedRevision: base, derivation });} catch (error) {diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex d2b5d47c60..6dae09a4fe 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -923,6 +923,7 @@ async function runPhaseSynthesizeInner(? `${t.contentHash.slice(0, 6)}-c${i}`: t.contentHash.slice(0, 6),oneshot_task_prefixes: [config.reflectionsPrefix, config.originalsPrefix], // #6160: oneshot task shapes+ ...(maintenance ? { dream_output: { raw_source: t.filePath, transcript_hash: t.contentHash, cycle_date: summaryDate, quote_verify: config.quoteVerify, ...(t.seat ? { seat: t.seat } : {}) } } : {}), // GBRA-60require_writes: true,// #1586: scope every child tool call to the cycle's resolved source// so put_page writes land there instead of the hardcoded 'default'.diff --git a/src/core/minions/handlers/subagent-oneshot.ts b/src/core/minions/handlers/subagent-oneshot.tsindex 9cfeda7915..84910f1603 100644--- a/src/core/minions/handlers/subagent-oneshot.ts+++ b/src/core/minions/handlers/subagent-oneshot.ts@@ -31,7 +31,8 @@* a completed result.*/-import { retainToolWriteRequestId, awaitCommittedToolWrite, isPendingToolWrite } from '../tool-write-identity.ts';+import { retainToolWriteRequestId, awaitCommittedToolWrite, assertToolWriteCommitted, isPendingToolWrite } from '../tool-write-identity.ts';+import { pageBatchChildRequestId } from '../../persistence/page-batch-id.ts';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../../engine.ts';import type { MinionJobContext, SubagentHandlerData, SubagentResult, ToolDef, ContentBlock, OneshotFallbackReason } from '../types.ts';@@ -213,6 +214,11 @@ export interface OneshotArgs {turnTimeoutMs?: number;/** The deferEmbeds-enabled brain_put_page ToolDef (same executor as the loop). */putPageTool: ToolDef | undefined;+ /**+ * GBRA-60: a trusted dream child's put_pages ToolDef; when set the pages are written as one batch (a Postgres+ * consumer publishes them as one group), each still settled on its own ledger row under its batch child request id.+ */+ putPagesTool?: ToolDef;leaseKey: string;maxConcurrent: number;leaseTtlMs: number;@@ -243,12 +249,68 @@ function isAbortShaped(e: unknown): boolean {return isAbortError(e) || (e instanceof Error && /\babort|\btimed?[ _-]?out/i.test(e.message));}-interface LedgerRow { tool_use_id: string; ordinal: number | null; status: string; slug: string | null; content: string | null; request_id: string | null; skip_reason: string | null }+interface LedgerRow { tool_use_id: string; ordinal: number | null; status: string; slug: string | null; content: string | null; request_id: string | null; skip_reason: string | null;+ batch_id: string | null }++/**+ * The oneshot writes, each with the ledger row banked before it executes. Each page is ALWAYS serialized with the+ * pinned type + parsed title: model-supplied frontmatter was stripped at parse time (R3-1), so no body can smuggle its+ * own keys past normalization. GBRA-60: a trusted dream child (`dreamOutput`; a delegated job never reads a transcript+ * path from its data) writes each page verified and stamped, so it is committed once, and its row records the+ * verification for postprocessing; with a batch each page's request id is its batch child id, so its row reads like a+ * put_page's.+ */+async function planOneshotWrites(engine: BrainEngine, jobId: number, dreamOutput: SubagentHandlerData['dream_output'], sourceId: string,+ pages: OneshotPage[], batchId: string | null) {+ const inv8 = randomUUID().replace(/-/g, '').slice(0, 8);+ const drafts = pages.map(page => ({ slug: page.slug, content: serializeMarkdown({}, page.body, '', { type: page.type as PageType, title: page.title, tags: [] }) }));+ const verified = dreamOutput ? await (await import('../../cycle/synthesize-child-verify.ts')).verifyChildPages(engine, dreamOutput, sourceId, drafts) : null;+ return drafts.map((draft, i) => {+ const toolUseId = `${ONESHOT_TOOL_USE_ID_PREFIX}${inv8}-p${i}`;+ const input = { slug: draft.slug, content: verified?.[i]!.content ?? draft.content, ...(batchId ? { request_id: pageBatchChildRequestId(batchId, i) } : {}) };+ retainToolWriteRequestId(input, jobId, 1, i, toolUseId, 'brain_put_page');+ return { toolUseId, input, ledger: { ...input, ...(batchId ? { batch_id: batchId } : {}), ...(verified ? { dream_verify: verified[i]!.verification } : {}) } };+ });+}++/**+ * GBRA-60: the pages of one oneshot invocation written as one put_pages batch. The first page's write sends the whole+ * batch (resent under the same request id while any page is still pending, which admits nothing new); each page then+ * settles from its own entry, so a refused page fails alone and a committed one carries its state and revision.+ */+function batchPageWriter(ctx: MinionJobContext, engine: BrainEngine, tool: ToolDef, batchId: string, pages: Array<{ slug: string; content: string }>) {+ let sent: Promise<Array<Record<string, unknown>>> | undefined;+ return async (index: number): Promise<unknown> => {+ const all = sent ??= awaitCommittedToolWrite(ctx, 'brain_put_page', async (): Promise<Array<Record<string, unknown>>> => {+ const receipt = await tool.execute({ request_id: batchId, pages: pages.map(({ slug, content }) => ({ slug, content })) },+ { engine, jobId: ctx.id, remote: true, signal: ctx.signal }) as { pages?: Array<Record<string, unknown>> };+ const entries = receipt.pages ?? [];+ for (const entry of entries) {+ if (['queued', 'running', 'recovering'].includes(String(entry.state))) assertToolWriteCommitted({ request_id: entry.request_id, state: entry.state, retry_after_ms: 1000 }, 'brain_put_page');+ }+ return entries;+ }) as Promise<Array<Record<string, unknown>>>;+ const entry = (await all)[index];+ if (entry?.state === 'committed') return entry;+ const message = (entry?.error as { message?: unknown } | undefined)?.message;+ throw new Error(`brain_put_pages: page ${index} ${typeof message === 'string' ? message : `ended ${String(entry?.state ?? 'not_admitted')}`}`);+ };+}++/**+ * GBRA-60: recovery's writer for each batch among a ledger's pending rows: the whole batch replayed under its request+ * id (nothing is written twice), its pages taken from every row of the batch in page order.+ */+function ledgerBatchWriters(ctx: MinionJobContext, engine: BrainEngine, tool: ToolDef | undefined, ledger: LedgerRow[]) {+ const writers = new Map<string, ReturnType<typeof batchPageWriter>>();+ return (id: string) => writers.get(id) ?? writers.set(id, batchPageWriter(ctx, engine, tool!, id, ledger.filter(row => row.batch_id === id)+ .sort((a, b) => (a.ordinal ?? 0) - (b.ordinal ?? 0)).map(row => ({ slug: row.slug ?? '', content: row.content ?? '' })))).get(id)!;+}async function loadOneshotLedger(engine: BrainEngine, jobId: number): Promise<LedgerRow[]> {return engine.executeRaw<LedgerRow>(`SELECT tool_use_id, ordinal, status, input->>'slug' AS slug, input->>'content' AS content, input->>'request_id' AS request_id,- input->>'skip_reason' AS skip_reason+ input->>'skip_reason' AS skip_reason, input->>'batch_id' AS batch_idFROM subagent_tool_executionsWHERE job_id = $1 AND tool_use_id LIKE $2ORDER BY id`,@@ -285,19 +347,20 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc// ledger would finalize 'completed' with zero pages — the exact// completed-means-zero-pages class #4217 exists to kill (flagged// independently by two ship reviewers).+ const batchOf = ledgerBatchWriters(ctx, engine, args.putPagesTool, priorLedger);for (const row of priorLedger) {if (row.status !== 'pending') continue;const input = { slug: row.slug ?? '', content: row.content ?? '', ...(row.request_id ? { request_id: row.request_id } : {}) };retainToolWriteRequestId(input, ctx.id, 1, row.ordinal ?? 0, row.tool_use_id, 'brain_put_page');- if (!putPageTool || !input.slug || !input.content) {+ if ((row.batch_id ? !args.putPagesTool : !putPageTool) || !input.slug || !input.content) {await persistToolExecFailed(engine, ctx.id, 1, row.ordinal ?? 0, row.tool_use_id, 'brain_put_page', input,'oneshot recovery: pending write could not be re-executed (missing tool or ledger input)');row.status = 'failed';continue;}try {- const output = await awaitCommittedToolWrite(ctx, 'brain_put_page',- () => putPageTool.execute(input, { engine, jobId: ctx.id, remote: true, signal: ctx.signal }));+ const output = row.batch_id ? await batchOf(row.batch_id)(row.ordinal ?? 0) : await awaitCommittedToolWrite(ctx, 'brain_put_page',+ () => putPageTool!.execute(input, { engine, jobId: ctx.id, remote: true, signal: ctx.signal }));await persistToolExecComplete(engine, ctx.id, 1, row.ordinal ?? 0, row.tool_use_id, output);row.status = 'complete';} catch (e) {@@ -534,17 +597,9 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc}// ── Programmatic writes through the shared put_page executor ────────────- const inv8 = randomUUID().replace(/-/g, '').slice(0, 8);- const plannedWrites = parsed.pages.map((page, i) => {- // ALWAYS serialize with the pinned type + parsed title — model-supplied- // frontmatter was stripped at parse time (R3-1), so no body can smuggle- // its own keys past normalization.- const content = serializeMarkdown({}, page.body, '', { type: page.type as PageType, title: page.title, tags: [] });- const toolUseId = `${ONESHOT_TOOL_USE_ID_PREFIX}${inv8}-p${i}`;- const input = { slug: page.slug, content };- retainToolWriteRequestId(input, ctx.id, 1, i, toolUseId, 'brain_put_page');- return { toolUseId, input };- });+ const batchId = args.putPagesTool ? randomUUID() : null;+ const plannedWrites = await planOneshotWrites(engine, ctx.id, submitted ? undefined : data.dream_output, writeSourceId, parsed.pages, batchId);+ const writeBatch = batchId ? batchPageWriter(ctx, engine, args.putPagesTool!, batchId, plannedWrites.map(w => w.input)) : null;// Bank the WHOLE batch as pending in ONE transaction BEFORE the first// write executes. Interleaved pending/execute would let a crash mid-batch// leave a truncated ledger, and recovery would then finalize 'completed'@@ -562,7 +617,7 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc`INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, ordinal)VALUES ($1, 1, $2, 'brain_put_page', $3::text::jsonb, 'pending', $4)ON CONFLICT (job_id, message_idx, ordinal) DO NOTHING`,- [ctx.id, w.toolUseId, JSON.stringify(w.input), i],+ [ctx.id, w.toolUseId, JSON.stringify(w.ledger), i],);}});@@ -577,7 +632,7 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutcif (ctx.signal?.aborted) throw new DOMException('oneshot write loop aborted by job signal', 'AbortError');let output: unknown;try {- output = await awaitCommittedToolWrite(ctx, 'brain_put_page',+ output = writeBatch ? await writeBatch(i) : await awaitCommittedToolWrite(ctx, 'brain_put_page',() => putPageTool.execute(input, { engine, jobId: ctx.id, remote: true, signal: ctx.signal }));} catch (e) {// Abort/transient-conn errors are not write verdicts (same rule asdiff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.tsindex a7e6865128..db4b7ad490 100644--- a/src/core/minions/handlers/subagent.ts+++ b/src/core/minions/handlers/subagent.ts@@ -38,7 +38,7 @@ import type {import type { BrainEngine } from '../../engine.ts';import type { GBrainConfig } from '../../config.ts';import { loadConfig, isConfigTruthy } from '../../config.ts';-import { buildBrainTools, selectAllowedTools } from '../tools/brain-allowlist.ts';+import { buildBrainPutPagesTool, buildBrainTools, selectAllowedTools } from '../tools/brain-allowlist.ts';import {acquireLease,releaseLease,@@ -531,7 +531,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {if (dispatchOneshot) {// Rebuild put_page with deferEmbeds so the embed network call leaves// the model path (the standing embed machinery backfills).- const oneshotRegistry = deps.toolRegistry ?? buildBrainTools({+ const oneshotToolOpts = {subagentId: ctx.id,engine,config,@@ -539,7 +539,8 @@ export function makeSubagentHandler(deps: SubagentDeps) {allowedSlugPrefixes: data.allowed_slug_prefixes,sourceId: data.source_id,deferEmbeds: true, readBudgetBytes: data.read_budget_bytes,- });+ };+ const oneshotRegistry = deps.toolRegistry ?? buildBrainTools(oneshotToolOpts);// Honor allowed_tools EXACTLY like the loop registry — a submitter// that scoped its job read-only must not gain write capability by// setting mode: oneshot (put_page filtered out → no_put_page_tool@@ -554,6 +555,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {maxOutputTokens,turnTimeoutMs,putPageTool: oneshotTools.find(t => t.name === 'brain_put_page'),+ putPagesTool: data.dream_output && !submitted && !deps.toolRegistry && oneshotTools.some(t => t.name === 'brain_put_page') ? buildBrainPutPagesTool(oneshotToolOpts) : undefined,leaseKey: gatewayLeaseKey,maxConcurrent,leaseTtlMs,diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.tsindex fcc85236b8..8045174da6 100644--- a/src/core/minions/tools/brain-allowlist.ts+++ b/src/core/minions/tools/brain-allowlist.ts@@ -240,62 +240,75 @@ export function buildBrainTools(opts: BuildBrainToolsOpts): ToolDef[] {// through the job payload).if (opts.sourceId !== undefined) validateSourceId(opts.sourceId);- return picked.map<ToolDef>(op => {- const schema = op.name === 'put_page'- ? namespacedPutPageSchema(op, opts.subagentId, opts.allowedSlugPrefixes)- : paramsToInputSchema(op);+ return picked.map(op => brainTool(op, opts));+}- const toolName = sanitizeToolName(op.name);- if (!ANTHROPIC_NAME_RE.test(toolName)) {- throw new Error(`brain tool name ${toolName} does not match Anthropic constraint`);- }+/**+ * GBRA-60: the `put_pages` tool of a trusted dream synthesis child's oneshot runner, which writes its validated pages+ * as one batch so a Postgres consumer publishes them as one group (one commit on a strict source). It is never in+ * the registry a model sees: BRAIN_TOOL_ALLOWLIST keeps put_pages out, and the oneshot runner is its only caller.+ */+export function buildBrainPutPagesTool(opts: BuildBrainToolsOpts): ToolDef {+ if (opts.sourceId !== undefined) validateSourceId(opts.sourceId);+ return brainTool(operations.find(op => op.name === 'put_pages')!, opts);+}- return {- name: toolName,- description: op.description,- input_schema: schema,- // The persisted tool dispatcher binds mutations to a stable request UUID;- // a replay returns the original durable receipt without another write.- idempotent: true,- // v0.41 Approach C: surface usage_hint to the system-prompt renderer.- // Keyed by the unprefixed op name. Undefined when no hint is registered.- usage_hint: BRAIN_TOOL_USAGE_HINTS[op.name],- async execute(input: unknown, ctx: ToolCtx): Promise<unknown> {- if (op.localOnly) throw new Error(`${toolName}: local-only operations cannot be delegated`);- const opCtx = buildOpContext({- engine: ctx.engine,- config: opts.config,- subagentId: opts.subagentId,- jobId: ctx.jobId,- signal: ctx.signal,- brainId: opts.brainId,- allowedSlugPrefixes: opts.allowedSlugPrefixes,- sourceId: opts.sourceId,- deferEmbeds: opts.deferEmbeds,- delegatedAuth: opts.delegatedAuth,- });- const raw = (input && typeof input === 'object') ? input as Record<string, unknown> : {};- // Same order the MCP dispatchers keep: normalize the optional-param- // absent idioms (`null`, `''` on a string) FIRST — the validator's- // header calls this load-bearing — then validate, so a missing- // required param (or wrong type / unknown enum) is named back to the- // model instead of crashing inside the handler, and `since: ""` never- // reaches a handler raw.- const params = normalizeOptionalParams(op, raw);- // #6297: a subagent's full-content read returns the round-trip fields only, not the body twice.- if (op.name === 'get_page' && params.include_content === true) params.content_only = true;- const validationError = validateParams(op, params);- if (validationError) throw new Error(`${toolName}: ${validationError}`);- const output = op.name === 'put_page'- ? await op.handler(opCtx, params).catch(e => rethrowWithCurrentRevision(ctx.engine, opCtx.sourceId ?? 'default', params.slug, e))- : await op.handler(opCtx, params);- const rejection = op.name === 'put_page' ? putPageRejection(output) : null;- if (rejection) throw new Error(rejection);- if (op.name === 'get_page' && opts.readBudgetBytes) return budgetedPageRead(ctx.engine, ctx.jobId, opts.readBudgetBytes, params.slug, output);- return output;- },- };- });+/** One subagent tool: `op` under a subagent-tagged OperationContext, with a namespace-wrapped schema for put_page. */+function brainTool(op: Operation, opts: BuildBrainToolsOpts): ToolDef {+ const schema = op.name === 'put_page'+ ? namespacedPutPageSchema(op, opts.subagentId, opts.allowedSlugPrefixes)+ : paramsToInputSchema(op);++ const toolName = sanitizeToolName(op.name);+ if (!ANTHROPIC_NAME_RE.test(toolName)) {+ throw new Error(`brain tool name ${toolName} does not match Anthropic constraint`);+ }++ return {+ name: toolName,+ description: op.description,+ input_schema: schema,+ // The persisted tool dispatcher binds mutations to a stable request UUID;+ // a replay returns the original durable receipt without another write.+ idempotent: true,+ // v0.41 Approach C: surface usage_hint to the system-prompt renderer.+ // Keyed by the unprefixed op name. Undefined when no hint is registered.+ usage_hint: BRAIN_TOOL_USAGE_HINTS[op.name],+ async execute(input: unknown, ctx: ToolCtx): Promise<unknown> {+ if (op.localOnly) throw new Error(`${toolName}: local-only operations cannot be delegated`);+ const opCtx = buildOpContext({+ engine: ctx.engine,+ config: opts.config,+ subagentId: opts.subagentId,+ jobId: ctx.jobId,+ signal: ctx.signal,+ brainId: opts.brainId,+ allowedSlugPrefixes: opts.allowedSlugPrefixes,+ sourceId: opts.sourceId,+ deferEmbeds: opts.deferEmbeds,+ delegatedAuth: opts.delegatedAuth,+ });+ const raw = (input && typeof input === 'object') ? input as Record<string, unknown> : {};+ // Same order the MCP dispatchers keep: normalize the optional-param+ // absent idioms (`null`, `''` on a string) FIRST — the validator's+ // header calls this load-bearing — then validate, so a missing+ // required param (or wrong type / unknown enum) is named back to the+ // model instead of crashing inside the handler, and `since: ""` never+ // reaches a handler raw.+ const params = normalizeOptionalParams(op, raw);+ // #6297: a subagent's full-content read returns the round-trip fields only, not the body twice.+ if (op.name === 'get_page' && params.include_content === true) params.content_only = true;+ const validationError = validateParams(op, params);+ if (validationError) throw new Error(`${toolName}: ${validationError}`);+ const output = op.name === 'put_page'+ ? await op.handler(opCtx, params).catch(e => rethrowWithCurrentRevision(ctx.engine, opCtx.sourceId ?? 'default', params.slug, e))+ : await op.handler(opCtx, params);+ const rejection = op.name === 'put_page' ? putPageRejection(output) : null;+ if (rejection) throw new Error(rejection);+ if (op.name === 'get_page' && opts.readBudgetBytes) return budgetedPageRead(ctx.engine, ctx.jobId, opts.readBudgetBytes, params.slug, output);+ return output;+ },+ };}/**diff --git a/src/core/minions/types.ts b/src/core/minions/types.tsindex c4bd787998..f6f5b4798c 100644--- a/src/core/minions/types.ts+++ b/src/core/minions/types.ts@@ -512,6 +512,20 @@ export function rowToMinionJob(row: Record<string, unknown>): MinionJob {* tool registry and provider config resolve via handler-side defaults + env,* not per-job data, so restart/replay uses the same behavior.*/+/** GBRA-60: the transcript a dream synthesis child's pages are verified against, and the stamp they carry. */+export interface DreamOutputSpec {+ /** The transcript path (or conversation-page URI) the cycle discovered; stamped as `raw_source`. */+ raw_source: string;+ /** sha256 of the transcript content the cycle discovered; a child that reads other bytes does not verify. */+ transcript_hash: string;+ /** The cycle date the prompt gave as today (`dream_cycle_date`, the verify `checkedAt`). */+ cycle_date: string;+ /** `dream.synthesize.quote_verify`; false stamps without verifying. */+ quote_verify: boolean;+ /** #4618: the capturing seat. */+ seat?: string;+}+export interface SubagentHandlerData {/** Top-level user turn kicking off the loop. */prompt: string;@@ -627,6 +641,13 @@ export interface SubagentHandlerData {* queued by older builds, which keep the allow-list derivation.*/oneshot_task_prefixes?: string[];+ /**+ * GBRA-60: a managed dream synthesis child verifies and stamps each oneshot page against this transcript before it+ * writes it (cycle/synthesize-child-verify.ts), so a strict source commits each output once. Trusted field+ * (PROTECTED_JOB_NAMES); a delegated (remote-owned) job ignores it. Absent on jobs queued by older builds, whose+ * outputs postprocessing verifies and republishes.+ */+ dream_output?: DreamOutputSpec;/*** v0.41 Approach C: opt out of the auto-generated tool-usage preamble* that `buildSystemPrompt()` splices into `system`. Default behaviordiff --git a/src/core/ops/page-batch.ts b/src/core/ops/page-batch.tsindex c34c9f315b..5218d801fc 100644--- a/src/core/ops/page-batch.ts+++ b/src/core/ops/page-batch.ts@@ -3,6 +3,7 @@ import type { Operation } from './contract.ts';import { WRITE_REQUEST_PARAM, WRITE_WAIT_PARAM, PAGE_MUTATION_PARAMS } from '../persistence/params.ts';import { PAGE_BATCH_MAX_BYTES, PAGE_BATCH_MAX_PAGES, submitPageBatch } from '../persistence/page-batch.ts';import { pageMutationSource } from '../persistence/page-mutations.ts';+import { enforceSubagentSlugFence } from './context.ts';const put_pages: Operation = {name: 'put_pages',@@ -33,6 +34,8 @@ const put_pages: Operation = {area: 'pages',handler: async (ctx, p) => {pageMutationSource(ctx, p, 'put_pages');+ // GBRA-60: a subagent's batch (a dream synthesis child's oneshot write) is fenced per page, as put_page is.+ if (Array.isArray(p.pages)) for (const page of p.pages) if (typeof page?.slug === 'string') enforceSubagentSlugFence(ctx, page.slug, 'put_pages');if (ctx.dryRun) return { dry_run: true, action: 'put_pages', pages: Array.isArray(p.pages) ? p.pages.length : 0 };return submitPageBatch(ctx, p);},diff --git a/test/git-door-g6-synthesize.test.ts b/test/git-door-g6-synthesize.test.tsindex fb3545a37d..d46536a5d4 100644--- a/test/git-door-g6-synthesize.test.ts+++ b/test/git-door-g6-synthesize.test.ts@@ -2,13 +2,16 @@* G6 (git-canonical memory): the dream synthesis writers on a strict source.** - synthesize_concepts (synthesize-concepts.ts runPhaseSynthesizeConcepts): on a managed brain it publishes each concept- * through publishManagedConcept (concept-publication.ts), private first and then world once the provenance edges land.- * A new concept publishes database-only (`file: false`) under the derive-phase folder `concepts/`, a declared- * database-only class (DERIVE_PHASE_DB_ONLY_DEFAULTS); a concept that already has a file republishes it.+ * through publishManagedConcept (concept-publication.ts), private first and then world once the provenance edges land;+ * a world concept whose banked edges already cover every member publishes once, at world (GBRA-60), so no private+ * intermediate is committed. A new concept publishes database-only (`file: false`) under the derive-phase folder+ * `concepts/`, a declared database-only class (DERIVE_PHASE_DB_ONLY_DEFAULTS); a concept that already has a file+ * republishes it.* - synthesize quote-verify repair: verifyAndRepairDreamPages (synthesize-verify.ts) is the unmanaged branch only; a- * managed brain routes to postprocessManagedSynthesis (synthesize-postprocess.ts), driven here through the whole- * synthesize phase with a stubbed provider whose oneshot child writes three reflection pages, each carrying an- * invented quotation the repair must strip.+ * managed brain's oneshot child verifies and stamps each page before it writes them as one put_pages batch+ * (synthesize-child-verify.ts, GBRA-60), and postprocessManagedSynthesis (synthesize-postprocess.ts) then has nothing+ * to publish. Driven here through the whole synthesize phase with a stubbed provider whose oneshot child writes three+ * reflection pages, each carrying an invented quotation the repair must strip.** Target for each batch (test/helpers/strict-door-audit.ts): every filed page at HEAD with the content its row holds, a* clean tree, no git-gap census gap, and at most one commit per publication group. Runs on PGLite, and on Postgres@@ -35,7 +38,7 @@ const put = (ctx: OperationContext, slug: string, content: string) => submitPageconst NO_GAP = { database_ahead: 0, worktree_only: 0, undeclared_database_only: 0 };/** What each batch commit put in Git for one probe per path: the intermediate states history keeps after the batch. */-const commitProbe = async (root: string, audit: DoorAudit, probe: (blob: string) => unknown) =>+const commitProbe = async <T>(root: string, audit: DoorAudit, probe: (blob: string) => T) =>Promise.all(audit.commits.flatMap(commit => commit.paths.map(async path => ({ sha: commit.sha.slice(0, 8), path, probe: probe(await gitAsync(root, 'show', `${commit.sha}:${path}`).catch(() => '')) }))));/** Three concept groups: one T2 (five atoms, LLM narrative) and two T3 (two atoms each, deterministic narrative). */@@ -95,12 +98,20 @@ for (const backend of testBackends()) {expect(audit.commits.filter(commit => commit.paths.some(path => path.startsWith('concepts/')))).toEqual([]);}, { databaseUrl, setup }), 180_000);- test('three file-backed concepts republished: at HEAD, clean, no census gap, one commit per group', () => managedBrain(async ({ engine, ctx, root }) => {+ /**+ * Three file-backed world concepts a prior run wrote, republished. `banked`: the prior run's provenance edges cover+ * every member, so each concept publishes once, at world. Without them the #5525 private step comes first.+ */+ const republish = ({ banked }: { banked: boolean }) => managedBrain(async ({ engine, ctx, root }) => {await strictSource(engine);await seedAtoms(ctx);for (const slug of CONCEPTS) {await put(ctx, slug, `---\ntype: concept\ntitle: ${slug.split('/')[1]}\nsynthesized_by: synthesize_concepts-v0.41\nsynthesis_mode: llm\nmember_hash: stale-example\nvisibility: world\n---\n\nAn older narrative from source-a.\n`);}+ if (banked) {+ await engine.addLinksBatch(ATOMS.map(atom => ({ from_slug: `concepts/${atom.stem}`, to_slug: atom.slug, link_type: 'synthesized_from',+ link_source: 'concept-provenance', context: 'member atom', from_source_id: 'default', to_source_id: 'default' })));+ }await settleManagedGitEffects(engine);const seeded = [...ATOMS.map(a => a.slug), ...CONCEPTS];const baseline = await auditDoor(engine, root, { since: await headCommit(root), slugs: seeded });@@ -120,9 +131,22 @@ for (const backend of testBackends()) {await settleManagedGitEffects(engine);const audit = await auditDoor(engine, root, { since, slugs: CONCEPTS });console.log(summarizeAudit(`synthesize_concepts republish ${backend}`, audit));- console.log(`[g6-measure] synthesize_concepts republish commits ${backend}: ${JSON.stringify(await commitProbe(root, audit, blob => /^visibility: (\w+)/m.exec(blob)?.[1] ?? null))}`);+ const probes = await commitProbe(root, audit, blob => /^visibility: (\w+)/m.exec(blob)?.[1] ?? null);+ console.log(`[g6-measure] synthesize_concepts republish (${banked ? 'banked' : 'no'} edges) commits ${backend}: ${JSON.stringify(probes)}`);+ // GBRA-176: private content is never committed, so no commit in the batch holds a private concept.+ expect(probes.filter(probe => probe.probe !== 'world')).toEqual([]);expectDoorTarget(audit, engine.kind);- }, { databaseUrl, setup }), 180_000);+ }, { databaseUrl, setup });++ test('three file-backed concepts with banked provenance edges republished once at world: at HEAD, clean, no census gap, one commit per group',+ () => republish({ banked: true }), 180_000);++ // GBRA-60/GBRA-95: a file-backed world concept whose edges do not yet cover its members takes the #5525 private step;+ // on a strict source that step is a visibility transition (one door commit that removes the file and clears+ // source_path/source_uri), owned by G7a. Until G7a's transition helper lands the private step commits the private+ // page, so this stays a todo; `bun test --todo` runs it.+ test.todo('three file-backed concepts without provenance edges republished: the private step removes the file (G7a visibility transition)',+ () => republish({ banked: false }), 180_000);});describe(`[${backend}] G6: synthesize postprocess (managed quote-verify repair) on a strict source writes only through the door`, () => {@@ -176,8 +200,19 @@ for (const backend of testBackends()) {await settleManagedGitEffects(engine);const audit = await auditDoor(engine, root, { since, slugs: outputs });console.log(summarizeAudit(`synthesize postprocess ${backend}`, audit));- console.log(`[g6-measure] synthesize postprocess commits ${backend}: ${JSON.stringify(await commitProbe(root, audit, blob => ({ invented_quote_in_body: blob.slice(blob.indexOf('\n---\n', 3) + 5).includes('"an entirely invented'), dream_generated: /^dream_generated: true/m.test(blob) })))}`);+ const probes = await commitProbe(root, audit, blob => ({ invented_quote_in_body: blob.slice(blob.indexOf('\n---\n', 3) + 5).includes('"an entirely invented'), dream_generated: /^dream_generated: true/m.test(blob) }));+ console.log(`[g6-measure] synthesize postprocess commits ${backend}: ${JSON.stringify(probes)}`);console.log(summarizeAudit(`synthesize summary ${backend}`, await auditDoor(engine, root, { since, slugs: [String(result.details.summary_slug)] })));+ // GBRA-60: the child verifies and stamps before its put_page, so each output is committed once, verified and+ // stamped, and the invented quotation never reaches Git history except as its `unverified_claims` review record.+ expect(audit.pages.map(page => ({ slug: page.slug, commits: page.commits }))).toEqual(outputs.map(slug => ({ slug, commits: 1 })));+ const outputPaths = new Set(audit.pages.map(page => page.path));+ expect(probes.filter(p => outputPaths.has(p.path) && (p.probe.invented_quote_in_body || !p.probe.dream_generated))).toEqual([]);+ for (const page of audit.pages) {+ const added = (await gitAsync(root, 'log', '-p', `${since}..HEAD`, '--', page.path)).split('\n')+ .filter(line => line.startsWith('+') && line.includes('"an entirely invented') && !/^\+\s+- text: /.test(line));+ expect({ path: page.path, added }).toEqual({ path: page.path, added: [] });+ }expectDoorTarget(audit, engine.kind);}, { databaseUrl, setup }), 180_000);});diff --git a/test/helpers/managed-synthesis-fixture.ts b/test/helpers/managed-synthesis-fixture.tsindex cd6fb99074..ab41db57af 100644--- a/test/helpers/managed-synthesis-fixture.ts+++ b/test/helpers/managed-synthesis-fixture.ts@@ -2,7 +2,8 @@* The managed dream-synthesis fixture shared by test/managed-synthesis-postprocess.test.ts and the GBRA-130* pathological probes (test/pathological/a4-synthesize-postprocess.test.ts).*/-import { expect } from 'bun:test';+import { expect, spyOn } from 'bun:test';+import * as childVerify from '../../src/core/cycle/synthesize-child-verify.ts';import { randomUUID } from 'node:crypto';import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';@@ -27,9 +28,15 @@ export interface SynthesisFixture {/*** A managed source per engine with one transcript and a stubbed provider: triage scores it 0.9 and the oneshot* child writes `outputCount` reflection pages (`outputBody`, or a body with one invented quotation).+ *+ * GBRA-60: a managed child verifies and stamps its pages before writing them (synthesize-child-verify.ts), which leaves+ * postprocessing nothing to do. Unless `childVerifies` is set the fixture's child cannot verify (as a job queued by an+ * older build, or a worker that cannot read the transcript), so these probes exercise postprocessing's backstop path.*/-export async function managedSynthesisFixture(engines: BrainEngine[], run: (f: SynthesisFixture) => Promise<void>, outputCount = 1, outputBody?: string) {- for (const engine of engines) {+export async function managedSynthesisFixture(engines: BrainEngine[], run: (f: SynthesisFixture) => Promise<void>, outputCount = 1, outputBody?: string,+ childVerifies = false) {+ const unverified = childVerifies ? null : spyOn(childVerify, 'verifyChildPages').mockResolvedValue(null);+ try { for (const engine of engines) {const dir = mkdtempSync(join(tmpdir(), 'gbrain-synth-postprocess-'));const root = join(dir, 'brain');mkdirSync(root);@@ -88,7 +95,7 @@ export async function managedSynthesisFixture(engines: BrainEngine[], run: (f: Sawait engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');rmSync(dir, { recursive: true, force: true });}- }+ } } finally { unverified?.mockRestore(); }}export async function outputSlug(engine: BrainEngine, sourceId: string): Promise<string> {diff --git a/test/managed-synthesis-postprocess.test.ts b/test/managed-synthesis-postprocess.test.tsindex 5f7c814842..80b1f49fb4 100644--- a/test/managed-synthesis-postprocess.test.ts+++ b/test/managed-synthesis-postprocess.test.ts@@ -111,6 +111,21 @@ test('managed native synthesis quarantines interpretations around valid evidence}, 1, [supported, ...unsupported, 'Related context: [[people/example]].'].join('\n\n'));}, 120_000);+test('GBRA-60: a child that verifies and stamps writes each output once; postprocessing counts its repair and publishes nothing', async () => {+ await managedSynthesisFixture(engines, async ({ engine, sourceId, opts }) => {+ const report = await runPhaseSynthesize(engine, opts);+ expect(report.status).toBe('ok');+ expect((report.details.synthesis as { quote_verify: { pages_repaired: number } }).quote_verify.pages_repaired).toBe(1);+ const slug = await outputSlug(engine, sourceId);+ const page = (await engine.readPageSnapshot(slug, { sourceId }))!.page;+ expect({ stamped: page.frontmatter.dream_generated, invented: page.compiled_truth.includes('"an entirely invented') }).toEqual({ stamped: true, invented: false });+ const [{ n: versions }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2', [sourceId, slug]);+ const [{ n: postprocessed }] = await engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent->>'kind'='managed_maintenance_page'", [sourceId, slug]);+ expect({ versions, postprocessed }).toEqual({ versions: 0, postprocessed: 0 });+ }, 1, undefined, true);+}, 120_000);+/*** #6051: deterministic contention injection. Each maintenance admission for* which `contended(slug)` holds fails with the exact error real admission