Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): dream-cycle summaries record created so they pass temporal lint (#6773)
garrytancbef683042e4
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex c4ee8ac23e..08f89dbab8 100644--- a/docs/architecture/key-files/core-cycle-continued.md+++ b/docs/architecture/key-files/core-cycle-continued.md@@ -18,7 +18,7 @@ Synthesis, patterns, consolidation and connector atom gating.- `src/core/cycle/attribution-checks.ts` — #5425 [UC4]: `dream.attribution_checks` (`ATTRIBUTION_CHECKS_KEY`, registered in `KNOWN_CONFIG_KEYS`; `config set` takes a boolean word through `CYCLE_GUARDED_KEYS` in `cycle/config-guards.ts`), the one default-off switch for the two mechanical attribution checks: the propose_takes holder downgrade (`propose-takes-attribution.ts`) and the synthesis `superseded_in_source` quarantine (`synthesize-verify.ts`). `attributionChecksEnabled(engine)` is `isConfigTruthy` over the stored value and false on any read error. The default flips only on a held-out gbrain-evals receipt, the same bar as the prompt rules `dream.synthesize.attribution_rules` / `dream.propose_takes.attribution_rules`.- `src/core/cycle/propose-takes-attribution.ts` — #5425 [UC4]: `downgradeAssistantOnlyHolders(proposals, pageBody)`, called once from `propose-takes.ts` right after the extractor returns when `dream.attribution_checks` is on. `claimContentTokens` takes a claim's numeric keys (`numericClaims`: currency, scaled amounts, percents, dates, 4+ digit numbers; bare years dropped) and its quoted phrases (`extractQuoteSpans`, normalized); `statedBySpeaker` credits each token to the speakers whose turns state it, plus a speaker who explicitly accepted the previous turn. A `people/<slug>` proposal every one of whose stated tokens was stated only by `assistant` is returned with holder `brain`; a token the user stated or accepted, a claim with no tokens, tokens no turn states, a page without speaker turns, and non-person holders leave the proposal untouched. Pure: returns the input array when nothing changes. Pinned by `test/propose-takes-attribution.test.ts` (standalone) and `test/propose-takes-attribution-callsite.test.ts` (the call, `test.todo` until the wave 13 hunk lands).- `src/core/cycle/synthesize-verify-epochs.ts` — the scope side of dream-page verification, peeled move-only from `synthesize-verify.ts` (module-size ratchet) and re-exported from it: `readVerifyEpoch`, `loadChildWriteEpochs`, `loadPreRunRevision`, `isDreamOwnedPage`, `resolveVerifyPrior`, exactly as described under `synthesize-verify.ts` above. Pure database reads; no claim check lives here.-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached as verdicts: `triage-backoff.ts` upserts a score-NULL backoff marker instead and the next passes report the file `deferred` with `code: 'triage_unreliable_backoff'` (counted in `details.triage.unreliable_backoff`, not in `deferred`, so the cooldown and autopilot's maintenance stamp are not held) without a judge call until the backoff ends; nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. A phase that throws fails with `SYNTH_PHASE_FAIL`; when the throw is an `OperationError` its suggestion becomes `error.hint` and its code `details.error_code`, so a postprocess `revision_conflict` names the slug, source and revision. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`). #5145: completed synthesis is partitioned out BEFORE the triage pass on every path (classic, managed and dry run) by `partitionCompletedSynthesis` in `src/core/cycle/synthesize-completion.ts` (which also holds the legacy / synth-v2 completion-key helpers); details carry `synthesis_state: {candidates, already_synthesized}` and the triage counters cover only screened candidates.+- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached as verdicts: `triage-backoff.ts` upserts a score-NULL backoff marker instead and the next passes report the file `deferred` with `code: 'triage_unreliable_backoff'` (counted in `details.triage.unreliable_backoff`, not in `deferred`, so the cooldown and autopilot's maintenance stamp are not held) without a judge call until the backoff ends; nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index (plus `created: <summary date>`, #6773, so the summary passes temporal lint) — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. A phase that throws fails with `SYNTH_PHASE_FAIL`; when the throw is an `OperationError` its suggestion becomes `error.hint` and its code `details.error_code`, so a postprocess `revision_conflict` names the slug, source and revision. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`). #5145: completed synthesis is partitioned out BEFORE the triage pass on every path (classic, managed and dry run) by `partitionCompletedSynthesis` in `src/core/cycle/synthesize-completion.ts` (which also holds the legacy / synth-v2 completion-key helpers); details carry `synthesis_state: {candidates, already_synthesized}` and the triage counters cover only screened candidates.- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still discovered; each class is reported as one count-only stderr line. Its conversation-page section is the DB discovery (#4419): `discoverConversationPages(engine, opts)` returns the cycle source's live `type: conversation` pages (date filter on the `date` frontmatter, min_chars, exclude_patterns, `dream_generated`/`mode: lsd` and gbrain-self-session guards) as transcripts keyed `gbrain-page://<source>/<slug>` with a sha256 of the body; `withConversationPages(engine, opts, config, corpus)` appends them to the corpus list when the setting is on and drops a page whose body hash a corpus file already carries; `conversationPagesNotConsumed` returns the `conversation_pages_not_consumed` warn when synthesis is unconfigured but such pages exist. Gated by `dream.synthesize.conversation_pages` (on by default with a corpus dir, `true` opts in without one, `false` off). Pinned by `test/dream-conversation-pages.test.ts`. Each discovered corpus file carries `seat` when its session's `<sessionId>.seat.json` sidecar (`context/seat.ts`, keyed through `corpusFileSessionId`, so segments and writeback files share the session's seat) holds a valid label; the sidecar itself is never a transcript. `withTranscriptSeats` credits synthesis output refs to the seat of the transcript in their `raw_source`. Pinned by `test/transcript-discovery-seat.test.ts`. #6091: `.txt` corpus files pass through `withoutOffPeriodTurns` (capture-consent.ts), so turns captured or retired under writeback off never feed synthesis.diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 71313be0a0..be24d739ad 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -3103,10 +3103,10 @@ async function writeSummaryPage({dream_generated: true,dream_cycle_date: summaryDate,- // #4337: immutable mirror — reruns preserve the first cycle date via- // stampDreamProvenance/renderPageToMarkdown; the summary is per-date so- // both keys are simply the summary's own date.+ // #4337: immutable mirror (reruns keep the first date via stampDreamProvenance); #6773: `created` is the+ // temporal key lint requires. The summary is per-date, so each key is simply the summary's own date.dream_created_cycle_date: summaryDate,+ created: summaryDate,// #1978: deterministic index page — no source document of its own;// raw traces live on the listed pages. Explicit exemption keeps the// doctor raw_provenance check quiet.diff --git a/test/cycle-synthesize-summary-page.test.ts b/test/cycle-synthesize-summary-page.test.tsindex 8770e2c0a1..6113f4315e 100644--- a/test/cycle-synthesize-summary-page.test.ts+++ b/test/cycle-synthesize-summary-page.test.ts@@ -18,6 +18,8 @@ import { __testing } from '../src/core/cycle/synthesize.ts';import type { PageInput } from '../src/core/types.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';+import { lintContent } from '../src/commands/lint.ts';+import { parseMarkdown } from '../src/core/markdown.ts';type SummaryWriter = (engine: BrainEngine,@@ -73,6 +75,15 @@ async function renderSummary(writtenSlugs: string[]): Promise<{ body: string; ma}}+describe('dream-cycle summary temporal frontmatter (#6773)', () => {+ // Contributed by @lubosxyz (#6773): dream provenance keys are not temporal keys, so the summary failed missing-created.+ test('the summary records created as its own cycle date and passes lint', async () => {+ const { markdown } = await renderSummary(['wiki/originals/ideas/example-output']);+ expect(parseMarkdown(markdown).frontmatter.created).toBe('2026-08-20');+ expect(lintContent(markdown, 'dream-cycle-summaries/2026-08-20.md')).toEqual([]);+ });+});+describe('dream-cycle summary graph bounds (#4337)', () => {test('more than 2,000 outputs produce one deterministic bounded sample with recoverable provenance', async () => {const slugs = Array.from(