Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): back off re-judging an unreliable triage verdict instead of paying every cycle (#6069)
time-attackdd7125655c68
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex 14a74f3b99..a5af2cef04 100644--- a/docs/architecture/key-files/core-cycle-continued.md+++ b/docs/architecture/key-files/core-cycle-continued.md@@ -13,7 +13,8 @@ Synthesis, patterns, consolidation and connector atom gating.- `src/core/cycle/synthesize-verify.ts` — Mechanical claim verification on every page a synthesis child wrote (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/ellipsis/case folding, skipping markdown inline markup (`*`, backticks, `~~`; not `_`), WITH an offset map back to the original string, so every replacement is a verbatim transcript slice; a slice that differs from the quote only by that markup counts exact and is not spliced in) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). A source built with `groundSource(path, content, { tolerant: true })` (think, concepts and patterns; never dream synthesis) also reads markdown link syntax and any other square bracket as plain text (`[Name](target)`, `[Name]` and `Name` match; repairs drop link targets and never carry a `"`), folds `"` to `'`, and counts a quote exact when its words match once the writer's edge punctuation and elision, brackets (including a bracketed letter's case, `[T]he`), editorial insertions in a word (`decide[s]`, `want[ed]`) and inner quote style are set aside. Think also grounds against the user's question. `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors and standalone `[user]` / `[assistant]` / `[system]` role lines (the session-corpus renderer's turn boundaries, so a `Name:` label inside one turn never carries into the next) always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the quote length) and never accepts a match that touches a speaker label (`reason: 'crosses_speakers'`). `verifyBody` splits a body into claim units (`claimUnits`: sentences within a line, whole list items, whole table rows; no boundary inside a quote) and checks each NEW unit: every quote must ground in some source, a quote whose sentence names a transcript speaker must name the speaker of the matched turn, and every numeric/date claim (outside grounded quotes, code, wikilinks and link targets) must appear in a source (`verifyDreamPage` exempts the ISO cycle date `checkedAt`, which the synthesis prompt gave the child as today, via `verifyBody`'s `exemptNumericKeys`); a unit saying a named speaker decided, agreed, committed or will act (and recording no proposal, refusal or negation) must carry only numbers and dates that speaker stated, or that the turn they explicitly accepted stated (`numbersBySpeaker`; bare years and numbers no turn states are not attributed). Any failure removes the whole unit from the body; `verifyDreamPage` records it in frontmatter `unverified_claims` (`text`, `reason` = `quote_not_in_source` / `quote_crosses_speakers` / `speaker_mismatch` / `number_not_in_source` / `decision_misattributed`, `detail`, `sources`, `detected_at`) and records every grounded quote's source path, character span and speaker in `grounding.quotes`; records from the pre-run revision carry forward, capped at 100 / 200. Frontmatter is neither chunked nor searched, so quarantined claims stay reviewable through `get_page` but out of search, recall, think and context packs. A page whose every unit failed keeps `ALL_CLAIMS_QUARANTINED_BODY`. Scope (`verifyAndRepairDreamPages(engine, refs, transcriptsByPath, { since, sinceByTranscript, checkedAt })`): sources are the transcripts of every child that wrote the page; the page epoch is the child's first write to that page (`first_write_at` on the ref) when known, so a page another writer created while the child ran is diffed rather than treated as the run's own; otherwise the earliest `loadChildWriteEpochs` entry of its sources (child job `created_at`, so resumed or coalesced children keep their original epoch), else `since` (`readVerifyEpoch`, taken before fan-out). Pages created at or after the epoch are verified whole; older pages are verified only on units absent from their pre-epoch revision (`loadPreRunRevision`: the first `page_versions` snapshot at or after the epoch; none means the page was not overwritten → `skipped_unchanged`). Write-back goes through `importFromContent` (`noEmbed`; the phase-end embed sweep backfills) with a `beforeCommit` that re-projects timeline entries, facts, takes (`prepareCanonicalProjections` as a `preserving` writer bound to the page's current snapshot) and automatic links (`prepareAutomaticLinks`) from the verified body in the same transaction, so no derived row outlives its quarantined claim while database-only timeline history is kept. `verifyBody` skips units inside a validly marked bullet (`materializedHistoryRanges`) only when that bullet is absent from the pre-run revision, i.e. it was materialized from the database during the run; a new page gets no exemption, and a claim added under a marked bullet that already existed is verified. Fail-open per page (read-back miss / write throw → `errors` + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts`, the write-path mini-eval `test/cycle-write-path-mini-eval.test.ts`, and the three-cycle repeated-consolidation pin `test/cycle-repeated-consolidation.test.ts` (harness `test/helpers/repeated-consolidation.ts`, printable run `scripts/repeated-consolidation-experiment.ts`). System One S8: `verifyBody` also returns `groundingUnits` (new units that pass only because they carry no quote, number or attribution; ≥5 words, not headings) without changing any other field; `verifyDreamPage` returns them per body, `verifyAndRepairDreamPages` takes an optional `grounding: GroundingPass` applied before write-back, and `quarantineUnits` removes S8-rejected units into `unverified_claims` with reason `unsupported_paraphrase`. `verifyBody(…, { checks: 'quotes' })` grounds quotes and speaker attribution only (no number, date or decision checks) for writers that legitimately derive numbers. `groundAnswerQuotes` is the span-level variant for live answers. `dreamQuoteVerifyEnabled` reads `dream.quote_verify` (default on) for patterns and concepts; synthesis keeps `dream.synthesize.quote_verify` (default on). `synthesize_concepts` grounds each LLM narrative against the atom titles and bodies its prompt carried before writing (failing units to `unverified_claims`; pinned by `test/cycle/synthesize-concepts-quote-verify.test.ts`). `groundingUnits` (the opt-in S8 input) lists every substantive new passing unit (not a heading, at least five words), quoted, attributed and numeric ones included, with its final quote repairs. Pinned by `test/cycle-synthesize-grounding-coverage.test.ts`.-- `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, 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. 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/triage-backoff.ts` — Backoff for unreliable dream-triage verdicts (#6069). `runTriagePass` calls `recordUnreliableTriage` for a truncated, refused or unparseable judge response: it upserts a `dream_verdicts` marker through `putDreamVerdict` (`score` NULL, `content_type` `triage_unreliable`, reasons `unreliable:<kind>` + `attempt:<n>`, the triage model and `TRIAGE_VERSION`) and writes one stderr line with the stop reason, response length and a 12-hex sha256 prefix, never the response text. A row that is a valid verdict for the current model is kept, and a cancelled run writes nothing. `backoffUntil` defers judging while the marker for the same model and version is younger than 24h × 2^(attempt−1), capped at 7 days; `force` (`dream retriage --force`), a model change or a content-hash change re-judges at once. Every score reader (`isTriageCacheValid`, retriage, triage-decide, the rescue gate) treats the NULL score as a miss; the 30-day TTL sweep removes old markers. `TRIAGE_BACKOFF_WHY` / `TRIAGE_BACKOFF_FIX` feed `details.triage.unreliable_backoff`. Pinned by `test/synthesize-triage-backoff.test.ts`.+- `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. 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/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.mdindex 0a2d844659..77e01757fa 100644--- a/docs/guides/cron-schedule.md+++ b/docs/guides/cron-schedule.md@@ -173,6 +173,9 @@ per-transcript synthesis subagents. The dials:judging NEW files; a big cold corpus triages across a few cycles (cachedfiles are free). Deferred files are labeled "not yet triaged", neversilently rejected.+- A truncated, refused or unparseable verdict backs off (24h, doubling to+ 7 days; `triage_unreliable_backoff`) instead of being re-paid nightly;+ `gbrain dream retriage --force` re-judges now.- `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off) —opt-in backstop cap on synthesis jobs per source; 200/day is a sane valuefor busy deployments.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3a2a9efedb..325fd6dfa2 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -14,7 +14,7 @@ src/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-src/core/ai/gateway.ts 4425 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts)src/commands/sync.ts 512 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 fieldsrc/core/cycle.ts 3264 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts)-src/core/cycle/synthesize.ts 3208 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+src/core/cycle/synthesize.ts 3226 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)src/core/cycle/extract-atoms.ts 1650 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 promptsrc/core/engine.ts 2721 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 contractsrc/core/import-file.ts 2200 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +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)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex be52f660be..344517d0dc 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -292,6 +292,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.103.0', text: 'Imported transcript pages now also redact a password typed after a credential label (`password: …`, `login alice / …`) as `<REDACTED:labeled_credential>`; pages imported earlier are not rewritten, so run `gbrain transcripts audit-secrets --json` to list them (doctor `transcript_secret_exposure`).' },{ since: 'WAVE12', text: 'Dream atom and concept extraction no longer accept a model answer that stopped at the output cap or was refused (claude-cli included): such an answer counts as a failure, never as "nothing to extract" or a new concept narrative. On a managed brain the failed atom batch keeps the page\'s earlier atoms and waits for an approved retry (`gbrain jobs submit extract-atoms-drain --params \'{"sourceId":"<id>","retryRequestId":"<request>"}\'`); a concept that fails 3 times on unchanged atoms is skipped until they change (`gbrain config unset dream.concepts.failed_attempts` retries it now).' },{ since: 'WAVE12', text: 'The dream patterns breaker now counts deaths per source (`dream:patterns:source:<id>`), including runs cancelled at their timeout after paid work, so a brain whose patterns runs keep dying is refused at once after the upgrade; fix the cause, then `gbrain dream reset-key \'dream:patterns:source:<id>\'`. Pattern pages store a quarantined claim\'s reflection list once per page (`unverified_claim_sources`); the first patterns run rewrites existing pages that way (frontmatter only, no model call) before it pays for a run.' },+ { since: 'WAVE12', text: 'Dream triage no longer re-judges a transcript every cycle after a truncated, refused or unparseable verdict: it waits 24 hours, doubling per repeat up to 7 days (`triage_unreliable_backoff`), and a content or triage-model change re-judges at once; `gbrain dream retriage --force` re-judges now and pays per file.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 64df00eeab..768935186d 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -96,6 +96,7 @@ import { withChatPhase, estimateChatCostUsd } from '../ai/chat-usage.ts';import { verifyAndRepairDreamPages, normForGrounding, readVerifyEpoch, loadChildWriteEpochs, isDreamOwnedPage, type QuoteVerifyStats, type TranscriptForVerify } from './synthesize-verify.ts';import { dreamBreakerRefusal, loadDreamBreaker } from './dream-breaker.ts';import { resolveTriageDecide, type TriageDecide, type TriageDecideStats } from './triage-decide.ts';+import { backoffUntil, recordUnreliableTriage, responseDiagnostic, triageBackoffDetails, TRIAGE_UNRELIABLE_BACKOFF, type TriageDiagnostic } from './triage-backoff.ts';import { resolveGroundingDecide } from './grounding-decide.ts';import { passesTriageGate, rescueConfigOf, DEFAULT_RESCUE_FLOOR, DEFAULT_RESCUE_MIN_SEGMENTS, DEFAULT_RESCUE_CONTENT_TYPES, DEFAULT_RESCUE_CONFIG, type RescueConfig, type RescueVerdictLike } from './triage-rescue.ts';@@ -565,7 +566,7 @@ async function runPhaseSynthesizeInner(judged: pass.judged,cache_hits: pass.cacheHits,unreliable: pass.unreliable,- deferred: pass.deferred,+ deferred: pass.deferred, ...triageBackoffDetails(pass.backoff),degraded: degradedCount,below_threshold: pass.reports.filter(r => r.score !== null && !r.worth).length,// F6 spend visibility: judge-call tokens for this pass's cache MISSES@@ -583,9 +584,9 @@ async function runPhaseSynthesizeInner(rescue_fired: pass.reports.filter(r => r.rescued === true).length, ...(pass.decide ? { decide: pass.decide } : {}),};// 3A: a time-boxed cold pass must never read as mass rejection.- const deferralSuffix = pass.deferred > 0+ const deferralSuffix = (pass.deferred > 0? ` (${pass.deferred} not yet triaged — time budget; re-run or use dream retriage)`- : '';+ : '') + (pass.backoff > 0 ? ` (${pass.backoff} in unreliable-verdict backoff — dream retriage --force re-judges)` : '');// Dry-run stops here: the triage pass ran (scores cached), but no// synthesis. Codex finding #8: --dry-run does NOT mean "zero LLM calls";@@ -1986,10 +1987,12 @@ export interface TriageResult {* could be parsed out of the response. Out-of-range scores* land here deliberately — clamping would cache a* fabricated verdict.- * runTriagePass skips putDreamVerdict for these so the next cycle re-judges- * the transcript instead of permanently trusting a degenerate rejection.+ * runTriagePass never caches these as a verdict: it writes a backoff marker+ * (triage-backoff.ts) so the same input is not re-paid every cycle.*/unreliable?: 'truncated' | 'refusal' | 'unparseable';+ /** Set with `unreliable`: stop reason, length and digest of the response, never its text. */+ diagnostic?: TriageDiagnostic;/*** F6: judge-call token usage when the client surfaced it (gateway clients* do; legacy SDK-shape mocks may not). Present on degenerate results too —@@ -2127,8 +2130,10 @@ Quote verbatim; never paraphrase inside "quote".`;? { in: rawUsage.input_tokens, out: rawUsage.output_tokens }: undefined;const answeredBy = (msg as { answered_by?: string }).answered_by;- const withTokens = (r: TriageResult): TriageResult =>- ({ ...r, ...(callTokens ? { tokens: callTokens } : {}), ...(answeredBy ? { answeredBy } : {}) });+ const withTokens = (r: TriageResult): TriageResult => ({+ ...r, ...(callTokens ? { tokens: callTokens } : {}), ...(answeredBy ? { answeredBy } : {}),+ ...(r.unreliable ? { diagnostic: responseDiagnostic(stopReasonRaw, text) } : {}),+ });const refused = stopReasonRaw === 'refusal';const abnormalStop: TriageResult['unreliable'] | undefined =truncated ? 'truncated' : refused ? 'refusal' : undefined;@@ -2349,8 +2354,10 @@ export interface TriageFileReport {reasons: string[];cached: boolean;unreliable?: string;- /** True when the maxMs budget (or shouldStop) expired before this file could be judged. */+ /** True when the maxMs budget (or shouldStop) expired, or an unreliable-verdict backoff holds, before this file could be judged. */deferred?: boolean;+ /** `triage_unreliable_backoff` when a backoff marker deferred the file (counted in the pass's `backoff`, not `deferred`). */+ code?: string;}export interface TriagePassResult {@@ -2362,6 +2369,8 @@ export interface TriagePassResult {cacheHits: number;unreliable: number;deferred: number;+ /** Files skipped by an unreliable-verdict backoff marker: free, and not a budget deferral. */+ backoff: number;/** F6: summed judge-call usage across cache MISSES this pass (hits are free). */tokens: { in: number; out: number };/** S7 decide stats, present only when the slot is not off. */@@ -2412,6 +2421,7 @@ export async function runTriagePass(let cacheHits = 0;let unreliableCount = 0;let deferredCount = 0;+ let backoffCount = 0;let tokensIn = 0;let tokensOut = 0;@@ -2461,7 +2471,8 @@ export async function runTriagePass(const processLlm = async (idx: number): Promise<void> => {const t = transcripts[idx];// Cache lookup is always free — never deferred by the time budget.- const cached = cfg.force ? null : await engine.getDreamVerdict(t.filePath, t.contentHash);+ const existing = await engine.getDreamVerdict(t.filePath, t.contentHash);+ const cached = cfg.force ? null : existing;const cacheValid = cached !== null && isTriageCacheValid(cached, cfg.model, cfg.staleBefore);if (cached && cacheValid) {cacheHits++;@@ -2478,6 +2489,15 @@ export async function runTriagePass(};return;}+ const backedOffUntil = cfg.force ? null : backoffUntil(existing, cfg.model, TRIAGE_VERSION);+ if (backedOffUntil) {+ backoffCount++;+ reports[idx] = {+ filePath: t.filePath, worth: false, score: null, content_type: null, cached: false, deferred: true, code: TRIAGE_UNRELIABLE_BACKOFF,+ reasons: [`${TRIAGE_UNRELIABLE_BACKOFF}: the last judge verdict was unreliable; not re-judged before ${backedOffUntil}`],+ };+ return;+ }if (budgetExhausted()) {deferredCount++;reports[idx] = {@@ -2528,16 +2548,14 @@ export async function runTriagePass(tokensOut += triage.tokens.out;}if (triage.unreliable) {- // Degenerate judgement — do NOT write it to dream_verdicts: a cached- // rejection is permanent for this content hash, and a triage model- // that reliably truncates would silently reject every transcript- // forever. Log + skip so the next cycle re-judges.+ // Degenerate judgement — never cached as a verdict (a cached rejection+ // is permanent for this content hash). A backoff marker instead keeps+ // the next cycles from paying to re-judge the same input (#6069).unreliableCount++;- process.stderr.write(- `[dream] triage for ${t.basename} was ${triage.unreliable} ` +- `(${triage.reasons.join('; ')}); not caching in dream_verdicts — ` +- `next cycle will re-judge ${t.filePath}\n`,- );+ await recordUnreliableTriage(engine, t, triage.unreliable, triage.diagnostic, {+ existing, keepExisting: existing !== null && isTriageCacheValid(existing, cfg.model),+ model: cfg.model, triageVersion: TRIAGE_VERSION, aborted: cfg.signal?.aborted === true,+ });reports[idx] = {filePath: t.filePath,worth: false,@@ -2649,7 +2667,7 @@ export async function runTriagePass(}}- return { reports, byPath, judged, cacheHits, unreliable: unreliableCount, deferred: deferredCount, tokens: { in: tokensIn, out: tokensOut }, ...(cfg.decide ? { decide: cfg.decide.stats } : {}) };+ return { reports, byPath, judged, cacheHits, unreliable: unreliableCount, deferred: deferredCount, backoff: backoffCount, tokens: { in: tokensIn, out: tokensOut }, ...(cfg.decide ? { decide: cfg.decide.stats } : {}) };}// ── Subagent prompt ──────────────────────────────────────────────────diff --git a/src/core/cycle/triage-backoff.ts b/src/core/cycle/triage-backoff.tsnew file mode 100644index 0000000000..04f7643e92--- /dev/null+++ b/src/core/cycle/triage-backoff.ts@@ -0,0 +1,124 @@+/**+ * Backoff for unreliable significance-judge verdicts (#6069).+ *+ * A truncated, refused or unparseable judge response is never cached as a+ * verdict, but without a record the next cycle pays to judge the same+ * transcript again, every cycle. runTriagePass instead upserts a marker row+ * into `dream_verdicts` (score NULL, content_type `triage_unreliable`), so+ * `isTriageCacheValid` and every other score reader see a miss, and skips+ * re-judging that (file, content hash) under the same model and+ * TRIAGE_VERSION until the backoff for its attempt count has passed:+ * 24h × 2^(attempt−1), capped at 7 days. `force` (dream retriage --force),+ * a model change or a content change re-judges at once.+ *+ * Logs carry the stop reason, response length and a sha256 prefix of the+ * response, never the response text: it is model output about a transcript+ * and can echo transcript content.+ */+import { createHash } from 'node:crypto';+import type { Action } from '../agent-output.ts';+import type { BrainEngine, DreamVerdict, DreamVerdictInput } from '../engine.ts';++export const TRIAGE_UNRELIABLE_CONTENT_TYPE = 'triage_unreliable';+export const TRIAGE_UNRELIABLE_BACKOFF = 'triage_unreliable_backoff';++const HOUR_MS = 3_600_000;+const MAX_BACKOFF_MS = 7 * 24 * HOUR_MS;++export type UnreliableKind = 'truncated' | 'refusal' | 'unparseable';++/** What a log line may say about an unreliable judge response. */+export interface TriageDiagnostic {+ stop_reason: string;+ response_chars: number;+ sha256: string;+}++export function responseDiagnostic(stopReason: string | null | undefined, text: string): TriageDiagnostic {+ return {+ stop_reason: stopReason ?? 'none',+ response_chars: text.length,+ sha256: createHash('sha256').update(text, 'utf8').digest('hex').slice(0, 12),+ };+}++export function triageBackoffMs(attempt: number): number {+ return Math.min(24 * HOUR_MS * 2 ** (Math.max(1, attempt) - 1), MAX_BACKOFF_MS);+}++type MarkerFields = Pick<DreamVerdict, 'score' | 'content_type' | 'reasons' | 'model' | 'triage_version' | 'judged_at'>;++/** Attempt count of a backoff marker for this model and version; 0 when the row is not one. */+export function markerAttempt(row: MarkerFields | null, model: string, triageVersion: number): number {+ if (!row || row.score !== null || row.content_type !== TRIAGE_UNRELIABLE_CONTENT_TYPE) return 0;+ if (row.model !== model || row.triage_version !== triageVersion) return 0;+ const n = Number(row.reasons.find(r => r.startsWith('attempt:'))?.slice('attempt:'.length));+ return Number.isInteger(n) && n >= 1 ? n : 1;+}++/** ISO instant the row's backoff ends, or null when it does not defer judging now. */+export function backoffUntil(row: MarkerFields | null, model: string, triageVersion: number, nowMs = Date.now()): string | null {+ const attempt = markerAttempt(row, model, triageVersion);+ if (attempt === 0) return null;+ const until = Date.parse(row!.judged_at) + triageBackoffMs(attempt);+ return Number.isFinite(until) && until > nowMs ? new Date(until).toISOString() : null;+}++export function backoffMarker(kind: UnreliableKind, attempt: number, model: string, triageVersion: number): DreamVerdictInput {+ return {+ worth_processing: false,+ reasons: [`unreliable:${kind}`, `attempt:${attempt}`],+ score: null,+ content_type: TRIAGE_UNRELIABLE_CONTENT_TYPE,+ segments: [],+ entities: [],+ model,+ triage_version: triageVersion,+ };+}++/**+ * Record an unreliable verdict: upsert the next backoff marker (unless the row+ * holds a valid verdict for this model, which stays, or the run was cancelled)+ * and write the one diagnostic stderr line.+ */+export async function recordUnreliableTriage(+ engine: BrainEngine,+ t: { filePath: string; contentHash: string; basename: string },+ kind: UnreliableKind,+ diagnostic: TriageDiagnostic | undefined,+ opts: { existing: DreamVerdict | null; keepExisting: boolean; model: string; triageVersion: number; aborted: boolean },+): Promise<void> {+ const attempt = markerAttempt(opts.existing, opts.model, opts.triageVersion) + 1;+ let outcome = opts.keepExisting+ ? 'kept the existing verdict'+ : `backoff attempt ${attempt}: not re-judged for ${triageBackoffMs(attempt) / HOUR_MS}h (gbrain dream retriage --force re-judges now)`;+ if (!opts.keepExisting && !opts.aborted) {+ try {+ await engine.putDreamVerdict(t.filePath, t.contentHash, backoffMarker(kind, attempt, opts.model, opts.triageVersion));+ } catch (e) {+ outcome = `backoff marker write failed (${e instanceof Error ? e.name : 'error'}); next cycle re-judges`;+ }+ }+ const diag = diagnostic+ ? `stop_reason=${diagnostic.stop_reason}, response_chars=${diagnostic.response_chars}, sha256=${diagnostic.sha256}`+ : 'no response diagnostic';+ process.stderr.write(`[dream] triage for ${t.basename} was ${kind} (${diag}); not caching in dream_verdicts — ${outcome}\n`);+}++export const TRIAGE_BACKOFF_WHY =+ 'The judge returned a truncated, refused or unparseable verdict for this transcript, so it is not judged again until its backoff ends (24h, doubling per repeat, at most 7 days); that keeps an input the model cannot score from being paid for every cycle.';++export const TRIAGE_BACKOFF_FIX: Action = {+ argv: ['gbrain', 'dream', 'retriage', '--force'],+ consent: ['paid'],+ actor: 'agent',+ why: 'Re-judges every transcript now, ignoring cached verdicts and backoff markers; it pays for one judge call per file, so ask the user first (the preview lists the files without a judge call). A different models.dream.triage model also re-judges.',+ preview_argv: ['gbrain', 'dream', 'retriage', '--dry-run', '--json'],+ requires_exclusive: false,+};++/** `details.triage.unreliable_backoff` when any file was held by a backoff marker. */+export function triageBackoffDetails(files: number): { unreliable_backoff?: { files: number; code: string; why: string; fix: Action } } {+ return files > 0 ? { unreliable_backoff: { files, code: TRIAGE_UNRELIABLE_BACKOFF, why: TRIAGE_BACKOFF_WHY, fix: TRIAGE_BACKOFF_FIX } } : {};+}diff --git a/src/core/engine.ts b/src/core/engine.tsindex 38d2c763f0..8727b02ff7 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -481,7 +481,7 @@ export const DREAM_VERDICT_TTL_SECONDS = 30 * 86400;export interface DreamVerdictInput {worth_processing: boolean;reasons: string[];- score: number;+ score: number | null; // NULL only on a triage backoff marker (cycle/triage-backoff.ts): a miss to every readercontent_type: string | null;segments: TriageSegment[];entities: string[];diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex e396da78c9..fd7b545f1b 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -334,6 +334,7 @@ export const CODES = {timeout: { class: 'retryable', summary: "The operation did not finish within its time bound.", exit: 124 },topology_change_required: { class: 'host_only', summary: "Adding this source would replace or overlap another owner root." },transcript_secret_exposure: { class: 'unavailable', summary: "Imported conversation pages may still carry a typed credential from before the labeled-credential detector, or the last audit found some; pages are never rewritten automatically.", why: 'Re-ingest skips unchanged sessions, so pages imported before the detector keep any password typed in prose until someone reviews them.', docs: 'docs/guides/data-ingestion.md#credential-redaction', suggestion: 'Run the read-only audit to list affected slugs (never values), then review, edit or (after asking the user) remove each page, and ask the user to rotate any real credential.', fix: { argv: ['gbrain', 'transcripts', 'audit-secrets', '--json'], consent: [], actor: 'agent', why: 'Lists conversation pages that still carry a credential with hit counts per pattern; changes no page.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'transcript_secret_exposure', '--json'] } } },+ triage_unreliable_backoff: { class: 'retryable', summary: "Dream triage did not re-judge a transcript because its last judge verdict was truncated, refused or unparseable and its backoff has not ended.", why: 'An unreliable verdict is never cached, so without a backoff the same input was paid for every cycle; it waits 24h, doubling per repeat up to 7 days, and a content or triage-model change re-judges at once.', docs: 'docs/guides/error-codes.md#triage_unreliable_backoff', suggestion: 'Leave it (it is retried after the backoff), or ask the user before `gbrain dream retriage --force`, which re-judges every transcript now and pays per file.', fix: { argv: ['gbrain', 'dream', 'retriage', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Lists the transcripts that still need a verdict without any judge call, read-only.', requires_exclusive: false } },trusted_local_only: { class: 'host_only', summary: 'The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it.', legacy_error: 'permission_denied', suggestion: 'Ask the user to run the named gbrain command on the brain host.' },unavailable: { class: 'unavailable', summary: "A required dependency or capability cannot serve this request." },unexpected_file_bytes: { class: 'server', summary: "A canonical skill file mode changed outside publication." },diff --git a/test/cycle-synthesize-triage.test.ts b/test/cycle-synthesize-triage.test.tsindex 7be2c85578..04179491bd 100644--- a/test/cycle-synthesize-triage.test.ts+++ b/test/cycle-synthesize-triage.test.ts@@ -423,7 +423,11 @@ describe('runTriagePass — degrade + failure contracts', () => {const r = await runTriagePass(engine, [t], baseCfg(judge));expect(r.unreliable).toBe(1);expect(r.reports[0].unreliable).toBe('truncated');- expect(rows.size).toBe(0);+ // #6069: the only row is the backoff marker; its NULL score is never a verdict.+ const stored = [...rows.values()];+ expect(stored).toHaveLength(1);+ expect(stored[0].score).toBeNull();+ expect(stored[0].content_type).toBe('triage_unreliable');expect(r.byPath.has(t.filePath)).toBe(false);});});diff --git a/test/e2e/dream-synthesize-pglite.test.ts b/test/e2e/dream-synthesize-pglite.test.tsindex 2d5473b801..2192045669 100644--- a/test/e2e/dream-synthesize-pglite.test.ts+++ b/test/e2e/dream-synthesize-pglite.test.ts@@ -726,12 +726,21 @@ describe('E2E synthesize — degenerate verdicts are NOT cached in dream_verdict}}+ // #6069: a degenerate verdict leaves only a backoff marker (score NULL), never a cached verdict.+ function expectBackoffMarkerOnly(verdictRow: unknown, kind: string): void {+ const row = verdictRow as { score: number | null; content_type: string | null; reasons: string[] } | null;+ expect(row).not.toBeNull();+ expect(row!.score).toBeNull();+ expect(row!.content_type).toBe('triage_unreliable');+ expect(row!.reasons).toEqual([`unreliable:${kind}`, 'attempt:1']);+ }+test('truncated judge response (stop_reason=length) → no dream_verdicts row + warning', async () => {const { verdictRow, stderr } = await runWithStubbedJudge({text: '{"scor', // reasoning ate the budget; partial JSONstopReason: 'length',});- expect(verdictRow).toBeNull();+ expectBackoffMarkerOnly(verdictRow, 'truncated');expect(stderr).toMatch(/\[dream\] triage for 2026-05-01-session was truncated/);expect(stderr).toMatch(/not caching in dream_verdicts/);}, 30_000);@@ -741,7 +750,7 @@ describe('E2E synthesize — degenerate verdicts are NOT cached in dream_verdicttext: 'not json at all',stopReason: 'end',});- expect(verdictRow).toBeNull();+ expectBackoffMarkerOnly(verdictRow, 'unparseable');expect(stderr).toMatch(/\[dream\] triage for 2026-05-01-session was unparseable/);expect(stderr).toMatch(/not caching in dream_verdicts/);}, 30_000);@@ -753,7 +762,7 @@ describe('E2E synthesize — degenerate verdicts are NOT cached in dream_verdicttext: '{"worth_processing": false, "reasons": ["routine ops"]}',stopReason: 'end',});- expect(verdictRow).toBeNull();+ expectBackoffMarkerOnly(verdictRow, 'unparseable');expect(stderr).toMatch(/\[dream\] triage for 2026-05-01-session was unparseable/);}, 30_000);diff --git a/test/synthesize-triage-backoff.test.ts b/test/synthesize-triage-backoff.test.tsnew file mode 100644index 0000000000..da7adaec3a--- /dev/null+++ b/test/synthesize-triage-backoff.test.ts@@ -0,0 +1,202 @@+/**+ * #6069: an unreliable significance verdict (truncated, refused, unparseable)+ * is not re-paid every cycle. runTriagePass writes a backoff marker into+ * dream_verdicts (score NULL, content_type triage_unreliable) and skips the+ * judge for that input until the backoff ends; force, a model change and a+ * content change re-judge at once. The stderr line names the stop reason,+ * response length and a digest, never the response text.+ *+ * Regression: before the fix the unreliable verdict wrote nothing, so the+ * second pass called the judge again (the reporter's ~280 paid calls).+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { createHash } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import {+ runTriagePass,+ isTriageCacheValid,+ TRIAGE_VERSION,+ type JudgeClient,+ type TriagePassCfg,+} from '../src/core/cycle/synthesize.ts';+import { triageBackoffMs } from '../src/core/cycle/triage-backoff.ts';+import type { DiscoveredTranscript } from '../src/core/cycle/transcript-discovery.ts';++const MODEL = 'anthropic:claude-haiku-4-5-20251001';+const SECRET = 'sk-live-transcript-secret-4242';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++function transcript(name: string, content = `the user said ${SECRET} and more `.repeat(40)): DiscoveredTranscript {+ return {+ filePath: `/corpus/${name}.txt`,+ contentHash: createHash('sha256').update(content).digest('hex'),+ content,+ basename: name,+ inferredDate: null,+ };+}++function countingJudge(text: string, stopReason = 'end_turn'): JudgeClient & { calls: number } {+ const judge = {+ calls: 0,+ create: async () => {+ judge.calls++;+ return { content: [{ type: 'text', text }], stop_reason: stopReason } as never;+ },+ };+ return judge;+}++const UNPARSEABLE = `I cannot score this. The transcript mentions ${SECRET}.`;++function cfg(judge: JudgeClient, over: Partial<TriagePassCfg> = {}): TriagePassCfg {+ return { model: MODEL, maxChars: 24_000, maxTokens: 2048, threshold: 0.5, concurrency: 1, maxMs: 0, judge, ...over };+}++async function ageMarker(t: DiscoveredTranscript, hours: number): Promise<void> {+ await engine.executeRaw(+ `UPDATE dream_verdicts SET judged_at = now() - make_interval(hours => $3) WHERE file_path = $1 AND content_hash = $2`,+ [t.filePath, t.contentHash, hours],+ );+}++async function withStderr<T>(body: () => Promise<T>): Promise<{ result: T; stderr: string }> {+ const chunks: string[] = [];+ const original = process.stderr.write.bind(process.stderr);+ (process.stderr as unknown as { write: (c: unknown) => boolean }).write = (c: unknown) => { chunks.push(String(c)); return true; };+ try {+ return { result: await body(), stderr: chunks.join('') };+ } finally {+ (process.stderr as unknown as { write: typeof original }).write = original;+ }+}++describe('triage unreliable-verdict backoff (#6069)', () => {+ test('an unparseable verdict writes a marker that no reader takes as a verdict', async () => {+ const t = transcript('marker');+ const r = await runTriagePass(engine, [t], cfg(countingJudge(UNPARSEABLE)));+ expect(r.unreliable).toBe(1);+ const row = await engine.getDreamVerdict(t.filePath, t.contentHash);+ expect(row).not.toBeNull();+ expect(row!.score).toBeNull();+ expect(row!.content_type).toBe('triage_unreliable');+ expect(row!.reasons).toEqual(['unreliable:unparseable', 'attempt:1']);+ expect(row!.model).toBe(MODEL);+ expect(row!.triage_version).toBe(TRIAGE_VERSION);+ expect(row!.worth_processing).toBe(false);+ expect(isTriageCacheValid(row!, MODEL)).toBe(false);+ expect(r.byPath.has(t.filePath)).toBe(false);+ });++ test('the next pass inside the backoff makes zero judge calls and reports the file deferred', async () => {+ const t = transcript('within');+ await runTriagePass(engine, [t], cfg(countingJudge(UNPARSEABLE)));+ const judge = countingJudge('{"score": 0.9, "reasons": ["x"]}');+ const r = await runTriagePass(engine, [t], cfg(judge));+ expect(judge.calls).toBe(0);+ expect(r.judged).toBe(0);+ expect(r.backoff).toBe(1);+ expect(r.deferred).toBe(0);+ expect(r.reports[0].deferred).toBe(true);+ expect(r.reports[0].code).toBe('triage_unreliable_backoff');+ expect(r.reports[0].worth).toBe(false);+ expect(r.reports[0].reasons[0]).toContain('triage_unreliable_backoff');+ });++ test('after the backoff it re-judges, and a repeat failure doubles the backoff', async () => {+ const t = transcript('after');+ await runTriagePass(engine, [t], cfg(countingJudge(UNPARSEABLE)));+ await ageMarker(t, 25);+ const again = countingJudge(UNPARSEABLE);+ await runTriagePass(engine, [t], cfg(again));+ expect(again.calls).toBe(1);+ expect((await engine.getDreamVerdict(t.filePath, t.contentHash))!.reasons).toEqual(['unreliable:unparseable', 'attempt:2']);++ await ageMarker(t, 25);+ const third = countingJudge('{"score": 0.8, "reasons": ["x"]}');+ const held = await runTriagePass(engine, [t], cfg(third));+ expect(third.calls).toBe(0);+ expect(held.backoff).toBe(1);++ await ageMarker(t, 49);+ const r = await runTriagePass(engine, [t], cfg(third));+ expect(third.calls).toBe(1);+ expect(r.reports[0].score).toBe(0.8);+ expect((await engine.getDreamVerdict(t.filePath, t.contentHash))!.score).toBe(0.8);+ });++ test('the backoff doubles from 24h and is capped at 7 days', () => {+ expect(triageBackoffMs(1)).toBe(24 * 3_600_000);+ expect(triageBackoffMs(2)).toBe(48 * 3_600_000);+ expect(triageBackoffMs(4)).toBe(7 * 24 * 3_600_000);+ expect(triageBackoffMs(30)).toBe(7 * 24 * 3_600_000);+ });++ test('force bypasses the backoff', async () => {+ const t = transcript('force');+ await runTriagePass(engine, [t], cfg(countingJudge(UNPARSEABLE)));+ const judge = countingJudge('{"score": 0.7, "reasons": ["x"]}');+ const r = await runTriagePass(engine, [t], cfg(judge, { force: true }));+ expect(judge.calls).toBe(1);+ expect(r.backoff).toBe(0);+ expect(r.reports[0].score).toBe(0.7);+ });++ test('a model change or a content change re-judges at once', async () => {+ const t = transcript('model');+ await runTriagePass(engine, [t], cfg(countingJudge(UNPARSEABLE)));+ const other = countingJudge('{"score": 0.6, "reasons": ["x"]}');+ await runTriagePass(engine, [t], cfg(other, { model: 'openai:gpt-5.5' }));+ expect(other.calls).toBe(1);++ const u = transcript('content');+ await runTriagePass(engine, [u], cfg(countingJudge(UNPARSEABLE)));+ const edited = { ...u, content: u.content + ' edited', contentHash: createHash('sha256').update(u.content + ' edited').digest('hex') };+ const judge = countingJudge('{"score": 0.6, "reasons": ["x"]}');+ await runTriagePass(engine, [edited], cfg(judge));+ expect(judge.calls).toBe(1);+ });++ test('a failed re-judge under force keeps the existing valid verdict', async () => {+ const t = transcript('keep');+ await runTriagePass(engine, [t], cfg(countingJudge('{"score": 0.9, "reasons": ["x"]}')));+ await runTriagePass(engine, [t], cfg(countingJudge(UNPARSEABLE), { force: true }));+ const row = await engine.getDreamVerdict(t.filePath, t.contentHash);+ expect(row!.score).toBe(0.9);+ expect(isTriageCacheValid(row!, MODEL)).toBe(true);+ });++ test('the log line names stop reason, length and digest, never the response text', async () => {+ const t = transcript('log');+ const truncatedEcho = `{"score": 0.4, "reasons": ["quotes ${SECRET}"], "segments": [{"quote": "${SECRET}`;+ const { stderr } = await withStderr(() => runTriagePass(engine, [t], cfg(countingJudge(truncatedEcho, 'max_tokens'))));+ const digest = createHash('sha256').update(truncatedEcho).digest('hex').slice(0, 12);+ expect(stderr).toContain('was truncated');+ expect(stderr).toContain('stop_reason=max_tokens');+ expect(stderr).toContain(`response_chars=${truncatedEcho.length}`);+ expect(stderr).toContain(`sha256=${digest}`);+ expect(stderr).not.toContain(SECRET);++ const u = transcript('log2');+ const parsedTruncated = `{"score": 0.4, "reasons": ["echo ${SECRET}"]}`;+ const second = await withStderr(() => runTriagePass(engine, [u], cfg(countingJudge(parsedTruncated, 'max_tokens'))));+ expect(second.stderr).toContain('was truncated');+ expect(second.stderr).not.toContain(SECRET);+ });+});