Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
P8 quote grounding: link display text, inner quote style, editorial brackets and the user's question; retest amendment
garrytanf85bcbdef976
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex 9ffcdd7fa0..ccf323eacf 100644--- a/docs/architecture/key-files/core-cycle-continued.md+++ b/docs/architecture/key-files/core-cycle-continued.md@@ -10,7 +10,7 @@ Synthesis, patterns, consolidation and connector atom gating.- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically. Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private.-- `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). A source built with `groundSource(path, content, { tolerant: true })` (the opt-in coverage: think, concepts, patterns; never dream synthesis) also reads markdown link syntax as its text (repairs drop link targets) and grounds a quote whose words match once closing punctuation and elision marks at its edges are set aside (counted exact). `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` (opt-in, default off) for patterns and concepts; synthesis keeps `dream.synthesize.quote_verify` (default on). `synthesize_concepts` grounds each LLM narrative against the atom titles and bodies its prompt carried before writing (failing units to `unverified_claims`; pinned by `test/cycle/synthesize-concepts-quote-verify.test.ts`).+- `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). A source built with `groundSource(path, content, { tolerant: true })` (the opt-in coverage: think, concepts, patterns; never dream synthesis) also reads markdown link syntax and any other square bracket as plain text (`[Name](target)`, `[Name]` and `Name` match; repairs drop link targets and never carry a `"`), folds `"` to `'`, and counts a quote exact when its words match once the writer's edge punctuation and elision, brackets (including a bracketed letter's case, `[T]he`), editorial insertions in a word (`decide[s]`, `want[ed]`) and inner quote style are set aside. Think also grounds against the user's question. `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors and standalone `[user]` / `[assistant]` / `[system]` role lines (the session-corpus renderer's turn boundaries, so a `Name:` label inside one turn never carries into the next) always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the quote length) and never accepts a match that touches a speaker label (`reason: 'crosses_speakers'`). `verifyBody` splits a body into claim units (`claimUnits`: sentences within a line, whole list items, whole table rows; no boundary inside a quote) and checks each NEW unit: every quote must ground in some source, a quote whose sentence names a transcript speaker must name the speaker of the matched turn, and every numeric/date claim (outside grounded quotes, code, wikilinks and link targets) must appear in a source; 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` (opt-in, default off) for patterns and concepts; synthesis keeps `dream.synthesize.quote_verify` (default on). `synthesize_concepts` grounds each LLM narrative against the atom titles and bodies its prompt carried before writing (failing units to `unverified_claims`; pinned by `test/cycle/synthesize-concepts-quote-verify.test.ts`).- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached, nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`).diff --git a/docs/eval/decisions/p8/PREREGISTRATION.md b/docs/eval/decisions/p8/PREREGISTRATION.mdindex d643f8f98c..9a739b4172 100644--- a/docs/eval/decisions/p8/PREREGISTRATION.md+++ b/docs/eval/decisions/p8/PREREGISTRATION.md@@ -122,3 +122,19 @@ Written before P0 generated any sealed withdrawal-review data.judges them or the data the threshold was tuned on.- **Disclosure.** The verdict record and the PR state that the paraphrase pairs are model-written andcustodian-checked, not human-written. Every other gate in section 3 is unchanged.++### 2026-10-05: quote grounding retest on fresh sealed quotes (section 6)++Written after the section 6 sealed run failed and before any retest data exists.++- **Change.** One retest of section 6 on a fresh sealed set: new held-out questions and quote spans the second+ custodian writes, disjoint from the dev questions and from the first sealed set, sized to at least 300 supported+ spans and clustered by question. The build is the frozen SHA reported with this amendment. Gate, metric, think+ model, judge and cost limit are unchanged: supported spans wrongly flagged, Wilson 95% upper bound ≤ 5%.+- **What changed in the build.** Matcher gaps the second custodian found in the first run's false flags, described+ without sealed text: link display text kept as `[Name]`, the source's inner `"` written as `'`, editorial brackets+ in or at the end of a word, and (a policy decision) the user's question counted as a grounding source. Unit tests+ in `test/think-quote-verify.test.ts`.+- **Reason.** The first sealed run's text informed these fixes, so it can no longer test them; only fresh quotes can.+- **Outcome.** PASS turns `think.quote_verify` and `dream.quote_verify` on by default; FAIL keeps them opt-in. The+ first run's FAIL stays in the verdict record either way.diff --git a/docs/eval/decisions/p8/SEALED_VERDICTS.md b/docs/eval/decisions/p8/SEALED_VERDICTS.mdindex cae549abf9..c5fd3ddaef 100644--- a/docs/eval/decisions/p8/SEALED_VERDICTS.md+++ b/docs/eval/decisions/p8/SEALED_VERDICTS.md@@ -6,7 +6,8 @@ Each part's held-out result, measured by the custodian (P0) against the gates in| Part | Gate | Held-out result | Verdict | Default ||---|---|---|---|---|| Write cost (section 2) | commit-path generative attempts = 0 in both arms | 0 in the extraction-on and extraction-off arms | PASS | Guard on; cost published |-| Quote grounding (section 6) | supported spans wrongly flagged, Wilson 95% upper bound ≤ 5% | 4.7% wrongly flagged, upper bound 7.6% | FAIL | `think.quote_verify` and `dream.quote_verify` off by default (opt-in) |+| Quote grounding (section 6) | supported spans wrongly flagged, Wilson 95% upper bound ≤ 5% | 4.7% wrongly flagged, upper bound 7.6%; the second custodian's rescore with the fixed scorer: 16 of 319 (5.0%), upper bound 8.0% | FAIL | `think.quote_verify` and `dream.quote_verify` off by default (opt-in) |+| Quote grounding retest (section 6, amendment 2026-10-05) | same gate, fresh sealed quotes | pending (second custodian) | — | stays off until PASS || Semantic withdrawal review (section 3) | precision LB ≥ 0.90, end-to-end recall ≥ 0.60, zero proposals on corrected values, N5 unchanged | precision LB 0.970 (124/124 eval families, 248 actions), end-to-end recall 0.977, 0 proposals on corrected values, N5 contracts pass | PASS | `review_withdraw` on (proposes where the conflict slot is on with a TypeSafe key); reference calibration shipped || Advertised tool surface (section 7) | pooled success ≥ control − 3 pts, no leak rise, hidden-tool family ≥ control − 5 pts | pending | — | new installs advertise `full` || HTTP graph freshness (report-only) | remote `put_page`: timeline row at commit; mention links after the `links` effect; typed edges only after extract | as stated, on PGLite (`test/remote-graph-freshness.test.ts`) | REPORT | no switch |@@ -22,10 +23,21 @@ link syntax read as its text, punctuation and elision at a quote's edges) appliesources (`groundSource(…, { tolerant: true })`), because the held-out run measured it only as part of thatcoverage, which failed.-Follow-up: the over-flagging. The dev runs measured 1.3% after the edge-punctuation and link-syntax fix; the-held-out set flags 4.7%, so supported quotes still fail on forms the dev questions did not contain. The next step-is to read the held-out wrongly-flagged spans with the custodian (without tuning on the sealed questions) and-re-run on a fresh held-out set.+Root cause of the over-flagging, from the second custodian's rerun (the sealed text was not shared): the scorer+fix left the verdict unchanged at 16 of 319 supported spans flagged (5.0%, upper bound 8.0%), and most false flags+were matcher gaps in the opt-in tolerance. The tolerant matcher now also accepts:++1. link display text written as `[Name]` without the target, against the source's `[Name](target)`;+2. the source's inner `"` written as `'` inside a quotation (a repair never inserts a `"`);+3. editorial brackets in or at the end of a word: `[T]he` for `the`, `decide[s]` or `want[ed]` for `decide` or+ `want`;+4. a quote of the user's own question (policy decision): the question is a grounding source for think answers.++The custodian estimates about 2.2% wrongly flagged (upper bound 4.5%) after items 1–3, lower with item 4. That is an+estimate, not a verdict: per the 2026-10-05 retest amendment in the preregistration, the second custodian writes a+fresh sealed quote set and runs it against the frozen build with the same gate. Quote grounding stays off by+default until that retest passes. The dream synthesis quote check (`dream.synthesize.quote_verify`) stays+byte-identical to master; none of these changes reach it.## HTTP graph freshness (report-only)diff --git a/src/core/cycle/synthesize-verify.ts b/src/core/cycle/synthesize-verify.tsindex 4befab922d..cfc5ce10af 100644--- a/src/core/cycle/synthesize-verify.ts+++ b/src/core/cycle/synthesize-verify.ts@@ -193,8 +193,8 @@ export function emptyQuoteVerifyStats(): QuoteVerifyStats {* source char desynced every later offset and could slice garbage — or* nothing — back into a page as a "verbatim" repair).*/-export function normalizeForGrounding(s: string, opts: { foldLinks?: boolean } = {}): { norm: string; map: number[] } {- return foldForGrounding(s, true, opts.foldLinks === true) as { norm: string; map: number[] };+export function normalizeForGrounding(s: string, opts: { tolerant?: boolean } = {}): { norm: string; map: number[] } {+ return foldForGrounding(s, true, opts.tolerant === true) as { norm: string; map: number[] };}/**@@ -207,10 +207,10 @@ export function normalizeForGrounding(s: string, opts: { foldLinks?: boolean } =* Parity matters: the rescue gate and the repair ladder must mean the same* thing by "normalized substring of the transcript".*/-function foldForGrounding(s: string, withMap: boolean, foldLinks = false): { norm: string; map: number[] } | string {+function foldForGrounding(s: string, withMap: boolean, tolerant = false): { norm: string; map: number[] } | string {const out: string[] = [];const map: number[] = [];- const skip = foldLinks ? linkSyntaxMask(s) : null;+ const skip = tolerant ? bracketMask(s) : null;let pendingSpace = false;// Iterate by CODE POINT (for..of), not code unit: a surrogate pair// lowercases as a pair (Deseret 𐐀 → 𐐨) but never half by half, so a@@ -233,6 +233,7 @@ function foldForGrounding(s: string, withMap: boolean, foldLinks = false): { nor// grounding agree. One-to-many like the toLowerCase expansions below —// every emitted unit maps to the ellipsis' original index.else if (ch === '…') ch = '...';+ if (tolerant && ch === '"') ch = "'";if (pendingSpace) {out.push(' ');if (withMap) map.push(map.length > 0 ? map[map.length - 1] : i);@@ -250,21 +251,53 @@ function foldForGrounding(s: string, withMap: boolean, foldLinks = false): { norconst MD_LINK = /\[([^\[\]\n]{1,300})\]\([^()\s]{1,500}\)/g;-/** Code-unit offsets of markdown link syntax (`[` and `](target)`): a quote never carries a link target, so the fold reads `[Ana](people/ana)` as `Ana`. */-function linkSyntaxMask(s: string): Set<number> | null {- if (!s.includes('](')) return null;+/**+ * Code-unit offsets the tolerant fold skips: markdown link syntax (`[` and+ * `](target)`, since a quote never carries a link target) and every other+ * square bracket, so `[Ana](people/ana)`, `[Ana]` and `Ana` read alike, and so+ * do an editorial `[T]he` and `The`.+ */+function bracketMask(s: string): Set<number> | null {+ if (!s.includes('[') && !s.includes(']')) return null;const skip = new Set<number>();for (const m of s.matchAll(MD_LINK)) {const at = m.index!;- skip.add(at);for (let k = at + 1 + m[1]!.length; k < at + m[0].length; k++) skip.add(k);}+ for (let i = 0; i < s.length; i++) if (s[i] === '[' || s[i] === ']') skip.add(i);return skip;}-/** A source slice as a reader sees it: link syntax reduced to the link text. */+/** A source slice as a reader sees it, ready to sit inside a quotation: link syntax reduced to the link text, inner double quotes as single. */function displayText(slice: string): string {- return slice.replace(MD_LINK, '$1').replace(/\]\([^()\s]*\)/g, '');+ return slice.replace(MD_LINK, '$1').replace(/\]\([^()\s]*\)/g, '').replace(/"/g, "'");+}++/**+ * Whether `form` is the source's `words` with only the changes a writer may+ * make in a quotation: brackets (link display, editorial), the case of a+ * bracketed letter (`[T]he` for `the`) and the inner quote style.+ */+function sameWords(words: string, form: string): boolean {+ const src = words.replace(/[[\]]/g, '').replace(/["“”]/g, "'");+ let out = '';+ let bracketed = false;+ const loose = new Set<number>();+ for (const ch of form.replace(/["“”]/g, "'")) {+ if (ch === '[' || ch === ']') { bracketed = ch === '['; continue; }+ if (bracketed) loose.add(out.length);+ out += ch;+ }+ if (out.length !== src.length) return false;+ for (let i = 0; i < out.length; i++) {+ if (out[i] !== src[i] && !(loose.has(i) && out[i]!.toLowerCase() === src[i]!.toLowerCase())) return false;+ }+ return true;+}++/** A quote without editorial insertions attached to a word (`decide[s]`, `want[ed]`): the letters are the writer's. */+function withoutInsertions(inner: string): string {+ return inner.replace(/(?<=\p{L})\[\p{L}{1,3}\]/gu, '');}/** A quote's core: the elision marks and closing punctuation writers put at a quotation's edges ("the deal," / "…edge cases o…"). */@@ -298,8 +331,10 @@ export interface GroundedTranscript {turns?: SpeakerTurn[];/*** The opt-in quote grounding's tolerance (think, concepts, patterns): link- * syntax reads as its text, and punctuation or elision at a quote's edges is- * the writer's. Unset (dream synthesis): exact, normalized and near rungs only.+ * syntax reads as its text, and the writer's punctuation or elision at a+ * quote's edges, brackets (`[Name]`, `[T]he`, `decide[s]`) and inner quote+ * style (`'` for the source's `"`) do not change its words. Unset (dream+ * synthesis): exact, normalized and near rungs only.*/tolerant?: boolean;}@@ -499,7 +534,7 @@ function numbersBySpeaker(content: string, turns: SpeakerTurn[]): Map<string, Se/** Prepare one transcript for verification. */export function groundSource(path: string, content: string, opts: { tolerant?: boolean } = {}): GroundedSource {- const { norm, map } = normalizeForGrounding(content, { foldLinks: opts.tolerant });+ const { norm, map } = normalizeForGrounding(content, { tolerant: opts.tolerant });const turns = parseSpeakerTurns(content);const name = basename(path);return {@@ -601,14 +636,15 @@ const PUNCT_EDGE = /[.,;:!?]/;*/export function groundQuote(inner: string, t: GroundedTranscript): GroundResult {if (!t.tolerant) return groundQuoteSpan(inner, t, true);- const whole = groundQuoteSpan(inner, t, false);- if (whole.status !== 'none') return whole;- const core = quoteCore(inner);- if (core !== inner && core.split(/\s+/).filter(Boolean).length >= 2) {- // Punctuation or elision marks at the edges are the writer's, not the source's: the words themselves are grounded.- const r = groundQuoteSpan(core, t, false);- if (r.status === 'exact' || (r.status === 'normalized' && r.replacement === core)) return { status: 'exact', spans: r.spans };- if (r.status !== 'none') return r;+ const bare = withoutInsertions(inner);+ const forms = [...new Set([inner, quoteCore(inner), bare, quoteCore(bare)])]+ .filter((form, i) => i === 0 || form.split(/\s+/).filter(Boolean).length >= 2);+ for (const form of forms) {+ const r = groundQuoteSpan(form, t, false);+ if (r.status === 'none') continue;+ // Edge punctuation, editorial brackets, link display and inner quote style are the writer's: the words themselves are grounded.+ if (r.status === 'exact' || sameWords(r.replacement, form)) return { status: 'exact', spans: r.spans };+ return r;}return groundQuoteSpan(inner, t, true);}@@ -624,7 +660,7 @@ function groundQuoteSpan(inner: string, t: GroundedTranscript, near: boolean): G}if (exact.length) return { status: 'exact', spans: exact };- const q = normalizeForGrounding(inner, { foldLinks: t.tolerant });+ const q = normalizeForGrounding(inner, { tolerant: t.tolerant });const shown = (slice: string) => t.tolerant ? displayText(slice) : slice;if (q.norm.length === 0) return { status: 'none', reason: 'not_found' };diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 87bb7bdda4..5bbea966ef 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -962,7 +962,7 @@ export async function runThink(return {question: opts.question,- answer: response.answer, ...(synthesisStatus === 'ok' ? await groundThinkAnswer(engine, response.answer, [pagesBlock, takesBlock, graphBlock ?? '', trajectoryBlock], warnings) : {}),+ answer: response.answer, ...(synthesisStatus === 'ok' ? await groundThinkAnswer(engine, response.answer, [opts.question, pagesBlock, takesBlock, graphBlock ?? '', trajectoryBlock], warnings) : {}),citations: resolved.citations,gaps: response.gaps,pagesGathered: gather.pages.length,@@ -1124,7 +1124,8 @@ 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+ * the prompt carried, the user's question included (quoting the question back+ * is supported). 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).*/diff --git a/test/think-quote-verify.test.ts b/test/think-quote-verify.test.tsindex c65df71e2f..8d0ac13c7c 100644--- a/test/think-quote-verify.test.ts+++ b/test/think-quote-verify.test.ts@@ -70,6 +70,30 @@ describe('groundAnswerQuotes (pure)', () => {expect(r.answer).not.toContain('](');});+ test('link display text kept as [Name] without its target grounds against the linked source', () => {+ const linked = [groundSource('evidence', '[Elena Example](people/elena-example) said the [Meridian](companies/meridian-example) deal is moving faster than expected.', { tolerant: true })];+ const r = groundAnswerQuotes('Notes: "[Elena Example] said the [Meridian] deal is moving faster than expected".', linked);+ expect(r.quote_check).toEqual({ grounded: 1, repaired: 0, unverified: 0 });+ expect(r.answer).toContain('"[Elena Example] said the [Meridian] deal is moving faster than expected"');+ });++ test("the source's inner double quotes written as single quotes inside a quotation still ground, and repairs never carry a double quote", () => {+ const quoted = [groundSource('evidence', 'Bob Example wrote that the plan is "ship it by Friday" and moved on.', { tolerant: true })];+ const r = groundAnswerQuotes('He wrote "the plan is \'ship it by Friday\' and moved on".', quoted);+ expect(r.quote_check).toEqual({ grounded: 1, repaired: 0, unverified: 0 });+ const repaired = groundAnswerQuotes('He wrote "The Plan is \'ship it by Friday\'".', quoted);+ expect(repaired.quote_check.unverified).toBe(0);+ expect(repaired.answer).toBe('He wrote "the plan is \'ship it by Friday\'".');+ });++ test('editorial brackets inside or at the end of a word ground: [T]he, decide[s], want[ed]', () => {+ const src = [groundSource('evidence', 'Carol Example said the board will decide the budget once we want clarity on hiring.', { tolerant: true })];+ const r = groundAnswerQuotes('She said "[T]he board will decide the budget", that it "decide[s] the budget once we want[ed] clarity on hiring".', src);+ expect(r.quote_check).toEqual({ grounded: 2, repaired: 0, unverified: 0 });+ expect(r.answer).toContain('"decide[s] the budget once we want[ed] clarity on hiring"');+ expect(groundAnswerQuotes('She said "the board will decide[s] the payroll".', src).quote_check.unverified).toBe(1);+ });+test('the tolerance is opt-in coverage only: a default source (dream synthesis) grounds as before', () => {const text = 'She said "the Meridian deal," twice.';const evidence = 'Elena said the [Meridian](companies/meridian-example) deal is moving faster than expected.';@@ -97,6 +121,12 @@ describe('think and saved syntheses', () => {expect(r.answer).toContain('52 percent');});+ test("a quote of the user's own question counts as supported", async () => {+ const question = 'did we agree to move pricing to annual billing for enterprise seats';+ const r = await runThink(engine, { question, client: stub(`You asked "did we agree to move pricing to annual billing for enterprise seats": yes, Alice said "we will move to annual billing in March".`) });+ expect(r.quote_check).toEqual({ grounded: 2, repaired: 0, unverified: 0 });+ });+test('a saved synthesis keeps the failing claim out of its body', async () => {const r = await runThink(engine, {question: 'annual billing decision',