Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(grounding): verify quotes in think answers, saved syntheses, concept narratives and pattern pages

garrytaneac8edd5cf03
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index bc86fe13e6..0a4e9c9569 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -6,11 +6,11 @@ Synthesis, patterns, consolidation and connector atom gating.
- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. A publish still `write_pending` after the job's shared maintenance wait is deferred, never written or finalized: `withPublishPending` turns the phase result into `warn` with `publish_pending` and `SYNTH_PUBLISH_DEFERRED` ("publish deferred (writer busy); finishes next cycle, no action needed"), `synthesize.ts` leaves `dream.synthesize.last_completion_ts` unstamped, and the next ordinary cycle resumes the same deterministic request id. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the ref's `first_write_at`, else the child write epochs passed as `sinceByTranscript`) and stamps the dream provenance fields only on dream-owned pages (`isDreamOwnedPage`); the published page reconciles its automatic links like an ordinary put_page (`page-prepare.ts` treats `managed_maintenance_page` intents as auto-linked); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper. The optional `grounding` pass (System One S8) runs after `verifyDreamPage` and before `publishMaintenancePage`, so the published revision never carries a unit S8 quarantined; pinned by `test/decide/writepath-phase.serial.test.ts`. The postprocess stamps the transcript's `seat` next to `raw_source` on dream-owned output.
-- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats.
+- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, kill switch `dream.quote_verify`): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`.
- `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.
-- `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 WITH an offset map back to the original string, so every replacement is a verbatim transcript slice) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). `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; 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`.
+- `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 WITH an offset map back to the original string, so every replacement is a verbatim transcript slice) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). `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; 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`, with `dream.synthesize.quote_verify` as its alias, for synthesis, patterns and concepts. `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`).
- `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. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`).
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index dc2a68ff38..e6dcdff46a 100644
--- a/docs/architecture/key-files/core-services-3.md
+++ b/docs/architecture/key-files/core-services-3.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/think/index.ts` — `runThink` builds its internal `LLMClient` via a small adapter wrapping `gateway.chat()` from `src/core/ai/gateway.ts` (not `new Anthropic()` directly) so stdio MCP launches (Claude Desktop, Cursor) that don't inherit shell env still find a key set via `gbrain config set anthropic_api_key` (the gateway reads `~/.gbrain/config.json` AND env). Test seam: `opts.client?: ThinkLLMClient` injection works (`test/think-pipeline.serial.test.ts`, `test/think-gateway-adapter.test.ts`); `opts.stubResponse` short-circuits before any LLM call. When neither key nor client is available, the "no LLM available" stub fires with `NO_ANTHROPIC_API_KEY`. Trajectory injection (default ON): `runThink` orchestrates `classifyIntent(question)` → `extractCandidateEntities(question, retrievedSlugs)` → `findTrajectory` (5s `Promise.race` timeout per candidate, concurrency cap 3) → `formatTrajectoryBlock`. `buildThinkUserMessage` (in `src/core/think/prompt.ts`) has a `trajectory?: ThinkTrajectoryBlockOpts` slot honoring BOTH prompt orderings (calibration mode: retrieval → calibration → trajectory → question; default mode: question → retrieval → trajectory → instruction). The MCP `think` op handler maps `sourceScopeOpts(ctx)` onto `RunThinkOpts` via `thinkSourceScopeOpts(ctx)` (operations.ts), and `runThink` threads the scope into `runGather` (`src/core/think/gather.ts`) — so every gather stream (hybrid retrieval, takes keyword + vector via the engines' scoped `searchTakes`/`searchTakesVector`, graph walk via `traversePaths`) AND trajectory resolution stay within the caller's source grant (federated `sourceIds[]` wins over scalar `sourceId`); pinned by `test/e2e/think-source-isolation-pglite.test.ts`. Config key `think.trajectory_enabled` (default `true`). Any error in the trajectory path degrades to "no block injected" + `TRAJECTORY_INJECTION_FAILED` warning — the think call never crashes from trajectory. Production path skips `fallback_slugify` resolutions (avoid querying invented slugs); the LongMemEval harness accepts them. Pinned by `test/think-trajectory-injection.test.ts`. Debug: `GBRAIN_THINK_DEBUG=1 gbrain think "..."` prints the spliced prompt to stderr. System One (`think/decide.ts`, no work when S2 and S4 are off): S2 decides the trajectory-gating intent (regex `classifyIntent` is the fallback and tie source) and hands gather one precomputed search-intent answer; S4 may return an abstention after gather and before synthesis (`ThinkResult.abstained`, warning `DECIDE_ABSTAINED`, `synthesisOk: false`, synthesis call skipped).
+- `src/core/think/index.ts` — `runThink` builds its internal `LLMClient` via a small adapter wrapping `gateway.chat()` from `src/core/ai/gateway.ts` (not `new Anthropic()` directly) so stdio MCP launches (Claude Desktop, Cursor) that don't inherit shell env still find a key set via `gbrain config set anthropic_api_key` (the gateway reads `~/.gbrain/config.json` AND env). Test seam: `opts.client?: ThinkLLMClient` injection works (`test/think-pipeline.serial.test.ts`, `test/think-gateway-adapter.test.ts`); `opts.stubResponse` short-circuits before any LLM call. When neither key nor client is available, the "no LLM available" stub fires with `NO_ANTHROPIC_API_KEY`. Trajectory injection (default ON): `runThink` orchestrates `classifyIntent(question)` → `extractCandidateEntities(question, retrievedSlugs)` → `findTrajectory` (5s `Promise.race` timeout per candidate, concurrency cap 3) → `formatTrajectoryBlock`. `buildThinkUserMessage` (in `src/core/think/prompt.ts`) has a `trajectory?: ThinkTrajectoryBlockOpts` slot honoring BOTH prompt orderings (calibration mode: retrieval → calibration → trajectory → question; default mode: question → retrieval → trajectory → instruction). The MCP `think` op handler maps `sourceScopeOpts(ctx)` onto `RunThinkOpts` via `thinkSourceScopeOpts(ctx)` (operations.ts), and `runThink` threads the scope into `runGather` (`src/core/think/gather.ts`) — so every gather stream (hybrid retrieval, takes keyword + vector via the engines' scoped `searchTakes`/`searchTakesVector`, graph walk via `traversePaths`) AND trajectory resolution stay within the caller's source grant (federated `sourceIds[]` wins over scalar `sourceId`); pinned by `test/e2e/think-source-isolation-pglite.test.ts`. Config key `think.trajectory_enabled` (default `true`). Any error in the trajectory path degrades to "no block injected" + `TRAJECTORY_INJECTION_FAILED` warning — the think call never crashes from trajectory. Production path skips `fallback_slugify` resolutions (avoid querying invented slugs); the LongMemEval harness accepts them. Pinned by `test/think-trajectory-injection.test.ts`. Debug: `GBRAIN_THINK_DEBUG=1 gbrain think "..."` prints the spliced prompt to stderr. System One (`think/decide.ts`, no work when S2 and S4 are off): S2 decides the trajectory-gating intent (regex `classifyIntent` is the fallback and tie source) and hands gather one precomputed search-intent answer; S4 may return an abstention after gather and before synthesis (`ThinkResult.abstained`, warning `DECIDE_ABSTAINED`, `synthesisOk: false`, synthesis call skipped). Quote grounding (`think.quote_verify`, default on): after a real synthesis, every quoted span in the answer is grounded against exactly the evidence blocks the prompt carried (pages, takes, graph, trajectory; no refetch) with `groundAnswerQuotes`; when the answer had quotes, `answer` becomes the safe version (near matches repaired, quotes found nowhere unquoted and marked `[unverified]`, warning `QUOTE_NOT_IN_EVIDENCE`), `answer_raw`/`quote_check`/`unverified_quotes` are added, and `persist` (internal; stripped by the MCP `think` op) holds the raw answer run through `verifyBody(…, { checks: 'quotes' })`, which `persistSynthesis` saves with failing units in frontmatter `unverified_claims`. The `synthesize` verb returns the same additive fields. Pinned by `test/think-quote-verify.test.ts`.
- `src/core/think/intent.ts` + `src/core/think/entity-extract.ts` — pure `classifyIntent(question)` returns `'temporal' | 'knowledge_update' | 'other'` (regex-first, no LLM, `'other'` fast path short-circuits with zero SQL). `extractCandidateEntities(question, retrievedSlugs)` pulls high-precision candidates from retrieved entity-prefix slugs (`people/`, `companies/`, `organizations/`) and medium-precision noun phrases. Stop-word boundaries + leading-verb stripper handle "When did I last meet Marco" → `marco`. Both consumed by `runThink` and the LongMemEval harness so the two paths cannot drift. Pinned by `test/think-intent.test.ts` and `test/think-entity-extract.test.ts`.
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 967807c49c..dd4b7e6de1 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -364,6 +364,17 @@ output_tokens, usd_estimate}, protocol_version }`.
- No LLM configured ⇒ the protocol error `unavailable` with a fix — never a
fake answer.
+#### synthesize quote check (additive)
+
+Every quoted span in a synthesized `answer` is grounded against the evidence
+the answer was composed from (the same page excerpts, takes and graph lines,
+no refetch). An exact match stays; a normalized or near match is replaced with
+the evidence's own words; a quote found in no evidence loses its quotation
+marks and gains `[unverified]`, and the response warns `QUOTE_NOT_IN_EVIDENCE`.
+When the answer contained quotes, the response adds `answer_raw` (as written),
+`quote_check: { grounded, repaired, unverified }` and `unverified_quotes:
+[{ text, reason }]`. Present `answer`, not `answer_raw`, to the user.
+
#### synthesize compose status (additive)
Every response additionally carries four ADDITIVE-FOREVER fields (optional;
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4bb277515f..4512794515 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1838 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured)
+src/core/config.ts 1840 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +2 P8: dream.quote_verify and think.quote_verify known keys
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)
diff --git a/src/core/config.ts b/src/core/config.ts
index 60c1fb60d9..709ea9d456 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1468,6 +1468,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'dream.synthesize.mode',
'dream.synthesize.link_manifest',
'dream.synthesize.quote_verify',
+ 'dream.quote_verify',
+ 'think.quote_verify',
'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/patterns.ts b/src/core/cycle/patterns.ts
index cc5ed84bcf..76b7de0629 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -361,13 +361,13 @@ export async function runPhasePatterns(
throwIfAborted(opts.signal, '[dream] patterns output');
const writtenRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId);
- await stampPatternOutputs(engine, maintenance, writtenRefs.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), opts.signal);
+ const quoteVerify = await stampPatternOutputs(engine, maintenance, writtenRefs, reflections, config, cycleSourceId, cycleDate, opts.signal);
const reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, writtenRefs)
: await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);
const details = {
reflections_considered: reflections.length,
- patterns_written: writtenRefs.length,
+ patterns_written: writtenRefs.length, ...(quoteVerify ? { quote_verify: quoteVerify } : {}),
reverse_write_count: reverseWriteCount,
child_outcome: outcome,
job_id: job.id,
@@ -532,7 +532,7 @@ async function loadPatternsConfig(engine: BrainEngine): Promise<PatternsConfig>
* `dream.synthesize.last_completion_ts`; `dream.` is already a known prefix. */
const LAST_EVIDENCE_KEY = 'dream.patterns.last_evidence_ts';
-interface ReflectionRef {
+export interface ReflectionRef {
slug: string;
title: string;
excerpt: string;
@@ -633,7 +633,18 @@ When done, briefly list the pattern slugs you wrote/updated in your final messag
* #5884: a pattern is derived from reflection pages, not raw material, so it is
* stamped raw-trace exempt (doctor raw_provenance) on every run that writes it.
*/
-async function stampPatternOutputs(engine: BrainEngine, maintenance: MaintenanceAuthority | null,
+/**
+ * Quote-ground the pattern outputs (and pages a crashed run left unverified), then stamp provenance on the
+ * outputs. Returns the grounding counts, or null when dream.quote_verify is off.
+ */
+async function stampPatternOutputs(engine: BrainEngine, maintenance: MaintenanceAuthority | null, written: Array<{ slug: string; source_id: string }>,
+ reflections: ReflectionRef[], config: { outputSlugPrefix: string; sourceSlugPrefix: string }, sourceId: string, cycleDate: string, signal?: AbortSignal) {
+ const stats = await groundPatternPages(engine, maintenance, written, reflections, config.outputSlugPrefix, sourceId, cycleDate, signal);
+ await stampProvenance(engine, maintenance, written.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), signal);
+ return stats;
+}
+
+async function stampProvenance(engine: BrainEngine, maintenance: MaintenanceAuthority | null,
refs: Array<{ slug: string; source_id: string }>, cycleDate: string, sourceSlugPrefix: string, seat: string | undefined, signal?: AbortSignal): Promise<void> {
const reason = `derived from reflections under ${sourceSlugPrefix}/; raw traces live on the cited reflection pages`;
if (!maintenance) return stampDreamProvenance(engine, refs.map(ref => ({ ...ref, raw_trace_exempt_reason: reason, ...(seat ? { seat } : {}) })), cycleDate, signal);
@@ -643,6 +654,60 @@ async function stampPatternOutputs(engine: BrainEngine, maintenance: Maintenance
}
}
+// ── Quote grounding ──────────────────────────────────────────────────
+
+/**
+ * Ground every quoted span on the pattern pages against the full reflection
+ * pages the run read (quotes and speaker attribution only: a pattern counts
+ * its evidence). A failing claim unit leaves the body for frontmatter
+ * `unverified_claims`; `quote_verified_at` marks a checked page, so a page a
+ * crashed run left behind is verified by the next run. Kill switch:
+ * dream.quote_verify. Returns null when disabled.
+ */
+export async function groundPatternPages(engine: BrainEngine, maintenance: MaintenanceAuthority | null, refs: Array<{ slug: string; source_id: string }>,
+ reflections: ReflectionRef[], outputSlugPrefix: string, sourceId: string, cycleDate: string, signal?: AbortSignal):
+ Promise<{ pages: number; quarantined: number; repaired: number } | null> {
+ const { dreamQuoteVerifyEnabled, groundSource, verifyBody } = await import('./synthesize-verify.ts');
+ if (!await dreamQuoteVerifyEnabled(engine)) return null;
+ const leftover = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id = $1 AND slug LIKE $2 AND deleted_at IS NULL
+ AND frontmatter->>'dream_generated' = 'true' AND frontmatter->>'quote_verified_at' IS NULL`, [sourceId, `${outputSlugPrefix}/%`]);
+ const slugs = [...new Set([...refs.map(r => r.slug).filter(slug => slug.startsWith(`${outputSlugPrefix}/`)), ...leftover.map(r => r.slug)])];
+ if (slugs.length === 0) return { pages: 0, quarantined: 0, repaired: 0 };
+ const sourcePages = await engine.executeRaw<{ slug: string; compiled_truth: string; timeline: string }>(
+ 'SELECT slug, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL',
+ [sourceId, reflections.map(r => r.slug)]);
+ const sources = sourcePages.map(p => groundSource(p.slug, `${p.compiled_truth}\n\n${p.timeline ?? ''}`));
+ const stats = { pages: 0, quarantined: 0, repaired: 0 };
+ const { serializePageToMarkdown } = await import('../markdown.ts');
+ for (const slug of slugs) {
+ throwIfAborted(signal, '[dream] patterns quote verify');
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ if (!snapshot) continue;
+ const ct = verifyBody(snapshot.page.compiled_truth, sources, { checks: 'quotes' });
+ const tl = verifyBody(snapshot.page.timeline ?? '', sources, { checks: 'quotes' });
+ const quarantined = [...ct.quarantined, ...tl.quarantined];
+ stats.pages++;
+ stats.quarantined += quarantined.length;
+ stats.repaired += ct.normalized + ct.near + tl.normalized + tl.near;
+ const prior = Array.isArray(snapshot.page.frontmatter.unverified_claims) ? snapshot.page.frontmatter.unverified_claims as unknown[] : [];
+ const page = { ...snapshot.page,
+ compiled_truth: ct.body.trim() ? ct.body : (await import('./synthesize-verify.ts')).ALL_CLAIMS_QUARANTINED_BODY,
+ timeline: tl.body,
+ frontmatter: { ...snapshot.page.frontmatter, quote_verified_at: cycleDate,
+ ...(quarantined.length ? { unverified_claims: [...prior, ...quarantined.map(c => ({ ...c, sources: sources.map(x => x.path), detected_at: cycleDate }))].slice(-100) } : {}) } };
+ const content = serializePageToMarkdown(page, snapshot.tags);
+ if (maintenance) {
+ const { publishMaintenancePage } = await import('../persistence/prepared-maintenance.ts');
+ await publishMaintenancePage(engine, maintenance, slug, content, { expectedRevision: snapshot.revision });
+ } else {
+ const [{ importFromContent }, { isAvailable }] = await Promise.all([import('../import-file.ts'), import('../ai/gateway.ts')]);
+ await importFromContent(engine, slug, content, { noEmbed: !isAvailable('embedding'), sourceId });
+ }
+ }
+ return stats;
+}
+
// ── Provenance via put_page tool execution rows ─────────────────────
async function collectChildPutPageSlugs(
diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts
index 8a9b80f09d..a5ae00ff73 100644
--- a/src/core/cycle/synthesize-concepts.ts
+++ b/src/core/cycle/synthesize-concepts.ts
@@ -325,7 +325,7 @@ export async function runPhaseSynthesizeConcepts(
}
tierCounts[group.tier]++;
let narrative: string;
- let synthesisMode: ConceptSynthesisMode;
+ let synthesisMode: ConceptSynthesisMode, unverifiedClaims: UnverifiedClaim[] = [];
if (group.tier === 'T1' || group.tier === 'T2') {
if (estimatedSpendUsd >= budgetCap) {
narrative = deterministicNarrative(group);
@@ -365,7 +365,7 @@ export async function runPhaseSynthesizeConcepts(
1_000_000;
const text = result.text.trim();
if (text) {
- narrative = text;
+ ({ narrative, unverified: unverifiedClaims } = await groundConceptNarrative(engine, text, group));
synthesisMode = 'llm';
} else {
failures.push({ concept: group.conceptSlug, error: 'empty model response' });
@@ -423,7 +423,7 @@ export async function runPhaseSynthesizeConcepts(
member_hash: memberHash,
synthesized_at: synthesizedAt,
synthesized_by: 'synthesize_concepts-v0.41',
- visibility: pageVisibility,
+ visibility: pageVisibility, ...(unverifiedClaims.length ? { unverified_claims: unverifiedClaims.map(c => ({ ...c, sources: ['member atoms'], detected_at: synthesizedAt.slice(0, 10) })) } : {}),
});
// Each managed publication is bound to the revision the narrative was
// synthesized from, then to the previous publication's result.
@@ -615,3 +615,22 @@ function deterministicNarrative(group: AtomGroup): string {
.join('\n')}`
);
}
+
+/**
+ * Ground the narrative's quoted spans against the atom titles and bodies the
+ * prompt carried (quotes only: a concept narrative may count or compare).
+ * A claim unit with an unverified quote is removed from the narrative and
+ * kept in frontmatter `unverified_claims`. Kill switch: dream.quote_verify.
+ */
+type UnverifiedClaim = { text: string; reason: string; detail: string };
+async function groundConceptNarrative(engine: BrainEngine, narrative: string, group: { atomTitles: string[]; atomBodies: string[] }):
+ Promise<{ narrative: string; unverified: UnverifiedClaim[] }> {
+ const { ALL_CLAIMS_QUARANTINED_BODY, dreamQuoteVerifyEnabled, groundSource, verifyBody } = await import('./synthesize-verify.ts');
+ if (!await dreamQuoteVerifyEnabled(engine)) return { narrative, unverified: [] };
+ const sources = [
+ groundSource('concept-atom-titles', group.atomTitles.slice(0, 10).join('\n')),
+ ...group.atomBodies.slice(0, 5).map((b, i) => groundSource(`concept-atom-${i + 1}`, b.slice(0, 500))),
+ ];
+ const v = verifyBody(narrative, sources, { checks: 'quotes' });
+ return { narrative: v.body.trim() || ALL_CLAIMS_QUARANTINED_BODY, unverified: v.quarantined };
+}
diff --git a/src/core/cycle/synthesize-verify.ts b/src/core/cycle/synthesize-verify.ts
index 7a633fb21e..d9201dee42 100644
--- a/src/core/cycle/synthesize-verify.ts
+++ b/src/core/cycle/synthesize-verify.ts
@@ -838,6 +838,55 @@ function groundAcross(inner: string, sources: GroundedSource[]): { result: Exclu
return best ?? { result: { status: 'none', reason: crossed ? 'crosses_speakers' : 'not_found' } };
}
+/**
+ * The dream quote-verify kill switch: `dream.quote_verify` (covers synthesis,
+ * patterns and concepts), with `dream.synthesize.quote_verify` as an alias read
+ * when the new key is unset. Default on; only an explicit off spelling disables.
+ */
+export async function dreamQuoteVerifyEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
+ const raw = ((await engine.getConfig('dream.quote_verify')) ?? (await engine.getConfig('dream.synthesize.quote_verify')))?.trim().toLowerCase();
+ return !(raw === 'false' || raw === '0' || raw === 'off' || raw === 'no');
+}
+
+export interface AnswerQuoteCheck {
+ /** The answer with near-match quotes repaired to the evidence's words and unverified quotes unquoted and marked. */
+ answer: string;
+ quote_check: { grounded: number; repaired: number; unverified: number };
+ unverified_quotes: Array<{ text: string; reason: 'quote_not_in_source' | 'quote_crosses_speakers' }>;
+}
+
+export const UNVERIFIED_QUOTE_MARK = '[unverified]';
+
+/**
+ * Span-level quote check for a live answer (`think`, `synthesize`): every
+ * quoted span is grounded against the evidence the answer was written from.
+ * Exact matches stay; normalized or near matches are replaced with the
+ * evidence's own words; a quote found nowhere loses its quotation marks and
+ * gains `[unverified]`, so no caller can present it as a quotation. Pure.
+ */
+export function groundAnswerQuotes(answer: string, sources: GroundedSource[]): AnswerQuoteCheck {
+ const { spans } = extractQuoteSpans(answer);
+ const edits: Array<{ start: number; end: number; text: string }> = [];
+ const out: AnswerQuoteCheck = { answer, quote_check: { grounded: 0, repaired: 0, unverified: 0 }, unverified_quotes: [] };
+ for (const sp of spans) {
+ const g = groundAcross(sp.inner, sources);
+ if (g.result.status === 'none') {
+ out.quote_check.unverified++;
+ out.unverified_quotes.push({ text: clip(sp.inner, 300), reason: g.result.reason === 'crosses_speakers' ? 'quote_crosses_speakers' : 'quote_not_in_source' });
+ edits.push({ start: sp.start, end: sp.end + 1, text: `${sp.inner} ${UNVERIFIED_QUOTE_MARK}` });
+ } else if (g.result.status === 'exact') {
+ out.quote_check.grounded++;
+ } else {
+ out.quote_check.repaired++;
+ edits.push({ start: sp.start + 1, end: sp.end, text: g.result.replacement.replace(/\s*\n\s*/g, ' ') });
+ }
+ }
+ let body = answer;
+ for (const e of edits.sort((a, b) => b.start - a.start)) body = body.slice(0, e.start) + e.text + body.slice(e.end);
+ out.answer = body;
+ return out;
+}
+
function blank(s: string, ranges: Array<[number, number]>): string {
let out = s;
for (const [a, b] of ranges) out = out.slice(0, a) + ' '.repeat(b - a) + out.slice(b);
@@ -853,9 +902,11 @@ function clip(s: string, n = PROVENANCE_TEXT_CHARS): string {
* Verify one body (compiled_truth or timeline) against its source
* transcripts. Pure. With `priorNorm` (the normalized pre-run revision of a
* page that already existed), only units absent from it are checked; every
- * other unit is left exactly as it was.
+ * other unit is left exactly as it was. `checks: 'quotes'` grounds quotes and
+ * 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 } = {}): BodyVerification {
+export function verifyBody(body: string, sources: GroundedSource[], opts: { priorNorm?: string; checks?: 'all' | 'quotes' } = {}): 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 };
@@ -914,9 +965,10 @@ export function verifyBody(body: string, sources: GroundedSource[], opts: { prio
});
}
const unquoted = blank(masked.slice(u.start, u.end), quoteRanges);
- const numbers = unsupportedNumericClaims(unquoted, sources);
+ // Quotes-only mode (answers that legitimately compute numbers): no number or decision checks.
+ const numbers = opts.checks === 'quotes' ? [] : unsupportedNumericClaims(unquoted, sources);
for (const n of numbers) fail('number_not_in_source', n);
- if (numbers.length === 0) {
+ if (numbers.length === 0 && opts.checks !== 'quotes') {
for (const n of misattributedDecisionClaims(unquoted, attribution, sources, [...mentioned.keys()])) {
fail('decision_misattributed', `${[...mentioned.values()].join(', ')}: ${n} was stated only by another speaker`);
}
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 2d01adf66c..a7bc280d5b 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -1142,7 +1142,7 @@ async function runPhaseSynthesizeInner(
// created this run, new units only otherwise), BEFORE the provenance
// stamp / reverse-write / embed sweep, so unsupported claims never reach
// chunks or the markdown body. Fail-open (abort still unwinds); kill
- // switch: dream.synthesize.quote_verify=false.
+ // switch: dream.quote_verify=false (alias dream.synthesize.quote_verify).
let quoteVerifyStats: QuoteVerifyStats | null = null;
let publishPending = 0;
const sinceByTranscript = await loadChildWriteEpochs(engine, childIds, jobRawSource, verifySince);
@@ -1685,8 +1685,7 @@ export async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig>
const linkManifestRaw = (await engine.getConfig('dream.synthesize.link_manifest'))?.trim().toLowerCase();
const linkManifest = !(linkManifestRaw === 'false' || linkManifestRaw === '0' || linkManifestRaw === 'off');
// F1b kill switch (same off-spelling contract as link_manifest).
- const quoteVerifyRaw = (await engine.getConfig('dream.synthesize.quote_verify'))?.trim().toLowerCase();
- const quoteVerify = !(quoteVerifyRaw === 'false' || quoteVerifyRaw === '0' || quoteVerifyRaw === 'off');
+ const quoteVerify = await (await import('./synthesize-verify.ts')).dreamQuoteVerifyEnabled(engine);
// #4216: mode default 'oneshot' (D1=A). loadOutputRoot pattern: unknown
// values warn to stderr and fall back to the default rather than failing.
const modeRaw = (await engine.getConfig('dream.synthesize.mode'))?.trim().toLowerCase();
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 0395cb51e0..088dba1c98 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -299,8 +299,9 @@ const think: Operation = {
const { keylessThinkNotice, thinkNotSavedNotice } = await import('../interop-notices.ts');
if (result.synthesis_status === 'no_llm') ctx.emitNotice?.(keylessThinkNotice());
if (remote && (Boolean(p.save) || Boolean(p.take))) ctx.emitNotice?.(thinkNotSavedNotice());
+ const { persist: _persist, ...visible } = result;
return {
- ...result,
+ ...visible,
// #1698 (#10): the persist-skip signal returns slug '' — map it (and any
// falsy) to null so callers never see an empty-string "slug".
saved_slug: savedSlug || null,
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index 44541d92c9..4deefeeb74 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -208,6 +208,17 @@ export interface ThinkResult {
evidence_delivery?: import('../search/evidence-delivery.ts').DeliveryMeta;
/** Only set when --save was true and the caller persisted a synthesis page. */
savedSlug?: string;
+ /**
+ * Quote grounding (think.quote_verify, default on): `answer` is the safe
+ * version (near-match quotes repaired to the evidence's words, quotes found
+ * in no evidence unquoted and marked [unverified]); `answer_raw` is what the
+ * model wrote. Present only when the answer contained quotes.
+ */
+ answer_raw?: string;
+ quote_check?: { grounded: number; repaired: number; unverified: number };
+ unverified_quotes?: Array<{ text: string; reason: string }>;
+ /** What `persistSynthesis` saves: the raw answer with every claim unit carrying an unverified quote removed, and those units. */
+ persist?: { answer: string; unverified_claims: Array<{ text: string; reason: string; detail: string }> };
/** Diagnostics for `--explain` callers (CLI surface for v0.29). */
diagnostics: {
pagesFromHybrid: number;
@@ -947,6 +958,7 @@ export async function runThink(
return {
question: opts.question,
answer: response.answer,
+ ...(synthesisStatus === 'ok' ? await groundThinkAnswer(engine, response.answer, [pagesBlock, takesBlock, graphBlock ?? '', trajectoryBlock], warnings) : {}),
citations: resolved.citations,
gaps: response.gaps,
pagesGathered: gather.pages.length,
@@ -1030,11 +1042,12 @@ export async function persistSynthesis(
.slice(0, 60) || 'untitled';
const slug = `synthesis/${slugSafe}-${today}`;
- // Build the markdown body
+ // Build the markdown body. A claim whose quote is not in the evidence is not saved as prose;
+ // it goes to frontmatter unverified_claims (reviewable with get_page, out of search and recall).
const body = [
`# ${result.question}`,
'',
- stripGapsSection(result.answer),
+ stripGapsSection(result.persist?.answer ?? result.answer),
'',
result.gaps.length > 0 ? '## Gaps\n\n' + result.gaps.map(g => `- ${g}`).join('\n') : '',
].filter(Boolean).join('\n');
@@ -1050,6 +1063,7 @@ export async function persistSynthesis(
date: today,
pages_gathered: result.pagesGathered,
takes_gathered: result.takesGathered,
+ ...(result.persist?.unverified_claims.length ? { unverified_claims: result.persist.unverified_claims.map(c => ({ ...c, sources: ['think evidence'], detected_at: today })) } : {}),
},
}, scope.sourceId ? { sourceId: scope.sourceId } : undefined);
@@ -1103,6 +1117,36 @@ async function readThinkTrajectoryEnabled(engine: BrainEngine): Promise<boolean>
}
}
+/**
+ * Ground every quoted span of a synthesized answer against the evidence blocks
+ * the prompt carried. Empty when think.quote_verify is off or the answer has no
+ * quotes; otherwise the safe answer, what the model wrote, the counts, and the
+ * body persistSynthesis saves (failing claim units removed).
+ */
+async function groundThinkAnswer(engine: BrainEngine, answer: string, blocks: string[], warnings: string[]):
+ Promise<Partial<Pick<ThinkResult, 'answer' | 'answer_raw' | 'quote_check' | 'unverified_quotes' | 'persist'>>> {
+ if (answer.trim().length === 0 || !await readThinkQuoteVerify(engine)) return {};
+ const { groundSource, groundAnswerQuotes, verifyBody } = await import('../cycle/synthesize-verify.ts');
+ const sources = blocks.map((block, i) => ({ block, i })).filter(b => b.block.trim().length > 0)
+ .map(b => groundSource(`think-evidence-${b.i}`, b.block));
+ const check = groundAnswerQuotes(answer, sources);
+ if (check.quote_check.grounded + check.quote_check.repaired + check.quote_check.unverified === 0) return {};
+ if (check.quote_check.unverified > 0) warnings.push('QUOTE_NOT_IN_EVIDENCE');
+ const persisted = verifyBody(answer, sources, { checks: 'quotes' });
+ return { answer: check.answer, answer_raw: answer, quote_check: check.quote_check, unverified_quotes: check.unverified_quotes,
+ persist: { answer: persisted.body, unverified_claims: persisted.quarantined } };
+}
+
+/** `think.quote_verify` (default on): ground quoted spans in think answers against the prompt's evidence. */
+async function readThinkQuoteVerify(engine: BrainEngine): Promise<boolean> {
+ try {
+ const v = await engine.getConfig('think.quote_verify');
+ return !(v && ['false', '0', 'no', 'off'].includes(v.trim().toLowerCase()));
+ } catch {
+ return true;
+ }
+}
+
/**
* Try to build a gateway-backed ThinkLLMClient for the given model.
* Returns null when the gateway cannot resolve a usable chat provider for
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 7e9979042c..79a3db60ec 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -331,6 +331,7 @@ const synthesize: Operation = {
return {
answer: result.answer,
+ ...(result.answer_raw !== undefined ? { answer_raw: result.answer_raw, quote_check: result.quote_check, unverified_quotes: result.unverified_quotes } : {}),
sources: result.citations.map(c => c.page_slug),
gaps: result.gaps,
cost,
@@ -581,7 +582,10 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
required: ['answer', 'sources', 'cost', 'protocol_version'],
properties: {
protocol_version: { type: 'integer', const: MEMORY_VERBS_VERSION },
- answer: { type: 'string' },
+ answer: { type: 'string', description: 'Quoted words not found in the evidence are unquoted and marked [unverified]; never present them as quotes.' },
+ answer_raw: { type: 'string', description: 'Present when the answer contained quotes: the answer as the model wrote it.' },
+ quote_check: { type: 'object', properties: { grounded: { type: 'integer' }, repaired: { type: 'integer' }, unverified: { type: 'integer' } } },
+ unverified_quotes: { type: 'array', items: { type: 'object', properties: { text: { type: 'string' }, reason: { type: 'string' } } } },
sources: { type: 'array', items: { type: 'string' } },
gaps: { type: 'array', items: { type: 'string' } },
cost: {
diff --git a/test/cycle-patterns-quote-verify.test.ts b/test/cycle-patterns-quote-verify.test.ts
new file mode 100644
index 0000000000..2dfb1e33fa
--- /dev/null
+++ b/test/cycle-patterns-quote-verify.test.ts
@@ -0,0 +1,45 @@
+/**
+ * The patterns phase grounds quotes on the pattern pages its subagent wrote
+ * against the full reflection pages, right after the writes and before
+ * provenance stamping. A pattern page an earlier crashed run left without
+ * `quote_verified_at` is verified on the next run. Quotes only: a pattern
+ * counts its evidence, so numbers are not checked.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { groundPatternPages } from '../src/core/cycle/patterns.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const [slug, body] of [
+ ['wiki/personal/reflections/r1', 'I keep saying "ship smaller pieces" when projects stall.'],
+ ['wiki/personal/reflections/r2', 'Again I told myself to ship smaller pieces.'],
+ ]) await importFromContent(engine, slug!, `---\ntype: note\ntitle: ${slug}\n---\n${body}\n`, { noEmbed: true, sourceId: 'default' });
+ await importFromContent(engine, 'wiki/personal/patterns/small-pieces',
+ '---\ntype: note\ntitle: Small pieces\ndream_generated: true\n---\nAcross 2 reflections you repeat "ship smaller pieces".\n\nYou also wrote "never ship on Fridays".\n',
+ { noEmbed: true, sourceId: 'default' });
+});
+afterAll(async () => { await engine.disconnect(); });
+
+describe('patterns quote grounding', () => {
+ test('an unverified quote moves to unverified_claims; a leftover page is picked up; counts stay', async () => {
+ const reflections = [
+ { slug: 'wiki/personal/reflections/r1', title: 'r1', excerpt: '', updatedAt: new Date(), seat: null },
+ { slug: 'wiki/personal/reflections/r2', title: 'r2', excerpt: '', updatedAt: new Date(), seat: null },
+ ];
+ const stats = await groundPatternPages(engine, null, [], reflections, 'wiki/personal/patterns', 'default', '2026-10-04');
+ expect(stats).toEqual({ pages: 1, quarantined: 1, repaired: 0 });
+ const page = await engine.getPage('wiki/personal/patterns/small-pieces');
+ expect(page!.compiled_truth).toContain('Across 2 reflections');
+ expect(page!.compiled_truth).not.toContain('never ship on Fridays');
+ expect(page!.frontmatter.quote_verified_at).toBe('2026-10-04');
+ expect((page!.frontmatter.unverified_claims as unknown[]).length).toBe(1);
+ const again = await groundPatternPages(engine, null, [], reflections, 'wiki/personal/patterns', 'default', '2026-10-05');
+ expect(again).toEqual({ pages: 0, quarantined: 0, repaired: 0 });
+ });
+});
diff --git a/test/cycle/synthesize-concepts-quote-verify.test.ts b/test/cycle/synthesize-concepts-quote-verify.test.ts
new file mode 100644
index 0000000000..8084ee6f9c
--- /dev/null
+++ b/test/cycle/synthesize-concepts-quote-verify.test.ts
@@ -0,0 +1,62 @@
+// synthesize_concepts grounds the narrative's quotes against exactly the atom
+// titles and bodies its prompt carried, before the concept page is written: a
+// claim with a quote no atom contains leaves the narrative for frontmatter
+// unverified_claims; supported quotes and computed counts stay. Kill switch:
+// dream.quote_verify (dream.synthesize.quote_verify is its alias).
+//
+// Hermetic: PGLite + injected `_atoms` and `_chat`.
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+
+const atoms = () => Array.from({ length: 5 }, (_, i) => ({
+ slug: `atoms/a${i}`,
+ concept_refs: ['concepts/compounding'],
+ body: i === 0 ? 'Patience lets small advantages "compound into durable moats" over years.' : `Atom ${i} about compounding effort.`,
+ title: `Compounding ${i}`,
+}));
+
+function chat(text: string): (o: ChatOpts) => Promise<ChatResult> {
+ return async (o: ChatOpts) => ({ text, blocks: [{ type: 'text', text }], stopReason: 'end',
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: o.model ?? 'unset', providerId: 'test' });
+}
+
+const NARRATIVE = 'Five atoms agree that small advantages "compound into durable moats" over time.\n\nOne atom claims "luck beats skill every time".';
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');
+});
+
+describe('synthesize_concepts quote grounding', () => {
+ test('an unsupported quote leaves the narrative for unverified_claims before the page is written', async () => {
+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms(), _chat: chat(NARRATIVE) });
+ const page = await engine.getPage('concepts/compounding');
+ expect(page).toBeTruthy();
+ expect(page!.compiled_truth).toContain('compound into durable moats');
+ expect(page!.compiled_truth).toContain('Five atoms');
+ expect(page!.compiled_truth).not.toContain('luck beats skill');
+ const claims = page!.frontmatter.unverified_claims as Array<{ text: string; reason: string }>;
+ expect(claims).toHaveLength(1);
+ expect(claims[0]!.reason).toBe('quote_not_in_source');
+ });
+
+ test('the dream.synthesize.quote_verify alias turns it off', async () => {
+ await engine.setConfig('dream.synthesize.quote_verify', 'false');
+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms(), _chat: chat(NARRATIVE) });
+ const page = await engine.getPage('concepts/compounding');
+ expect(page!.compiled_truth).toContain('luck beats skill');
+ expect(page!.frontmatter.unverified_claims).toBeUndefined();
+ });
+});
diff --git a/test/think-quote-verify.test.ts b/test/think-quote-verify.test.ts
new file mode 100644
index 0000000000..7d8a99a921
--- /dev/null
+++ b/test/think-quote-verify.test.ts
@@ -0,0 +1,100 @@
+/**
+ * Quote grounding for think answers and saved syntheses: every quoted span is
+ * checked against exactly the evidence the prompt carried. Exact quotes stay,
+ * near matches are repaired to the evidence's words, quotes found nowhere are
+ * unquoted and marked [unverified] in the live answer, and a saved synthesis
+ * keeps the failing claim out of its body (frontmatter unverified_claims).
+ * Numbers are not checked here (answers compute them). Kill switch:
+ * think.quote_verify.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runThink, persistSynthesis, type ThinkLLMClient } from '../src/core/think/index.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { groundAnswerQuotes, groundSource, verifyBody, UNVERIFIED_QUOTE_MARK } from '../src/core/cycle/synthesize-verify.ts';
+
+let engine: PGLiteEngine;
+
+function stub(answer: string): ThinkLLMClient {
+ return {
+ create: async () => ({
+ id: 'msg_quote', type: 'message', role: 'assistant', model: 'stub', stop_reason: 'end_turn', stop_sequence: null,
+ usage: { input_tokens: 1, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, server_tool_use: null, service_tier: null },
+ content: [{ type: 'text', text: JSON.stringify({ answer, citations: [], gaps: [] }) }],
+ }) as never,
+ };
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await importFromContent(engine, 'meetings/pricing-review',
+ '---\ntype: meeting\ntitle: Pricing review\n---\nAlice Example said "we will move to annual billing in March" and the team agreed. Revenue grew 40 percent.\n',
+ { noEmbed: true, sourceId: 'default' });
+});
+afterAll(async () => { await engine.disconnect(); });
+
+describe('groundAnswerQuotes (pure)', () => {
+ const sources = [groundSource('evidence', 'Alice Example said we will move to annual billing in March. Bob Example asked about seats.')];
+
+ test('exact stays, near match is repaired, a fabricated quote is unquoted and marked', () => {
+ const r = groundAnswerQuotes('She said "we will move to annual billing in March". She also said "we will double prices tomorrow".', sources);
+ expect(r.quote_check).toEqual({ grounded: 1, repaired: 0, unverified: 1 });
+ expect(r.answer).toContain('"we will move to annual billing in March"');
+ expect(r.answer).toContain(`we will double prices tomorrow ${UNVERIFIED_QUOTE_MARK}`);
+ expect(r.answer).not.toContain('"we will double prices tomorrow"');
+ expect(r.unverified_quotes).toEqual([{ text: 'we will double prices tomorrow', reason: 'quote_not_in_source' }]);
+ });
+
+ test('a normalized match is repaired to the evidence words', () => {
+ const r = groundAnswerQuotes('She said “We will move to annual billing in March”.', sources);
+ expect(r.quote_check.unverified).toBe(0);
+ expect(r.quote_check.grounded + r.quote_check.repaired).toBe(1);
+ });
+
+ test('quotes-only mode never flags computed numbers; full mode does', () => {
+ const body = 'Revenue grew 75 percent across 3 quarters.';
+ expect(verifyBody(body, sources, { checks: 'quotes' }).quarantined).toEqual([]);
+ expect(verifyBody(body, sources).quarantined.length).toBeGreaterThan(0);
+ });
+});
+
+describe('think and saved syntheses', () => {
+ test('the live answer is safe; answer_raw keeps what the model wrote', async () => {
+ const r = await runThink(engine, {
+ question: 'annual billing pricing review',
+ client: stub('Per the review, Alice said "we will move to annual billing in March" and later "we will triple prices". Revenue grew 52 percent.'),
+ });
+ expect(r.quote_check).toEqual({ grounded: 1, repaired: 0, unverified: 1 });
+ expect(r.answer).toContain(`we will triple prices ${UNVERIFIED_QUOTE_MARK}`);
+ expect(r.answer_raw).toContain('"we will triple prices"');
+ expect(r.warnings).toContain('QUOTE_NOT_IN_EVIDENCE');
+ expect(r.answer).toContain('52 percent');
+ });
+
+ test('a saved synthesis keeps the failing claim out of its body', async () => {
+ const r = await runThink(engine, {
+ question: 'annual billing decision',
+ client: stub('Alice said "we will move to annual billing in March".\n\nShe also promised "free upgrades for everyone".'),
+ });
+ const saved = await persistSynthesis(engine, r);
+ const page = await engine.getPage(saved.slug);
+ expect(page!.compiled_truth).toContain('annual billing in March');
+ expect(page!.compiled_truth).not.toContain('free upgrades for everyone');
+ const claims = page!.frontmatter.unverified_claims as Array<{ text: string; reason: string }>;
+ expect(claims.map(c => c.reason)).toEqual(['quote_not_in_source']);
+ expect(claims[0]!.text).toContain('free upgrades for everyone');
+ });
+
+ test('think.quote_verify false leaves the answer as written', async () => {
+ await engine.setConfig('think.quote_verify', 'false');
+ try {
+ const r = await runThink(engine, { question: 'annual billing', client: stub('She said "we will triple prices".') });
+ expect(r.answer).toBe('She said "we will triple prices".');
+ expect(r.quote_check).toBeUndefined();
+ } finally {
+ await engine.unsetConfig('think.quote_verify');
+ }
+ });
+});