Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

dream: mechanical attribution checks behind dream.attribution_checks, default off (#5425 [UC4])

garrytanea72dcb7179a
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index 72ea73ccd4..989e822710 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -11,9 +11,12 @@ Synthesis, patterns, consolidation and connector atom gating.
- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically. Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private. #5575 ENG-3: fact tiers are read per bucket and external_untrusted facts cluster in a separate pass, so an external claim never shares a take with owner facts. Each cluster's take is written at `derive:consolidate` = min(cluster fact tiers, agent_written): unmanaged, the take insert or re-promotion, consolidation marks and valid_until writeback are one `derivedMaintenanceTransaction` (a re-promotion lowers the existing take to min(existing, cluster), even a resolved one); managed, the request carries `declareDerivation`. Edges: take -> every cluster fact. The unmanaged path runs the write gate (`decideTakeWrite`, config read once per run via `loadImportSanityConfig`) on each new take at the cluster's tier: `insert` writes it and `recordFlaggedRow` in the same transaction, `hold` records a `write_gate_holds` row and leaves the facts unconsolidated, `reject` skips the cluster (`details.clusters_gate_held` / `clusters_gate_rejected`); a re-promotion inserts nothing and is not gated; managed takes are gated in takes-prepare. Clustering (`clusterFacts`): typed metric facts cluster at `cycle.consolidate.cluster_threshold` (0.85) when `claimsCompatible` (same metric, unit, period); untyped facts cluster only at `untypedClusterThreshold` (max of the configured threshold and the 0.95 explicit-duplicate bar) and never when `claimsDiverge` (a differing negation, number, date or amount token), so two event facts about different invoices or amounts stay separate and the `valid_until` writeback never expires a true fact. `details.untyped_cluster_threshold` reports the bar; a dry run adds `details.clusters` (at most 50: source, entity, would-be claim, member ids and visibility; private text only when `opts.remote === false`). Pinned by `test/trust-taint-dream.test.ts` and `test/consolidate-divergence.test.ts`.
-- `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`. #5575 I2: the unmanaged repair writeback (`verifyAndRepairDreamPages`) runs `importFromContent` inside `derivedMaintenanceTransaction` at the tier of the page's transcripts (`meetingTranscriptsDir` in opts), so a repaired page and its re-projected rows are not stamped `unknown`.
+- `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` / `superseded_in_source`, `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`. #5575 I2: the unmanaged repair writeback (`verifyAndRepairDreamPages`) runs `importFromContent` inside `derivedMaintenanceTransaction` at the tier of the page's transcripts (`meetingTranscriptsDir` in opts), so a repaired page and its re-projected rows are not stamped `unknown`. #5425 [UC4]: `verifyBody(…, { supersession: true })` (threaded from `verifyDreamPage`'s `supersession` option; `verifyAndRepairDreamPages` reads it through `attributionChecksEnabled`, the managed path in `synthesize-postprocess.ts` passes it) adds `superseded_in_source`: a unit whose grounded quote is followed, in the same transcript, by a `user` turn holding a sentence that both negates (`NEGATION_RE`) and names one of the unit's `numericClaims` keys (never a bare year) is quarantined with the retracting sentence in `detail`; only the sentence holding both counts, so a later repeat of the number or a negation of another number supersedes nothing. Absent the option the output is byte-identical. `statedBySpeaker(content, turns, extract)` is the exported general form of `numbersBySpeaker` (explicit-assent credit included) and `numericClaims` is exported for `propose-takes-attribution.ts`. Pinned by `test/cycle-synthesize-verify-superseded.test.ts`.
- `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/attribution-checks.ts` — #5425 [UC4]: `dream.attribution_checks` (`ATTRIBUTION_CHECKS_KEY`, registered in `KNOWN_CONFIG_KEYS`; `config set` takes a boolean word through `CYCLE_GUARDED_KEYS` in `cycle/config-guards.ts`), the one default-off switch for the two mechanical attribution checks: the propose_takes holder downgrade (`propose-takes-attribution.ts`) and the synthesis `superseded_in_source` quarantine (`synthesize-verify.ts`). `attributionChecksEnabled(engine)` is `isConfigTruthy` over the stored value and false on any read error. The default flips only on a held-out gbrain-evals receipt, the same bar as the prompt rules `dream.synthesize.attribution_rules` / `dream.propose_takes.attribution_rules`.
+- `src/core/cycle/propose-takes-attribution.ts` — #5425 [UC4]: `downgradeAssistantOnlyHolders(proposals, pageBody)`, called once from `propose-takes.ts` right after the extractor returns when `dream.attribution_checks` is on. `claimContentTokens` takes a claim's numeric keys (`numericClaims`: currency, scaled amounts, percents, dates, 4+ digit numbers; bare years dropped) and its quoted phrases (`extractQuoteSpans`, normalized); `statedBySpeaker` credits each token to the speakers whose turns state it, plus a speaker who explicitly accepted the previous turn. A `people/<slug>` proposal every one of whose stated tokens was stated only by `assistant` is returned with holder `brain`; a token the user stated or accepted, a claim with no tokens, tokens no turn states, a page without speaker turns, and non-person holders leave the proposal untouched. Pure: returns the input array when nothing changes. Pinned by `test/propose-takes-attribution.test.ts` (standalone) and `test/propose-takes-attribution-callsite.test.ts` (the call, `test.todo` until the wave 13 hunk lands).
+- `src/core/cycle/synthesize-verify-epochs.ts` — the scope side of dream-page verification, peeled move-only from `synthesize-verify.ts` (module-size ratchet) and re-exported from it: `readVerifyEpoch`, `loadChildWriteEpochs`, `loadPreRunRevision`, `isDreamOwnedPage`, `resolveVerifyPrior`, exactly as described under `synthesize-verify.ts` above. Pure database reads; no claim check lives here.
- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached as verdicts: `triage-backoff.ts` upserts a score-NULL backoff marker instead and the next passes report the file `deferred` with `code: 'triage_unreliable_backoff'` (counted in `details.triage.unreliable_backoff`, not in `deferred`, so the cooldown and autopilot's maintenance stamp are not held) without a judge call until the backoff ends; nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. A phase that throws fails with `SYNTH_PHASE_FAIL`; when the throw is an `OperationError` its suggestion becomes `error.hint` and its code `details.error_code`, so a postprocess `revision_conflict` names the slug, source and revision. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`). #5145: completed synthesis is partitioned out BEFORE the triage pass on every path (classic, managed and dry run) by `partitionCompletedSynthesis` in `src/core/cycle/synthesize-completion.ts` (which also holds the legacy / synth-v2 completion-key helpers); details carry `synthesis_state: {candidates, already_synthesized}` and the triage counters cover only screened candidates.
- `src/core/cycle/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/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.md
index be220576e3..9711247b0c 100644
--- a/docs/architecture/key-files/hindsight.md
+++ b/docs/architecture/key-files/hindsight.md
@@ -22,7 +22,7 @@ round-trip suite (CHECK admits unresolvable+NULL, still rejects partial+true and
unresolvable+true|false, pre-v80 NULL/NULL rows survive).
- `src/core/cycle/base-phase.ts` — abstract `BaseCyclePhase` class. Enforces `sourceScopeOpts(ctx)` threading at the type level; rules out the source-isolation leak class structurally for every new phase. Inherits source-scope, budget meter, error envelope, progress reporter. propose_takes / grade_takes / calibration_profile all extend it. `run()` honors dry-run for every subclass at once: when `opts.dryRun` or `ctx.dryRun === true`, it returns `status: 'skipped'` / `reason: 'no_dry_run_support'` before `process()` (no LLM calls, no take_proposals / take_grade_cache / calibration_profiles writes) — the same skip shape extract and resolve_symbol_edges use; runCycle threads `dryRun` into all three call sites. The ONE home of `CYCLE_DEADLINE_RESERVE_MS` (60s carved out of the enclosing job's remaining wall-clock — wait-poll + worker force-evict grace + cleanup headroom; patterns.ts re-exports it) and of `BasePhaseOpts.deadlineAtMs` (the enclosing minion job's absolute deadline, threaded via runCycle; null/unset for direct `gbrain dream` callers — phases then fall back to their derived defaults).
-- `src/core/cycle/propose-takes.ts` — LLM scans markdown prose, proposes gradeable claims to the `take_proposals` queue. Candidate discovery excludes `extract_receipt` pages before the LLM call so the phase never re-ingests its own operational receipts; nullable legacy page types remain eligible. Idempotency cache on `(source_id, page_slug, content_hash, prompt_version)` composite unique index. Fence-dedup: existing canonical takes passed to the extractor as context. Opt-in `dream.propose_takes.attribution_rules=true` adds `EXTRACT_TAKES_ATTRIBUTION_RULES` (withdrawn claims, assistant-authored judgments not attributed to the user) under prompt version suffix `+attribution5425`; off by default because it measured lower cat15 recall. Ships a stub prompt; tuned prompt arrives via the synthetic corpus build. Per-page extractor failures log a warning and continue, but a whole-run condition (per `classifyGlobalLlmError` in `src/core/ai/errors.ts`) breaks the page loop with a single combined warning line, sets `aborted_global_error`, and records a halt in the rollup — auth/billing on the first hit, bare rate_limit only after `RATE_LIMIT_HALT_STREAK` (3) consecutive hits (a successful call resets the streak). Status: `fail` when the halt happened with ZERO successful extractor calls (the whole LLM lane is down), otherwise any warnings fold into `warn` + ` (N warning(s))` summary suffix, so swallowed failures can't read as a clean `ok`. `llm_calls_succeeded`/`llm_calls_failed`/`halted` land in details. The phase wall-clock deadline is DERIVED, never a literal (a literal equal to the autopilot-cycle handler anchor, with non-co-started clocks, would make the clean `deadline_hit` partial-completion path structurally unreachable): explicit `opts.deadlineMs` wins (test seam), else `resolveProposeTakesDeadlineMs(deadlineAtMs, now)` = `PHASE_DEADLINE_FRACTION_OF_JOB` (0.8, headroom for grade_takes + calibration_profile which run after it with no deadline of their own) × (remaining job budget − `CYCLE_DEADLINE_RESERVE_MS`), clamped to the fallback (0.8 × the `autopilot-cycle` entry in `HANDLER_DEFAULT_TIMEOUT_MS` — a missing anchor throws at module LOAD, failing the whole cycle visibly). A fractioned value under `MIN_PROPOSE_TAKES_BUDGET_MS` (2 min) resolves to null and the phase returns an honest `skipped` with `reason: 'insufficient_cycle_budget'` (after the cheap provider probe, before any rollup/DB write — records neither a halt nor a completed round; next cycle retries with a fresh budget). Pinned by `test/propose-takes.test.ts` + `test/propose-takes-per-claim.test.ts` + `test/cycle-phase-deadline-drift.test.ts`. The kind vocabulary is `TAKE_KIND_VALUES` imported from `src/core/takes-fence.ts` (the fence enum — no hand-copied set); an unknown kind maps through the legacy-kind table, else `take`. `dream.propose_takes.call_timeout_ms` (whole ms 1000..300000; `config set` refuses others, a stored out-of-range value is clamped and a non-number ignored, each with a named-key phase warning) replaces the output-cap scaling for every extractor call, held to the phase time left (never below 90 s); a call its own bound stops fails per page with an error naming the key. Pinned by `test/propose-takes-config-max-tokens.test.ts` + `test/propose-takes-truncation.test.ts`.
+- `src/core/cycle/propose-takes.ts` — LLM scans markdown prose, proposes gradeable claims to the `take_proposals` queue. Candidate discovery excludes `extract_receipt` pages before the LLM call so the phase never re-ingests its own operational receipts; nullable legacy page types remain eligible. Idempotency cache on `(source_id, page_slug, content_hash, prompt_version)` composite unique index. Fence-dedup: existing canonical takes passed to the extractor as context. Opt-in `dream.propose_takes.attribution_rules=true` adds `EXTRACT_TAKES_ATTRIBUTION_RULES` (withdrawn claims, assistant-authored judgments not attributed to the user) under prompt version suffix `+attribution5425`; off by default because it measured lower cat15 recall. The mechanical holder check of #5425 [UC4] (`cycle/propose-takes-attribution.ts`, one call after the extractor returns, behind `dream.attribution_checks`, default off) is separate from the prompt rule and documented with that module. Ships a stub prompt; tuned prompt arrives via the synthetic corpus build. Per-page extractor failures log a warning and continue, but a whole-run condition (per `classifyGlobalLlmError` in `src/core/ai/errors.ts`) breaks the page loop with a single combined warning line, sets `aborted_global_error`, and records a halt in the rollup — auth/billing on the first hit, bare rate_limit only after `RATE_LIMIT_HALT_STREAK` (3) consecutive hits (a successful call resets the streak). Status: `fail` when the halt happened with ZERO successful extractor calls (the whole LLM lane is down), otherwise any warnings fold into `warn` + ` (N warning(s))` summary suffix, so swallowed failures can't read as a clean `ok`. `llm_calls_succeeded`/`llm_calls_failed`/`halted` land in details. The phase wall-clock deadline is DERIVED, never a literal (a literal equal to the autopilot-cycle handler anchor, with non-co-started clocks, would make the clean `deadline_hit` partial-completion path structurally unreachable): explicit `opts.deadlineMs` wins (test seam), else `resolveProposeTakesDeadlineMs(deadlineAtMs, now)` = `PHASE_DEADLINE_FRACTION_OF_JOB` (0.8, headroom for grade_takes + calibration_profile which run after it with no deadline of their own) × (remaining job budget − `CYCLE_DEADLINE_RESERVE_MS`), clamped to the fallback (0.8 × the `autopilot-cycle` entry in `HANDLER_DEFAULT_TIMEOUT_MS` — a missing anchor throws at module LOAD, failing the whole cycle visibly). A fractioned value under `MIN_PROPOSE_TAKES_BUDGET_MS` (2 min) resolves to null and the phase returns an honest `skipped` with `reason: 'insufficient_cycle_budget'` (after the cheap provider probe, before any rollup/DB write — records neither a halt nor a completed round; next cycle retries with a fresh budget). Pinned by `test/propose-takes.test.ts` + `test/propose-takes-per-claim.test.ts` + `test/cycle-phase-deadline-drift.test.ts`. The kind vocabulary is `TAKE_KIND_VALUES` imported from `src/core/takes-fence.ts` (the fence enum — no hand-copied set); an unknown kind maps through the legacy-kind table, else `take`. `dream.propose_takes.call_timeout_ms` (whole ms 1000..300000; `config set` refuses others, a stored out-of-range value is clamped and a non-number ignored, each with a named-key phase warning) replaces the output-cap scaling for every extractor call, held to the phase time left (never below 90 s); a call its own bound stops fails per page with an error naming the key. Pinned by `test/propose-takes-config-max-tokens.test.ts` + `test/propose-takes-truncation.test.ts`.
- `src/core/cycle/grade-takes.ts` — walks unresolved takes older than 6 months, retrieves evidence, asks judge model, caches verdict. Auto-resolve DISABLED by default. Conservative thresholds: >=0.95 single OR >=0.85 ensemble 3/3 unanimous. `aggregateEnsemble` reuses the cross-modal substrate; fires on the borderline 0.6-0.95 band. Writes to `take_grade_cache`. Same global-error posture as propose-takes: a judge failure that classifies as a whole-run condition breaks the take loop with `aborted_global_error` (auth/billing first hit; rate_limit after 3 consecutive takes; `fail` status when zero judge calls succeeded, else `warn` + warning count; `judge_calls_succeeded`/`judge_calls_failed`/`halted` in details). Rejected ensemble judges are classified the same way — `Promise.allSettled` never flattens a revoked key or exhausted spend limit into a silent null verdict. Per-take auto-apply failures stay per-take.
- `src/core/cycle/calibration-profile.ts` — aggregates resolved takes into 2-4 narrative pattern statements + active bias tags. Voice-gated via `gateVoice()`. Cold-brain skip when <5 resolved. Writes to `calibration_profiles` with audit columns (`voice_gate_passed`, `voice_gate_attempts`, `grade_completion`).
- `src/core/calibration/voice-gate.ts` — single `gateVoice()` function, mode parameter (`pattern_statement` | `nudge` | `forecast_blurb` | `dashboard_caption` | `morning_pulse`). 2 regens then template fallback from `src/core/calibration/templates.ts`. Haiku judge with mode-specific rubrics; all rubrics structurally forbid clinical/preachy voice.
diff --git a/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.md
index 207c294448..bec67735dd 100644
--- a/docs/guides/cron-schedule.md
+++ b/docs/guides/cron-schedule.md
@@ -166,6 +166,24 @@ per-transcript synthesis subagents. The dials:
Pages that already existed are checked only on the sentences this run
added. The off switch is the incident escape hatch; telemetry lands in
`details.synthesis.quote_verify`.
+- `dream.synthesize.attribution_rules` and `dream.propose_takes.attribution_rules`
+ (default off) — extra prompt rules from #5425: keep who proposed what and
+ later corrections explicit; an assistant-authored judgment is not the
+ user's. Off because matched runs measured no benefit (propose-takes F1
+ 0.896 → 0.876); a brain that wants them opts in per phase.
+- `dream.attribution_checks` (default off; `true` or `false`) — the two
+ mechanical attribution checks of #5425 that need the same held-out
+ measurement before they can change defaults. On, `propose_takes` stores a
+ proposal held by `people/<slug>` as held by `brain` when its numbers, dates
+ and quoted phrases appear only in assistant turns of the page and no user
+ turn states or explicitly accepts any of them (a page without speaker turns
+ is left alone), and the synthesis claim check adds `superseded_in_source`:
+ a sentence whose grounded quote a later user turn takes back in a sentence
+ that negates and names the same number or date moves to
+ `unverified_claims`; a later sentence that only repeats the number, or
+ negates a different one, changes nothing. Off, every page and proposal is
+ byte-identical to a release without the checks. One switch, both checks:
+ `gbrain config set dream.attribution_checks true`.
- `dream.synthesize.max_turns` (default 16) — synthesis turn budget for
agentic children and oneshot fallbacks (the default oneshot path — see
the next section — is a single completion and never spends turns). The
@@ -269,11 +287,13 @@ Three more fields answer "what did that cost and did it land":
- `quote_verify` — what the post-write claim check touched: quotes checked
and repaired, sentences quarantined (with counts per reason:
`quote_not_in_source`, `quote_crosses_speakers`, `speaker_mismatch`,
- `number_not_in_source`, `decision_misattributed`), pre-existing pages
+ `number_not_in_source`, `decision_misattributed`, and, with
+ `dream.attribution_checks` on, `superseded_in_source`), pre-existing pages
checked by diff, and unbalanced paragraphs. `decision_misattributed` is a
sentence saying a speaker decided, agreed or will do something whose
numbers or dates only another speaker stated and the named speaker never
- explicitly accepted.
+ explicitly accepted. `superseded_in_source` is a sentence whose quote a
+ later user turn took back on the same number or date.
Per-call spend also lands in the `chat_usage_log` ledger with a phase tag:
the orchestrator's own calls under `phase:synthesize`, each drained child
diff --git a/llms-full.txt b/llms-full.txt
index 60717e6980..e4523c066b 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7361,6 +7361,24 @@ per-transcript synthesis subagents. The dials:
Pages that already existed are checked only on the sentences this run
added. The off switch is the incident escape hatch; telemetry lands in
`details.synthesis.quote_verify`.
+- `dream.synthesize.attribution_rules` and `dream.propose_takes.attribution_rules`
+ (default off) — extra prompt rules from #5425: keep who proposed what and
+ later corrections explicit; an assistant-authored judgment is not the
+ user's. Off because matched runs measured no benefit (propose-takes F1
+ 0.896 → 0.876); a brain that wants them opts in per phase.
+- `dream.attribution_checks` (default off; `true` or `false`) — the two
+ mechanical attribution checks of #5425 that need the same held-out
+ measurement before they can change defaults. On, `propose_takes` stores a
+ proposal held by `people/<slug>` as held by `brain` when its numbers, dates
+ and quoted phrases appear only in assistant turns of the page and no user
+ turn states or explicitly accepts any of them (a page without speaker turns
+ is left alone), and the synthesis claim check adds `superseded_in_source`:
+ a sentence whose grounded quote a later user turn takes back in a sentence
+ that negates and names the same number or date moves to
+ `unverified_claims`; a later sentence that only repeats the number, or
+ negates a different one, changes nothing. Off, every page and proposal is
+ byte-identical to a release without the checks. One switch, both checks:
+ `gbrain config set dream.attribution_checks true`.
- `dream.synthesize.max_turns` (default 16) — synthesis turn budget for
agentic children and oneshot fallbacks (the default oneshot path — see
the next section — is a single completion and never spends turns). The
@@ -7464,11 +7482,13 @@ Three more fields answer "what did that cost and did it land":
- `quote_verify` — what the post-write claim check touched: quotes checked
and repaired, sentences quarantined (with counts per reason:
`quote_not_in_source`, `quote_crosses_speakers`, `speaker_mismatch`,
- `number_not_in_source`, `decision_misattributed`), pre-existing pages
+ `number_not_in_source`, `decision_misattributed`, and, with
+ `dream.attribution_checks` on, `superseded_in_source`), pre-existing pages
checked by diff, and unbalanced paragraphs. `decision_misattributed` is a
sentence saying a speaker decided, agreed or will do something whose
numbers or dates only another speaker stated and the named speaker never
- explicitly accepted.
+ explicitly accepted. `superseded_in_source` is a sentence whose quote a
+ later user turn took back on the same number or date.
Per-call spend also lands in the `chat_usage_log` ledger with a phase tag:
the orchestrator's own calls under `phase:synthesize`, each drained child
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index 4fd946fb5b..3f19960e60 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -53,6 +53,7 @@ const ALLOWLIST = new Map([
// string in a reviewer-visible edit. Modules reached from `scripts/**` carry
// reason 'script-reachable', which the guard verifies.
const PERMITTED_TEST_ONLY = [
+ { path: 'src/core/cycle/propose-takes-attribution.ts', reason: 'held: #5425 [UC4] mechanical holder check; its one call in propose-takes.ts is a wave 14 PR3 stack hunk behind wave 13 PR3 #6446 (remove this entry when it lands)' },
{ path: 'src/core/bootstrap/template-repo.ts', reason: 'script-reachable' },
{ path: 'src/eval/longmemeval/diagnostics.ts', reason: 'script-reachable' },
{ path: 'src/eval/longmemeval/evidence-brief.ts', reason: 'held: eval-only wave 1 brief builder (10x memory advantage plan A3), loaded by path from gbrain-evals eval/runner/pilot; product wiring is plan item A8, conditional on the A5 pilot' },
diff --git a/src/core/config.ts b/src/core/config.ts
index 72aef0f374..239c036bba 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1522,7 +1522,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'dream.synthesize.link_manifest',
'dream.synthesize.quote_verify',
'dream.quote_verify',
- 'think.quote_verify',
+ 'think.quote_verify', 'dream.attribution_checks', // #5425 [UC4] mechanical attribution checks, default off (cycle/attribution-checks.ts)
'dream.synthesize.inline_concurrency',
// #4152 triage knobs. The triage model's preferred key is
// `models.dream.triage` (models.* prefix, registered via the models.dream.*
diff --git a/src/core/cycle/attribution-checks.ts b/src/core/cycle/attribution-checks.ts
new file mode 100644
index 0000000000..d43326fe69
--- /dev/null
+++ b/src/core/cycle/attribution-checks.ts
@@ -0,0 +1,37 @@
+/**
+ * #5425 [UC4]: the one switch for the two mechanical attribution checks that
+ * wave 14 ships off by default, `dream.attribution_checks`:
+ *
+ * - `propose-takes-attribution.ts`: a proposal held by a person whose numbers,
+ * dates and quoted phrases only assistant turns of the page state is held by
+ * `brain` instead (a turn the user explicitly accepted still counts as the
+ * user's).
+ * - `synthesize-verify.ts` `superseded_in_source`: a synthesized sentence whose
+ * grounded quote a later user turn negates on the same number or date is
+ * quarantined to `unverified_claims`.
+ *
+ * Both change recall and attribution the way the opt-in prompt rules
+ * (`dream.synthesize.attribution_rules`, `dream.propose_takes.attribution_rules`)
+ * do, so the default flips only on a held-out gbrain-evals receipt. Off, every
+ * output is byte-identical to the release before the checks existed.
+ */
+import { isConfigTruthy } from '../config.ts';
+
+export const ATTRIBUTION_CHECKS_KEY = 'dream.attribution_checks';
+
+const FALSE_WORDS = new Set(['false', '0', 'no', 'off']);
+
+/** `config set` validation: the boolean a value means, or null when it means neither. */
+export function parseAttributionChecks(raw: string): boolean | null {
+ if (isConfigTruthy(raw)) return true;
+ return FALSE_WORDS.has(raw.trim().toLowerCase()) ? false : null;
+}
+
+/** Unset, unreadable or not a true word: off. A config lookup never stops a phase. */
+export async function attributionChecksEnabled(engine: { getConfig?(key: string): Promise<string | null> }): Promise<boolean> {
+ try {
+ return isConfigTruthy(await engine.getConfig?.(ATTRIBUTION_CHECKS_KEY));
+ } catch {
+ return false;
+ }
+}
diff --git a/src/core/cycle/config-guards.ts b/src/core/cycle/config-guards.ts
index 6db861e81b..de31a9893a 100644
--- a/src/core/cycle/config-guards.ts
+++ b/src/core/cycle/config-guards.ts
@@ -1,18 +1,31 @@
/**
* Fix wave 11 `config set` guards for cycle keys that are not numeric phase
* knobs (those live in phase-config-values.ts): `cycle.lint_exclude` refuses
- * a path (#6134), and `dream.patterns.last_run` is state the patterns phase
- * records, so it can only be unset (#6177). Each throws an `invalid_params`
+ * a path (#6134), `dream.patterns.last_run` is state the patterns phase
+ * records, so it can only be unset (#6177), and `dream.attribution_checks`
+ * takes a boolean word (#5425). Each throws an `invalid_params`
* OperationError whose fix is a real command; nothing is written.
*/
import { opError } from '../ops/contract.ts';
import { CYCLE_LINT_EXCLUDE_KEY, parseCycleLintExclude } from './lint-fix-setting.ts';
import { PATTERNS_LAST_RUN_KEY } from './patterns-plan.ts';
+import { ATTRIBUTION_CHECKS_KEY, parseAttributionChecks } from './attribution-checks.ts';
-export const CYCLE_GUARDED_KEYS: readonly string[] = [CYCLE_LINT_EXCLUDE_KEY, PATTERNS_LAST_RUN_KEY];
+export const CYCLE_GUARDED_KEYS: readonly string[] = [CYCLE_LINT_EXCLUDE_KEY, PATTERNS_LAST_RUN_KEY, ATTRIBUTION_CHECKS_KEY];
export function assertCycleConfigValue(key: string, value: string): void {
if (key === CYCLE_LINT_EXCLUDE_KEY) { parseCycleLintExclude(value); return; }
+ if (key === ATTRIBUTION_CHECKS_KEY) {
+ if (parseAttributionChecks(value) !== null) return;
+ throw opError('invalid_params', `Invalid ${ATTRIBUTION_CHECKS_KEY}: expected true or false.`,
+ `Set ${ATTRIBUTION_CHECKS_KEY} to true or false (default: false), or unset it to use the default.`, {
+ why: 'The dream phases read this switch on every run and would treat any other word as off. Nothing was written.',
+ fix: { argv: ['gbrain', 'config', 'set', ATTRIBUTION_CHECKS_KEY, '<VALUE>'],
+ inputs: [{ name: 'VALUE', how: 'true or false; ask the user when unclear.' }], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Turns the mechanical attribution checks on or off for the next dream run.',
+ verify: { argv: ['gbrain', 'config', 'get', ATTRIBUTION_CHECKS_KEY] } },
+ });
+ }
if (key !== PATTERNS_LAST_RUN_KEY) return;
throw opError('invalid_params', `${PATTERNS_LAST_RUN_KEY} is recorded by the patterns phase and cannot be set.`,
`To forget the recorded run cost, unset it: gbrain config unset ${PATTERNS_LAST_RUN_KEY}`, {
diff --git a/src/core/cycle/propose-takes-attribution.ts b/src/core/cycle/propose-takes-attribution.ts
new file mode 100644
index 0000000000..ecff7438dc
--- /dev/null
+++ b/src/core/cycle/propose-takes-attribution.ts
@@ -0,0 +1,68 @@
+/**
+ * #5425 [UC4]: mechanical holder check for propose_takes, behind
+ * `dream.attribution_checks` (default off; `cycle/attribution-checks.ts`).
+ *
+ * The extractor may hand a judgment the assistant made to `people/<slug>`.
+ * The one part of that a mechanical check can test is the claim's content
+ * tokens: its numbers and dates (`numericClaims`, so currency, scaled amounts,
+ * percents, dates and 4+ digit numbers, never a bare year) and its quoted
+ * phrases. When every token some speaker of the page states was stated only
+ * in assistant turns, and no user (or other human) turn states or explicitly
+ * accepts any of them, the proposal is held by `brain` instead. A turn the
+ * user accepted in the very next turn counts as the user's
+ * (`statedBySpeaker`, the same credit `decision_misattributed` gives), so a
+ * real decision after "yes, do that" keeps its person.
+ *
+ * A page without speaker turns (a synthesized wiki page, a note), a claim
+ * without content tokens, and tokens no turn states are left alone: without
+ * evidence of who said what there is nothing mechanical to decide. The one
+ * call sits in `propose-takes.ts`, right after the extractor returns.
+ */
+import { extractQuoteSpans, numericClaims, numericFacts, normForGrounding, parseSpeakerTurns, speakerKey, statedBySpeaker, YEAR_KEY_RE } from './synthesize-verify.ts';
+
+export interface HolderCheckInput { claim_text: string; holder: string }
+
+const PERSON_HOLDER_RE = /^people\//;
+
+/** The claim's content tokens: canonical numeric keys (no bare years) and normalized quoted phrases. */
+export function claimContentTokens(claim: string): string[] {
+ const numbers = numericClaims(claim).flatMap(({ keys }) => keys).filter(k => !YEAR_KEY_RE.test(k));
+ const phrases = extractQuoteSpans(claim).spans.map(sp => `q:${normForGrounding(sp.inner)}`);
+ return [...new Set([...numbers, ...phrases])];
+}
+
+function tokensIn(text: string, phrases: string[]): Set<string> {
+ const norm = normForGrounding(text);
+ const found = new Set<string>(numericFacts(text));
+ for (const p of phrases) if (norm.includes(p.slice(2))) found.add(p);
+ return found;
+}
+
+/**
+ * The proposals with every assistant-only person attribution downgraded to
+ * `brain`. Pure; the input array and its objects are not mutated. Returns the
+ * same array when nothing changes.
+ */
+export function downgradeAssistantOnlyHolders<T extends HolderCheckInput>(proposals: T[], pageBody: string): T[] {
+ const turns = parseSpeakerTurns(pageBody);
+ if (turns.length === 0 || !proposals.some(p => PERSON_HOLDER_RE.test(p.holder))) return proposals;
+ const phrases = proposals.flatMap(p => claimContentTokens(p.claim_text)).filter(t => t.startsWith('q:'));
+ const stated = statedBySpeaker(pageBody, turns, text => tokensIn(text, phrases));
+ const assistantOnly = (token: string): boolean | null => {
+ let byAssistant = false, byOther = false;
+ for (const [speaker, tokens] of stated) {
+ if (!tokens.has(token)) continue;
+ if (speaker === speakerKey('assistant')) byAssistant = true; else byOther = true;
+ }
+ return byOther ? false : byAssistant ? true : null;
+ };
+ let changed = false;
+ const out = proposals.map(p => {
+ if (!PERSON_HOLDER_RE.test(p.holder)) return p;
+ const verdicts = claimContentTokens(p.claim_text).map(assistantOnly).filter((v): v is boolean => v !== null);
+ if (verdicts.length === 0 || verdicts.includes(false)) return p;
+ changed = true;
+ return { ...p, holder: 'brain' };
+ });
+ return changed ? out : proposals;
+}
diff --git a/src/core/cycle/synthesize-verify.ts b/src/core/cycle/synthesize-verify.ts
index 0ee582c7fe..1d36d02d15 100644
--- a/src/core/cycle/synthesize-verify.ts
+++ b/src/core/cycle/synthesize-verify.ts
@@ -71,6 +71,7 @@ import { normalizePageFences } from '../fence-repair/import-step.ts';
import { prepareAutomaticLinks } from '../persistence/links-preparation.ts';
import { isAutoLinkEnabled } from '../link-extraction.ts';
import { resolveCycleDate, utcDate } from './cycle-date.ts';
+import { attributionChecksEnabled } from './attribution-checks.ts';
import { resolveVerifyPrior } from './synthesize-verify-epochs.ts';
export { readVerifyEpoch, loadChildWriteEpochs, loadPreRunRevision, isDreamOwnedPage, resolveVerifyPrior } from './synthesize-verify-epochs.ts';
@@ -152,6 +153,8 @@ export interface QuoteVerifyStats {
number_not_in_source: number;
/** A speaker's decision or commitment whose numbers/dates only another speaker stated (#5425). */
decision_misattributed: number;
+ /** A sentence whose grounded quote a later user turn took back on the same number or date (#5425 [UC4]; `dream.attribution_checks`). */
+ superseded_in_source: number;
skipped_no_transcript: number;
/** Pages where read-back or write-back failed (fail-open, logged). */
errors: number;
@@ -175,6 +178,7 @@ export function emptyQuoteVerifyStats(): QuoteVerifyStats {
speaker_mismatch: 0,
number_not_in_source: 0,
decision_misattributed: 0,
+ superseded_in_source: 0,
skipped_no_transcript: 0,
errors: 0,
};
@@ -552,22 +556,33 @@ export function numericFacts(text: string): Set<string> {
/** A turn that opens by accepting the previous turn's proposal. */
const ACCEPTANCE_RE = /^\W*(?:yes|yep|yeah|sure|ok(?:ay)?|agreed|sounds good|perfect|great|do (?:it|that)|go ahead|let'?s do (?:it|that)|approved)\b/i;
-function numbersBySpeaker(content: string, turns: SpeakerTurn[]): Map<string, Set<string>> {
+/**
+ * What each speaker stated, by speaker key: the tokens `extract` finds in the
+ * speaker's own turns, plus those of a turn by someone else that the speaker
+ * explicitly accepted in the very next turn (#5425: "yes, do that" makes the
+ * assistant's numbers the user's). `numbersBySpeaker` is the numeric form;
+ * `propose-takes-attribution.ts` passes its own token extractor.
+ */
+export function statedBySpeaker(content: string, turns: SpeakerTurn[], extract: (text: string) => Iterable<string>): Map<string, Set<string>> {
const out = new Map<string, Set<string>>();
- let previous: { key: string; numbers: Set<string> } | null = null;
+ let previous: { key: string; tokens: Set<string> } | null = null;
turns.forEach((turn, i) => {
const text = content.slice(turn.labelEnd, turns[i + 1]?.labelStart ?? content.length);
const key = speakerKey(turn.speaker);
- const numbers = numericFacts(text);
+ const tokens = new Set(extract(text));
const own = out.get(key) ?? new Set<string>();
- for (const n of numbers) own.add(n);
- if (previous && previous.key !== key && ACCEPTANCE_RE.test(text)) for (const n of previous.numbers) own.add(n);
+ for (const n of tokens) own.add(n);
+ if (previous && previous.key !== key && ACCEPTANCE_RE.test(text)) for (const n of previous.tokens) own.add(n);
out.set(key, own);
- previous = { key, numbers };
+ previous = { key, tokens };
});
return out;
}
+function numbersBySpeaker(content: string, turns: SpeakerTurn[]): Map<string, Set<string>> {
+ return statedBySpeaker(content, turns, numericFacts);
+}
+
/** Prepare one transcript for verification. */
export function groundSource(path: string, content: string, opts: { tolerant?: boolean } = {}): GroundedSource {
const { norm, map } = normalizeForGrounding(content, { tolerant: opts.tolerant });
@@ -809,8 +824,8 @@ const NUMERIC_CLAIM_RES: Array<{ re: RegExp; key: (m: RegExpMatchArray) => strin
{ re: /\b\d{1,3}(?:,\d{3})+(?:\.\d+)?\b|\b\d{4,}\b/g, key: m => [canonNumber(Number.parseFloat(m[0].replace(/,/g, '')))] },
];
-/** Numeric and date claims in `text`, each once, with its canonical keys. */
-function numericClaims(text: string): Array<{ raw: string; claim: string; keys: string[] }> {
+/** Numeric and date claims in `text` (currency, scaled amounts, percents, dates, 4+ digit numbers), each once, with its canonical keys. */
+export function numericClaims(text: string): Array<{ raw: string; claim: string; keys: string[] }> {
const out: Array<{ raw: string; claim: string; keys: string[] }> = [];
const seen = new Set<string>();
const covered: Array<[number, number]> = [];
@@ -850,7 +865,7 @@ const DECISION_RE = /\b(?:decid(?:e|ed|es)|agree(?:d|s)?|accept(?:ed|s)?|approv(
/** A unit that records a proposal, a refusal or a negation is not asserting agreement. */
const PROPOSAL_OR_REFUSAL_RE = /\b(?:(?:suggest|propos|recommend|offer|advis|declin|reject|refus)\w*|turned down|instead|rather than|not|no|never)\b|n't\b/i;
/** A bare year names when, not what was decided; it is never attributed. */
-const YEAR_KEY_RE = /^(?:19|20|21)\d\d$/;
+export const YEAR_KEY_RE = /^(?:19|20|21)\d\d$/;
/**
* #5425: numbers and dates in a decision claim that some speaker stated but
@@ -869,6 +884,42 @@ function misattributedDecisionClaims(text: string, attribution: string, sources:
.map(({ raw }) => raw);
}
+/** A user sentence that takes something back: a negation or a correction word. */
+const NEGATION_RE = /\b(?:not|no|never|nope|instead|rather than|scratch that|forget (?:it|that)|cancel\w*|drop(?:ped)? (?:it|that)|no longer|changed (?:my|our) mind|withdr\w+|retract\w*|revers\w+|wrong|incorrect|correction)\b|n't\b/i;
+const SENTENCE_SPLIT_RE = /(?<=[.!?])\s+|\n+/;
+
+/**
+ * #5425 [UC4] `superseded_in_source`: the numbers and dates a unit carries
+ * that a user turn later in the same transcript, after the turn the unit's
+ * grounded quote came from, takes back in a sentence that negates and names
+ * that same number or date. Only `user` turns count (role-labelled
+ * transcripts), only the sentence holding both the negation and the number,
+ * never a bare year, so a later sentence that merely repeats a number, or
+ * negates a different one, supersedes nothing.
+ */
+function supersededClaims(text: string, grounded: Array<{ source: GroundedSource; start: number }>): string[] {
+ const claims = numericClaims(text).filter(({ keys }) => !keys.every(k => YEAR_KEY_RE.test(k)));
+ if (claims.length === 0) return [];
+ const out: string[] = [];
+ for (const { source, start } of grounded) {
+ if (source.turns.length === 0) continue;
+ const from = turnIndexAt(source.turns, start);
+ for (let i = from + 1; i < source.turns.length; i++) {
+ const turn = source.turns[i];
+ if (speakerKey(turn.speaker) !== 'user') continue;
+ const turnText = source.content.slice(turn.labelEnd, source.turns[i + 1]?.labelStart ?? source.content.length);
+ for (const sentence of turnText.split(SENTENCE_SPLIT_RE)) {
+ if (!NEGATION_RE.test(sentence)) continue;
+ const stated = numericFacts(sentence);
+ for (const { raw, keys } of claims) {
+ if (keys.some(k => stated.has(k)) && !out.some(o => o.startsWith(`${raw} `))) out.push(`${raw} was later taken back by the user: ${clip(sentence.trim(), 120)}`);
+ }
+ }
+ }
+ }
+ return out;
+}
+
const LIST_MARKER_RE = /^(?:[-*+]|\d+[.)]|>|#{1,6})[ \t]+/;
const EMPTY_LINE_AFTER_REMOVAL_RE = /^\s*(?:[-*+]|\d+[.)]|>|#{1,6})?\s*$/;
const REMOVED = '\uFFFF';
@@ -918,7 +969,7 @@ export function claimUnits(body: string, spans: Array<{ start: number; end: numb
return units;
}
-export type ClaimFailure = 'quote_not_in_source' | 'quote_crosses_speakers' | 'speaker_mismatch' | 'number_not_in_source' | 'decision_misattributed';
+export type ClaimFailure = 'quote_not_in_source' | 'quote_crosses_speakers' | 'speaker_mismatch' | 'number_not_in_source' | 'decision_misattributed' | 'superseded_in_source';
export interface QuarantinedClaim {
text: string;
@@ -1030,10 +1081,12 @@ function clip(s: string, n = PROVENANCE_TEXT_CHARS): string {
* their speaker attribution only (no number, date or decision checks), for
* writers whose prose legitimately derives numbers from its sources.
*/
-export function verifyBody(body: string, sources: GroundedSource[], opts: { priorNorm?: string; checks?: 'all' | 'quotes'; exemptNumericKeys?: ReadonlySet<string> } = {}): BodyVerification {
+export function verifyBody(body: string, sources: GroundedSource[], opts: { priorNorm?: string; checks?: 'all' | 'quotes'; exemptNumericKeys?: ReadonlySet<string>;
+ /** #5425 [UC4]: also quarantine `superseded_in_source` units (`dream.attribution_checks`; off: no change). */
+ supersession?: boolean } = {}): BodyVerification {
const { spans, unbalanced } = extractQuoteSpans(body);
const masked = maskNonProse(body);
- const failures: Record<ClaimFailure, number> = { quote_not_in_source: 0, quote_crosses_speakers: 0, speaker_mismatch: 0, number_not_in_source: 0, decision_misattributed: 0 };
+ const failures: Record<ClaimFailure, number> = { quote_not_in_source: 0, quote_crosses_speakers: 0, speaker_mismatch: 0, number_not_in_source: 0, decision_misattributed: 0, superseded_in_source: 0 };
const edits: Array<{ start: number; end: number; text: string }> = [];
const quarantined: QuarantinedClaim[] = [];
const provenance: QuoteProvenance[] = [];
@@ -1061,6 +1114,7 @@ export function verifyBody(body: string, sources: GroundedSource[], opts: { prio
const fail = (reason: ClaimFailure, detail: string) => { failures[reason]++; unitFailures.push({ reason, detail }); };
const unitEdits: typeof edits = [];
const unitProvenance: QuoteProvenance[] = [];
+ const grounded: Array<{ source: GroundedSource; start: number }> = [];
for (const sp of unitSpans) {
quotes++;
const g = groundAcross(sp.inner, sources);
@@ -1087,6 +1141,7 @@ export function verifyBody(body: string, sources: GroundedSource[], opts: { prio
span: result.spans[0],
speaker: speakers[0] ?? null,
});
+ grounded.push({ source, start: result.spans[0][0] });
}
const unquoted = blank(masked.slice(u.start, u.end), quoteRanges);
// Quotes-only mode (answers that legitimately compute numbers): no number or decision checks.
@@ -1096,6 +1151,7 @@ export function verifyBody(body: string, sources: GroundedSource[], opts: { prio
for (const n of misattributedDecisionClaims(unquoted, attribution, sources, [...mentioned.keys()])) {
fail('decision_misattributed', `${[...mentioned.values()].join(', ')}: ${n} was stated only by another speaker`);
}
+ if (opts.supersession) for (const n of supersededClaims(masked.slice(u.start, u.end), grounded)) fail('superseded_in_source', n);
}
if (unitFailures.length > 0) {
@@ -1189,13 +1245,15 @@ export interface GroundingPass {
export function verifyDreamPage(
page: VerifiablePage,
sources: GroundedSource[],
- opts: { prior: VerifiablePage | null; checkedAt: string },
+ opts: { prior: VerifiablePage | null; checkedAt: string;
+ /** #5425 [UC4]: `attributionChecksEnabled(engine)`; absent or false leaves the output unchanged. */
+ supersession?: boolean },
stats: QuoteVerifyStats,
): VerifiedDreamPage {
const priorNorm = opts.prior ? normForGrounding(`${opts.prior.compiled_truth}\n${opts.prior.timeline ?? ''}`) : undefined;
const exemptNumericKeys = new Set([`date:${opts.checkedAt}`]);
- const truth = verifyBody(page.compiled_truth ?? '', sources, { priorNorm, exemptNumericKeys });
- const timeline = verifyBody(page.timeline ?? '', sources, { priorNorm, exemptNumericKeys });
+ const truth = verifyBody(page.compiled_truth ?? '', sources, { priorNorm, exemptNumericKeys, supersession: opts.supersession });
+ const timeline = verifyBody(page.timeline ?? '', sources, { priorNorm, exemptNumericKeys, supersession: opts.supersession });
stats.pages_checked++;
for (const r of [truth, timeline]) {
stats.quotes_total += r.quotes;
@@ -1301,6 +1359,7 @@ export async function verifyAndRepairDreamPages(
): Promise<QuoteVerifyStats> {
const stats = emptyQuoteVerifyStats();
const checkedAt = opts.checkedAt ?? await resolveCycleDate(engine).catch(() => utcDate());
+ const supersession = await attributionChecksEnabled(engine);
const pages = new Map<string, { slug: string; source_id: string; paths: string[]; first_write_at?: Date }>();
for (const ref of refs) {
const key = `${ref.source_id} ${ref.slug}`;
@@ -1337,7 +1396,7 @@ export async function verifyAndRepairDreamPages(
if (prior === 'unchanged') { stats.skipped_unchanged++; continue; }
if (prior) stats.preexisting_diffed++;
const sources = ref.paths.map(sourceFor);
- const mechanical = verifyDreamPage(page, sources, { prior, checkedAt }, stats);
+ const mechanical = verifyDreamPage(page, sources, { prior, checkedAt, supersession }, stats);
const verified = opts.grounding ? await opts.grounding.apply(mechanical, sources, `page:${ref.source_id}:${ref.slug}`, checkedAt) : mechanical;
if (verified.changed) {
const tags = await engine.getTags(ref.slug, { sourceId: ref.source_id });
diff --git a/test/cycle-synthesize-verify-superseded.test.ts b/test/cycle-synthesize-verify-superseded.test.ts
new file mode 100644
index 0000000000..7b69044c9b
--- /dev/null
+++ b/test/cycle-synthesize-verify-superseded.test.ts
@@ -0,0 +1,132 @@
+// #5425 [UC4] (wave 14 PR3 row P3.9): `superseded_in_source`, behind
+// `dream.attribution_checks` (default off).
+//
+// Protects: with the switch on, a synthesized sentence whose grounded quote a
+// LATER user turn takes back on the same number or date is quarantined with
+// reason `superseded_in_source`; a later user sentence that merely repeats
+// the number, negates a different number, negates in an assistant turn, or
+// comes before the quote supersedes nothing; a bare year is never a target.
+// With the switch off (the default, and every caller that does not pass
+// `supersession`), the output is byte-identical to the previous release.
+// Fails when: the check fires without the switch, misses the same-sentence
+// rule, or counts non-user turns. Why not existing coverage:
+// cycle-synthesize-verify-decisions.test.ts pins attribution, not retraction.
+// No production seam: `verifyBody` already takes an options object.
+
+import { describe, expect, test } from 'bun:test';
+import { emptyQuoteVerifyStats, groundSource, verifyBody, verifyDreamPage } from '../src/core/cycle/synthesize-verify.ts';
+import { ATTRIBUTION_CHECKS_KEY, attributionChecksEnabled, parseAttributionChecks } from '../src/core/cycle/attribution-checks.ts';
+import { assertCycleConfigValue, CYCLE_GUARDED_KEYS } from '../src/core/cycle/config-guards.ts';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
+
+const transcript = [
+ '[user]',
+ 'Let us settle the beta budget and the launch.',
+ '[assistant]',
+ 'I suggest capping the beta at $30K of credits and launching on 2026-10-15.',
+ '[user]',
+ 'Yes, cap the beta at $30K of credits. We have 5 engineers on it.',
+ '[assistant]',
+ 'Noted. Anything else?',
+ '[user]',
+ 'Actually, not $30K. Make the cap $45K. The launch date stays 2026-10-15.',
+ '[user]',
+ 'Also, we do not have 5 engineers on it any more, only 4. The 2019 cohort is unaffected.',
+].join('\n');
+const src = [groundSource('/t/budget.txt', transcript)];
+const on = { supersession: true } as const;
+
+describe('superseded_in_source (#5425 [UC4], dream.attribution_checks on)', () => {
+ test('a sentence whose quote the user later took back on the same number is quarantined', () => {
+ const body = 'The user said "cap the beta at $30K of credits" for the first month.';
+ const r = verifyBody(body, src, on);
+ expect(r.quarantined.map(q => q.reason)).toEqual(['superseded_in_source']);
+ expect(r.quarantined[0]!.detail).toContain('$30K');
+ expect(r.quarantined[0]!.detail).toContain('taken back by the user: Actually, not $30K');
+ expect(r.body).toBe('');
+ expect(r.failures.superseded_in_source).toBe(1);
+ });
+
+ test('a later user sentence that merely repeats the date is not a retraction', () => {
+ const body = 'The assistant suggested "launching on 2026-10-15" after the pricing page.';
+ expect(verifyBody(body, src, on).quarantined).toEqual([]);
+ });
+
+ test('a negation of a different number, even in the same later turn, is not a retraction', () => {
+ const body = 'The user said "cap the beta at $30K of credits" for the first month.';
+ const later = [groundSource('/t/other.txt', [
+ '[assistant]', 'I suggest capping the beta at $30K of credits.',
+ '[user]', 'Yes, cap the beta at $30K of credits.',
+ '[user]', 'We will not spend $12,000 on ads this quarter.',
+ ].join('\n'))];
+ expect(verifyBody(body, later, on).quarantined).toEqual([]);
+ });
+
+ test('an unrelated later sentence sharing a bare number is not a retraction (same-sentence rule)', () => {
+ const body = 'The user said "We have 5 engineers on it" at the start.';
+ expect(verifyBody(body, src, on).quarantined).toEqual([]);
+ });
+
+ test('a negation in an assistant turn, or a user turn before the quote, supersedes nothing', () => {
+ const t = [groundSource('/t/order.txt', [
+ '[user]', 'Not $30K, that is too much.',
+ '[assistant]', 'Then let us cap the beta at $30K of credits anyway? No, not $30K, sorry, $20K.',
+ '[user]', 'Fine, "cap the beta at $20K of credits" it is.',
+ ].join('\n'))];
+ expect(verifyBody('The user said "cap the beta at $20K of credits" at the end.', t, on).quarantined).toEqual([]);
+ expect(verifyBody('The assistant said "cap the beta at $30K of credits" first.', t, on).quarantined).toEqual([]);
+ });
+
+ test('a bare year is never a retraction target', () => {
+ const t = [groundSource('/t/year.txt', [
+ '[assistant]', 'The 2019 cohort set the pattern for this.',
+ '[user]', 'No, the 2019 cohort was different.',
+ ].join('\n'))];
+ expect(verifyBody('The assistant said "The 2019 cohort set the pattern for this".', t, on).quarantined).toEqual([]);
+ });
+
+ test('a transcript without speaker turns is never checked', () => {
+ const flat = [groundSource('/t/notes.txt', 'Notes: cap the beta at $30K of credits. Not $30K after all.')];
+ expect(verifyBody('The notes say "cap the beta at $30K of credits".', flat, on).quarantined).toEqual([]);
+ });
+});
+
+describe('dream.attribution_checks off: byte-identical output', () => {
+ const body = 'The user said "cap the beta at $30K of credits" for the first month.';
+ test('verifyBody without the option quarantines nothing and leaves the body alone', () => {
+ const r = verifyBody(body, src);
+ expect(r.quarantined).toEqual([]);
+ expect(r.body).toBe(body);
+ expect(r.failures.superseded_in_source).toBe(0);
+ expect(verifyBody(body, src, { supersession: false })).toEqual(r);
+ });
+
+ test('verifyDreamPage without `supersession` is unchanged; with it, the sentence moves to unverified_claims', () => {
+ const page = { slug: 'wiki/x', compiled_truth: body, timeline: '', frontmatter: {} };
+ const off = verifyDreamPage(page, src, { prior: null, checkedAt: '2026-10-10' }, emptyQuoteVerifyStats());
+ expect(off.compiled_truth).toBe(body);
+ expect(off.frontmatter.unverified_claims).toBeUndefined();
+ const stats = emptyQuoteVerifyStats();
+ const flagged = verifyDreamPage(page, src, { prior: null, checkedAt: '2026-10-10', supersession: true }, stats);
+ expect(flagged.compiled_truth).not.toContain('$30K');
+ expect((flagged.frontmatter.unverified_claims as Array<{ reason: string }>).map(u => u.reason)).toEqual(['superseded_in_source']);
+ expect(stats.superseded_in_source).toBe(1);
+ });
+});
+
+describe('the switch', () => {
+ test('is registered, boolean-validated on config set, and off unless a true word is stored', async () => {
+ expect(KNOWN_CONFIG_KEYS).toContain(ATTRIBUTION_CHECKS_KEY);
+ expect(CYCLE_GUARDED_KEYS).toContain(ATTRIBUTION_CHECKS_KEY);
+ for (const [raw, want] of [['true', true], ['on', true], ['1', true], ['false', false], ['off', false], ['maybe', null], ['', null]] as const) {
+ expect(parseAttributionChecks(raw)).toBe(want);
+ }
+ expect(() => assertCycleConfigValue(ATTRIBUTION_CHECKS_KEY, 'maybe')).toThrow(/expected true or false/);
+ expect(() => assertCycleConfigValue(ATTRIBUTION_CHECKS_KEY, 'true')).not.toThrow();
+ const engineWith = (value: string | null) => ({ getConfig: async (key: string) => (key === ATTRIBUTION_CHECKS_KEY ? value : null) });
+ expect(await attributionChecksEnabled(engineWith(null))).toBe(false);
+ expect(await attributionChecksEnabled(engineWith('false'))).toBe(false);
+ expect(await attributionChecksEnabled(engineWith('true'))).toBe(true);
+ expect(await attributionChecksEnabled({ getConfig: async () => { throw new Error('db down'); } })).toBe(false);
+ });
+});
diff --git a/test/propose-takes-attribution-callsite.test.ts b/test/propose-takes-attribution-callsite.test.ts
new file mode 100644
index 0000000000..49049313a3
--- /dev/null
+++ b/test/propose-takes-attribution-callsite.test.ts
@@ -0,0 +1,51 @@
+// #5425 [UC4] (wave 14 PR3 row P3.9): the one call from `propose-takes.ts`
+// into `propose-takes-attribution.ts`, behind `dream.attribution_checks`.
+// The call site is a stack hunk on a wave 13 hot file
+// (`~/.capy/work/w14/pr3/stack-hunks/propose-takes.ts.p3.9.patch`, behind
+// #6446); flip `test.todo` to `test` when it lands. The helper itself is
+// pinned by test/propose-takes-attribution.test.ts.
+//
+// Protects: with the switch on, a person-holder proposal whose numbers only
+// assistant turns of the page state is stored with holder `brain`; with the
+// switch off (default) the stored holder is exactly what the extractor
+// returned. Fails when: the phase never calls the check, or calls it with
+// the switch off. Seam: the `extractor` option already exists.
+
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { runPhaseProposeTakes } from '../src/core/cycle/propose-takes.ts';
+import { ATTRIBUTION_CHECKS_KEY } from '../src/core/cycle/attribution-checks.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); });
+
+const context = (): OperationContext => ({
+ engine, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote: false, sourceId: 'default',
+});
+const PAGE = ['[user]', 'How should we price the pro tier?', '[assistant]', 'Price the pro tier at $49 per seat.', '[user]', 'Let me think about it.'].join('\n');
+const proposal = { claim_text: 'Pro tier should be priced at $49 per seat.', kind: 'take' as const, holder: 'people/alice-example', weight: 0.6 };
+
+async function storedHolders(): Promise<string[]> {
+ await engine.putPage('wiki/conversations/pricing', { title: 'pricing', type: 'conversation' as never, compiled_truth: PAGE, frontmatter: {}, timeline: '' });
+ await runPhaseProposeTakes(context(), { extractor: async () => [proposal] });
+ return (await engine.executeRaw<{ holder: string }>(`SELECT holder FROM take_proposals WHERE page_slug = 'wiki/conversations/pricing'`)).map(r => r.holder);
+}
+
+describe('propose_takes calls the mechanical holder check (#5425 [UC4], P3.9)', () => {
+ test('switch off (default): the extractor\'s holder is stored as is', async () => {
+ expect(await storedHolders()).toEqual(['people/alice-example']);
+ });
+
+ test.todo('P3.9: switch on: an assistant-only person attribution is stored as brain', async () => {
+ await engine.setConfig(ATTRIBUTION_CHECKS_KEY, 'true');
+ expect(await storedHolders()).toEqual(['brain']);
+ });
+});
diff --git a/test/propose-takes-attribution.test.ts b/test/propose-takes-attribution.test.ts
new file mode 100644
index 0000000000..4fe5ca7308
--- /dev/null
+++ b/test/propose-takes-attribution.test.ts
@@ -0,0 +1,88 @@
+// #5425 [UC4] (wave 14 PR3 row P3.9): the mechanical holder check for
+// propose_takes, `downgradeAssistantOnlyHolders`, unit-tested standalone
+// because its one call site in `propose-takes.ts` (wave 13 hot file) is a
+// stack hunk (`~/.capy/work/w14/pr3/stack-hunks/propose-takes.ts.p3.9.patch`).
+//
+// Protects: a `people/<slug>` proposal whose numbers, dates and quoted
+// phrases only assistant turns state is held by `brain`; a token the user
+// stated, or explicitly accepted in the next turn ("yes, do that"), keeps the
+// person; claims with no content tokens, pages with no speaker turns, and
+// tokens no turn states are left alone; non-person holders are never touched;
+// the input is not mutated. Fails when: the check downgrades on shared or
+// accepted tokens, or fires without turn evidence. Why not existing coverage:
+// attribution-rules-opt-in.test.ts pins the prompt rules, not a mechanical
+// check. No production seam.
+
+import { describe, expect, test } from 'bun:test';
+import { claimContentTokens, downgradeAssistantOnlyHolders } from '../src/core/cycle/propose-takes-attribution.ts';
+
+const page = [
+ '[user]',
+ 'How should we price the pro tier?',
+ '[assistant]',
+ 'Price the pro tier at $49 per seat and expect 12% monthly churn at first. "Annual prepay is the lever that matters most."',
+ '[user]',
+ 'The churn number I trust is 8%, from our own 2025 cohort.',
+ '[assistant]',
+ 'Then I would still cap discounts at 20% for annual prepay.',
+ '[user]',
+ 'Yes, do that.',
+].join('\n');
+
+const take = (claim_text: string, holder: string) => ({ claim_text, kind: 'take' as const, holder, weight: 0.6 });
+
+describe('downgradeAssistantOnlyHolders (#5425 [UC4])', () => {
+ test('a person-holder proposal whose numbers only the assistant stated is held by brain', () => {
+ const out = downgradeAssistantOnlyHolders([take('Pro tier should be priced at $49 per seat.', 'people/alice-example')], page);
+ expect(out.map(p => p.holder)).toEqual(['brain']);
+ });
+
+ test('a quoted phrase only the assistant said is assistant evidence too', () => {
+ const out = downgradeAssistantOnlyHolders([take('"Annual prepay is the lever that matters most."', 'people/alice-example')], page);
+ expect(out.map(p => p.holder)).toEqual(['brain']);
+ });
+
+ test('a number the user stated keeps the person; mixed tokens keep the person', () => {
+ const out = downgradeAssistantOnlyHolders([
+ take('Churn for the pro tier runs at 8%.', 'people/alice-example'),
+ take('Pro tier at $49 per seat with 8% churn is viable.', 'people/alice-example'),
+ ], page);
+ expect(out.map(p => p.holder)).toEqual(['people/alice-example', 'people/alice-example']);
+ });
+
+ test('a proposal the user explicitly accepted ("Yes, do that.") stays the person\'s', () => {
+ const out = downgradeAssistantOnlyHolders([take('Annual prepay discounts are capped at 20%.', 'people/alice-example')], page);
+ expect(out.map(p => p.holder)).toEqual(['people/alice-example']);
+ });
+
+ test('no content tokens, a number no turn states, or a bare year: nothing to decide', () => {
+ const input = [
+ take('The pro tier is under-priced.', 'people/alice-example'),
+ take('We should target $99 per seat eventually.', 'people/alice-example'),
+ take('The 2025 cohort is the one to study.', 'people/alice-example'),
+ ];
+ expect(downgradeAssistantOnlyHolders(input, page)).toBe(input);
+ });
+
+ test('a page without speaker turns is never checked', () => {
+ const input = [take('Pro tier should be priced at $49 per seat.', 'people/alice-example')];
+ expect(downgradeAssistantOnlyHolders(input, 'Pricing memo: the pro tier goes to $49 per seat; 12% churn expected.')).toBe(input);
+ });
+
+ test('non-person holders are never touched and the input is not mutated', () => {
+ const input = [take('Pro tier should be priced at $49 per seat.', 'brain'), take('Churn will be 12%.', 'companies/acme-example'),
+ take('Churn will be 12%.', 'people/bob-example')];
+ const before = JSON.stringify(input);
+ const out = downgradeAssistantOnlyHolders(input, page);
+ expect(out.map(p => p.holder)).toEqual(['brain', 'companies/acme-example', 'brain']);
+ expect(JSON.stringify(input)).toBe(before);
+ expect(out).not.toBe(input);
+ });
+
+ test('claimContentTokens: numbers and dates in canonical form, quoted phrases normalized, bare years dropped', () => {
+ expect(claimContentTokens('Ship by 2026-03-14 with $250K, 5% churn and "a quoted phrase here" in 2026')).toEqual([
+ '250000', '5%', 'date:2026-03-14', 'md:3-14', 'q:a quoted phrase here',
+ ]);
+ expect(claimContentTokens('Nothing numeric here, "short"')).toEqual([]);
+ });
+});