Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(synthesize): quote grounding skips markdown inline markup and exempts the prompt's cycle date (#6258)

time-attack6461dc50d528
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index 9300fddd11..14a74f3b99 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -11,7 +11,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 })` (think, concepts and patterns; never dream synthesis) also reads markdown link syntax and any other square bracket as plain text (`[Name](target)`, `[Name]` and `Name` match; repairs drop link targets and never carry a `"`), folds `"` to `'`, and counts a quote exact when its words match once the writer's edge punctuation and elision, brackets (including a bracketed letter's case, `[T]he`), editorial insertions in a word (`decide[s]`, `want[ed]`) and inner quote style are set aside. Think also grounds against the user's question. `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors and standalone `[user]` / `[assistant]` / `[system]` role lines (the session-corpus renderer's turn boundaries, so a `Name:` label inside one turn never carries into the next) always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the quote length) and never accepts a match that touches a speaker label (`reason: 'crosses_speakers'`). `verifyBody` splits a body into claim units (`claimUnits`: sentences within a line, whole list items, whole table rows; no boundary inside a quote) and checks each NEW unit: every quote must ground in some source, a quote whose sentence names a transcript speaker must name the speaker of the matched turn, and every numeric/date claim (outside grounded quotes, code, wikilinks and link targets) must appear in a source; a unit saying a named speaker decided, agreed, committed or will act (and recording no proposal, refusal or negation) must carry only numbers and dates that speaker stated, or that the turn they explicitly accepted stated (`numbersBySpeaker`; bare years and numbers no turn states are not attributed). Any failure removes the whole unit from the body; `verifyDreamPage` records it in frontmatter `unverified_claims` (`text`, `reason` = `quote_not_in_source` / `quote_crosses_speakers` / `speaker_mismatch` / `number_not_in_source` / `decision_misattributed`, `detail`, `sources`, `detected_at`) and records every grounded quote's source path, character span and speaker in `grounding.quotes`; records from the pre-run revision carry forward, capped at 100 / 200. Frontmatter is neither chunked nor searched, so quarantined claims stay reviewable through `get_page` but out of search, recall, think and context packs. A page whose every unit failed keeps `ALL_CLAIMS_QUARANTINED_BODY`. Scope (`verifyAndRepairDreamPages(engine, refs, transcriptsByPath, { since, sinceByTranscript, checkedAt })`): sources are the transcripts of every child that wrote the page; the page epoch is the child's first write to that page (`first_write_at` on the ref) when known, so a page another writer created while the child ran is diffed rather than treated as the run's own; otherwise the earliest `loadChildWriteEpochs` entry of its sources (child job `created_at`, so resumed or coalesced children keep their original epoch), else `since` (`readVerifyEpoch`, taken before fan-out). Pages created at or after the epoch are verified whole; older pages are verified only on units absent from their pre-epoch revision (`loadPreRunRevision`: the first `page_versions` snapshot at or after the epoch; none means the page was not overwritten → `skipped_unchanged`). Write-back goes through `importFromContent` (`noEmbed`; the phase-end embed sweep backfills) with a `beforeCommit` that re-projects timeline entries, facts, takes (`prepareCanonicalProjections` as a `preserving` writer bound to the page's current snapshot) and automatic links (`prepareAutomaticLinks`) from the verified body in the same transaction, so no derived row outlives its quarantined claim while database-only timeline history is kept. `verifyBody` skips units inside a validly marked bullet (`materializedHistoryRanges`) only when that bullet is absent from the pre-run revision, i.e. it was materialized from the database during the run; a new page gets no exemption, and a claim added under a marked bullet that already existed is verified. Fail-open per page (read-back miss / write throw → `errors` + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts`, the write-path mini-eval `test/cycle-write-path-mini-eval.test.ts`, and the three-cycle repeated-consolidation pin `test/cycle-repeated-consolidation.test.ts` (harness `test/helpers/repeated-consolidation.ts`, printable run `scripts/repeated-consolidation-experiment.ts`). System One S8: `verifyBody` also returns `groundingUnits` (new units that pass only because they carry no quote, number or attribution; ≥5 words, not headings) without changing any other field; `verifyDreamPage` returns them per body, `verifyAndRepairDreamPages` takes an optional `grounding: GroundingPass` applied before write-back, and `quarantineUnits` removes S8-rejected units into `unverified_claims` with reason `unsupported_paraphrase`. `verifyBody(…, { checks: 'quotes' })` grounds quotes and speaker attribution only (no number, date or decision checks) for writers that legitimately derive numbers. `groundAnswerQuotes` is the span-level variant for live answers. `dreamQuoteVerifyEnabled` reads `dream.quote_verify` (default on) for patterns and concepts; synthesis keeps `dream.synthesize.quote_verify` (default on). `synthesize_concepts` grounds each LLM narrative against the atom titles and bodies its prompt carried before writing (failing units to `unverified_claims`; pinned by `test/cycle/synthesize-concepts-quote-verify.test.ts`). `groundingUnits` (the opt-in S8 input) lists every substantive new passing unit (not a heading, at least five words), quoted, attributed and numeric ones included, with its final quote repairs. Pinned by `test/cycle-synthesize-grounding-coverage.test.ts`.
+- `src/core/cycle/synthesize-verify.ts` — Mechanical claim verification on every page a synthesis child wrote (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/ellipsis/case folding, skipping markdown inline markup (`*`, backticks, `~~`; not `_`), WITH an offset map back to the original string, so every replacement is a verbatim transcript slice; a slice that differs from the quote only by that markup counts exact and is not spliced in) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). A source built with `groundSource(path, content, { tolerant: true })` (think, concepts and patterns; never dream synthesis) also reads markdown link syntax and any other square bracket as plain text (`[Name](target)`, `[Name]` and `Name` match; repairs drop link targets and never carry a `"`), folds `"` to `'`, and counts a quote exact when its words match once the writer's edge punctuation and elision, brackets (including a bracketed letter's case, `[T]he`), editorial insertions in a word (`decide[s]`, `want[ed]`) and inner quote style are set aside. Think also grounds against the user's question. `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors and standalone `[user]` / `[assistant]` / `[system]` role lines (the session-corpus renderer's turn boundaries, so a `Name:` label inside one turn never carries into the next) always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the quote length) and never accepts a match that touches a speaker label (`reason: 'crosses_speakers'`). `verifyBody` splits a body into claim units (`claimUnits`: sentences within a line, whole list items, whole table rows; no boundary inside a quote) and checks each NEW unit: every quote must ground in some source, a quote whose sentence names a transcript speaker must name the speaker of the matched turn, and every numeric/date claim (outside grounded quotes, code, wikilinks and link targets) must appear in a source (`verifyDreamPage` exempts the ISO cycle date `checkedAt`, which the synthesis prompt gave the child as today, via `verifyBody`'s `exemptNumericKeys`); a unit saying a named speaker decided, agreed, committed or will act (and recording no proposal, refusal or negation) must carry only numbers and dates that speaker stated, or that the turn they explicitly accepted stated (`numbersBySpeaker`; bare years and numbers no turn states are not attributed). Any failure removes the whole unit from the body; `verifyDreamPage` records it in frontmatter `unverified_claims` (`text`, `reason` = `quote_not_in_source` / `quote_crosses_speakers` / `speaker_mismatch` / `number_not_in_source` / `decision_misattributed`, `detail`, `sources`, `detected_at`) and records every grounded quote's source path, character span and speaker in `grounding.quotes`; records from the pre-run revision carry forward, capped at 100 / 200. Frontmatter is neither chunked nor searched, so quarantined claims stay reviewable through `get_page` but out of search, recall, think and context packs. A page whose every unit failed keeps `ALL_CLAIMS_QUARANTINED_BODY`. Scope (`verifyAndRepairDreamPages(engine, refs, transcriptsByPath, { since, sinceByTranscript, checkedAt })`): sources are the transcripts of every child that wrote the page; the page epoch is the child's first write to that page (`first_write_at` on the ref) when known, so a page another writer created while the child ran is diffed rather than treated as the run's own; otherwise the earliest `loadChildWriteEpochs` entry of its sources (child job `created_at`, so resumed or coalesced children keep their original epoch), else `since` (`readVerifyEpoch`, taken before fan-out). Pages created at or after the epoch are verified whole; older pages are verified only on units absent from their pre-epoch revision (`loadPreRunRevision`: the first `page_versions` snapshot at or after the epoch; none means the page was not overwritten → `skipped_unchanged`). Write-back goes through `importFromContent` (`noEmbed`; the phase-end embed sweep backfills) with a `beforeCommit` that re-projects timeline entries, facts, takes (`prepareCanonicalProjections` as a `preserving` writer bound to the page's current snapshot) and automatic links (`prepareAutomaticLinks`) from the verified body in the same transaction, so no derived row outlives its quarantined claim while database-only timeline history is kept. `verifyBody` skips units inside a validly marked bullet (`materializedHistoryRanges`) only when that bullet is absent from the pre-run revision, i.e. it was materialized from the database during the run; a new page gets no exemption, and a claim added under a marked bullet that already existed is verified. Fail-open per page (read-back miss / write throw → `errors` + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts`, the write-path mini-eval `test/cycle-write-path-mini-eval.test.ts`, and the three-cycle repeated-consolidation pin `test/cycle-repeated-consolidation.test.ts` (harness `test/helpers/repeated-consolidation.ts`, printable run `scripts/repeated-consolidation-experiment.ts`). System One S8: `verifyBody` also returns `groundingUnits` (new units that pass only because they carry no quote, number or attribution; ≥5 words, not headings) without changing any other field; `verifyDreamPage` returns them per body, `verifyAndRepairDreamPages` takes an optional `grounding: GroundingPass` applied before write-back, and `quarantineUnits` removes S8-rejected units into `unverified_claims` with reason `unsupported_paraphrase`. `verifyBody(…, { checks: 'quotes' })` grounds quotes and speaker attribution only (no number, date or decision checks) for writers that legitimately derive numbers. `groundAnswerQuotes` is the span-level variant for live answers. `dreamQuoteVerifyEnabled` reads `dream.quote_verify` (default on) for patterns and concepts; synthesis keeps `dream.synthesize.quote_verify` (default on). `synthesize_concepts` grounds each LLM narrative against the atom titles and bodies its prompt carried before writing (failing units to `unverified_claims`; pinned by `test/cycle/synthesize-concepts-quote-verify.test.ts`). `groundingUnits` (the opt-in S8 input) lists every substantive new passing unit (not a heading, at least five words), quoted, attributed and numeric ones included, with its final quote repairs. Pinned by `test/cycle-synthesize-grounding-coverage.test.ts`.
- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached, nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`). #5145: completed synthesis is partitioned out BEFORE the triage pass on every path (classic, managed and dry run) by `partitionCompletedSynthesis` in `src/core/cycle/synthesize-completion.ts` (which also holds the legacy / synth-v2 completion-key helpers); details carry `synthesis_state: {candidates, already_synthesized}` and the triage counters cover only screened candidates.
diff --git a/src/core/cycle/synthesize-verify.ts b/src/core/cycle/synthesize-verify.ts
index a125504de1..9c7d9aff1f 100644
--- a/src/core/cycle/synthesize-verify.ts
+++ b/src/core/cycle/synthesize-verify.ts
@@ -183,7 +183,8 @@ export function emptyQuoteVerifyStats(): QuoteVerifyStats {
* buildTriageMapBlock's quote filter via the mapless `normForGrounding`).
*
* Folds: whitespace runs → single space, curly quotes/apostrophes → straight,
- * unicode dashes → '-', case → lower. `map[i]` = index in the ORIGINAL string
+ * unicode dashes → '-', case → lower; markdown inline markup (`*`, backticks,
+ * `~~`) is skipped (`foldSkipSet`). `map[i]` = index in the ORIGINAL string
* of the character that produced `norm[i]`, so any match in normalized space
* maps back to a VERBATIM original slice (outside-voice amendment: without
* the map, "replace with verbatim span" would not be verbatim).
@@ -211,7 +212,7 @@ export function normalizeForGrounding(s: string, opts: { tolerant?: boolean } =
function foldForGrounding(s: string, withMap: boolean, tolerant = false): { norm: string; map: number[] } | string {
const out: string[] = [];
const map: number[] = [];
- const skip = tolerant ? bracketMask(s) : null;
+ const skip = foldSkipSet(s, tolerant);
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
@@ -269,6 +270,37 @@ function bracketMask(s: string): Set<number> | null {
return skip;
}
+/**
+ * Code-unit offsets the fold skips: markdown inline markup (every `*`, every
+ * backtick, and `~` in a `~~` run) in both modes, so `**sync**`, `` `sync` ``
+ * and `sync` read alike; plus `bracketMask` in tolerant mode. `_` is kept:
+ * it is too common in identifiers and paths.
+ */
+function foldSkipSet(s: string, tolerant: boolean): Set<number> | null {
+ const brackets = tolerant ? bracketMask(s) : null;
+ if (!/[*`]|~~/.test(s)) return brackets;
+ const skip = brackets ?? new Set<number>();
+ for (let i = 0; i < s.length; i++) {
+ const ch = s[i];
+ if (ch === '*' || ch === '`' || (ch === '~' && (s[i - 1] === '~' || s[i + 1] === '~'))) skip.add(i);
+ }
+ return skip;
+}
+
+/**
+ * `s` without the inline markup `foldSkipSet` skips in strict mode. A source
+ * slice that differs from a quote only by these marks says the quote's exact
+ * words, so it grounds as exact rather than splicing in a `**` the slice may
+ * leave unbalanced.
+ */
+function withoutInlineMarkup(s: string): string {
+ const skip = foldSkipSet(s, false);
+ if (!skip) return s;
+ let out = '';
+ for (let i = 0; i < s.length; i++) if (!skip.has(i)) out += s[i];
+ return out;
+}
+
/** 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, '').replace(/"/g, "'");
@@ -679,7 +711,8 @@ function groundQuoteSpan(inner: string, t: GroundedTranscript, near: boolean): G
const [start, end] = normalized[0];
const replacement = shown(t.content.slice(start, end));
if (replacement.length === 0) return { status: 'none', reason: 'not_found' };
- return replacement === inner ? { status: 'exact', spans: normalized } : { status: 'normalized', replacement, spans: normalized };
+ const same = replacement === inner || withoutInlineMarkup(replacement) === withoutInlineMarkup(inner);
+ return same ? { status: 'exact', spans: normalized } : { status: 'normalized', replacement, spans: normalized };
}
// Rung 3: near match. Anchor on word trigrams from the quote; score
@@ -796,10 +829,13 @@ function numericClaims(text: string): Array<{ raw: string; claim: string; keys:
* Numeric and date claims in `text` that no source states. `text` must
* already be masked (code, links) and have grounded quotes blanked. A claim
* is supported when any of its canonical keys appears among a source's
- * numbers, or its normalized text occurs in a source or its file name.
+ * numbers or in `exemptNumericKeys` (facts the writer's prompt supplied,
+ * such as `date:<cycle date>`), or its normalized text occurs in a source or
+ * its file name.
*/
-export function unsupportedNumericClaims(text: string, sources: GroundedSource[]): string[] {
+export function unsupportedNumericClaims(text: string, sources: GroundedSource[], exemptNumericKeys?: ReadonlySet<string>): string[] {
return numericClaims(text)
+ .filter(({ keys }) => !keys.some(k => exemptNumericKeys?.has(k)))
.filter(({ claim, keys }) => !sources.some(src =>
keys.some(k => src.numbers.has(k)) || src.norm.includes(claim) || src.nameNorm.includes(claim)))
.map(({ raw }) => raw);
@@ -991,7 +1027,7 @@ function clip(s: string, n = PROVENANCE_TEXT_CHARS): string {
* their speaker attribution only (no number, date or decision checks), for
* writers whose prose legitimately derives numbers from its sources.
*/
-export function verifyBody(body: string, sources: GroundedSource[], opts: { priorNorm?: string; checks?: 'all' | 'quotes' } = {}): BodyVerification {
+export function verifyBody(body: string, sources: GroundedSource[], opts: { priorNorm?: string; checks?: 'all' | 'quotes'; exemptNumericKeys?: ReadonlySet<string> } = {}): 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 };
@@ -1051,7 +1087,7 @@ export function verifyBody(body: string, sources: GroundedSource[], opts: { prio
}
const unquoted = blank(masked.slice(u.start, u.end), quoteRanges);
// Quotes-only mode (answers that legitimately compute numbers): no number or decision checks.
- const numbers = opts.checks === 'quotes' ? [] : unsupportedNumericClaims(unquoted, sources);
+ const numbers = opts.checks === 'quotes' ? [] : unsupportedNumericClaims(unquoted, sources, opts.exemptNumericKeys);
for (const n of numbers) fail('number_not_in_source', n);
if (numbers.length === 0 && opts.checks !== 'quotes') {
for (const n of misattributedDecisionClaims(unquoted, attribution, sources, [...mentioned.keys()])) {
@@ -1142,6 +1178,11 @@ export interface GroundingPass {
apply(page: VerifiedDreamPage, sources: GroundedSource[], subject: string, checkedAt: string): Promise<VerifiedDreamPage>;
}
+/**
+ * Verify both bodies of one dream page. `checkedAt` is the cycle date the
+ * synthesis prompt gave the child as today's date, so a page stating that ISO
+ * date is not flagged `number_not_in_source`; every other date still is.
+ */
export function verifyDreamPage(
page: VerifiablePage,
sources: GroundedSource[],
@@ -1149,8 +1190,9 @@ export function verifyDreamPage(
stats: QuoteVerifyStats,
): VerifiedDreamPage {
const priorNorm = opts.prior ? normForGrounding(`${opts.prior.compiled_truth}\n${opts.prior.timeline ?? ''}`) : undefined;
- const truth = verifyBody(page.compiled_truth ?? '', sources, { priorNorm });
- const timeline = verifyBody(page.timeline ?? '', sources, { priorNorm });
+ const exemptNumericKeys = new Set([`date:${opts.checkedAt}`]);
+ const truth = verifyBody(page.compiled_truth ?? '', sources, { priorNorm, exemptNumericKeys });
+ const timeline = verifyBody(page.timeline ?? '', sources, { priorNorm, exemptNumericKeys });
stats.pages_checked++;
for (const r of [truth, timeline]) {
stats.quotes_total += r.quotes;
diff --git a/test/cycle-synthesize-verify.test.ts b/test/cycle-synthesize-verify.test.ts
index 5b5977463d..f7b74244a9 100644
--- a/test/cycle-synthesize-verify.test.ts
+++ b/test/cycle-synthesize-verify.test.ts
@@ -404,6 +404,9 @@ describe('normalizeForGrounding — multi-code-unit case folding (security-revie
' leading and trailing ',
'plain ascii already normalized',
'',
+ 'run `gbrain doctor` to check the **sync** step', // #6258: inline markup is skipped on both paths
+ '用户: **重要发现**:gbrain ~~old~~ ~5 my_var ```code```',
+ '[**Ana**](people/ana) said *this*',
];
for (const c of cases) {
expect(normForGrounding(c)).toBe(normalizeForGrounding(c).norm);
diff --git a/test/synthesize-verify-markup.test.ts b/test/synthesize-verify-markup.test.ts
new file mode 100644
index 0000000000..bcf7d2cf50
--- /dev/null
+++ b/test/synthesize-verify-markup.test.ts
@@ -0,0 +1,90 @@
+/**
+ * #6258 — grounding treats markdown inline markup (`**`, backticks, `~~`) as
+ * formatting, not words, on both the transcript and the page side, and the
+ * cycle date the synthesis prompt supplied as "today" is not an invented date.
+ */
+import { describe, test, expect } from 'bun:test';
+import {
+ emptyQuoteVerifyStats,
+ groundSource,
+ normalizeForGrounding,
+ normForGrounding,
+ verifyBody,
+ verifyDreamPage,
+} from '../src/core/cycle/synthesize-verify.ts';
+
+describe('grounding folds markdown inline markup (#6258)', () => {
+ test('CJK quote of a bolded source phrase grounds exact and the page keeps its quote', () => {
+ const src = groundSource('/t/2026-09-04-chat.md', '用户: **重要发现**:gbrain 是 Garry 的项目,而且规模不小。');
+ const body = '他说 "重要发现:gbrain 是 Garry 的项目,而且规模不小。"';
+ const r = verifyBody(body, [src]);
+ expect(r.failures.quote_not_in_source).toBe(0);
+ expect(r.quarantined).toHaveLength(0);
+ expect(r.exact).toBe(1);
+ expect(r.body).toBe(body);
+ });
+
+ test('quote of a source with inline code and bold grounds', () => {
+ const src = groundSource('/t/chat.md', 'user: You should run `gbrain doctor` to check the **sync** step.');
+ const body = 'He said "run gbrain doctor to check the sync step" before shipping.';
+ const r = verifyBody(body, [src]);
+ expect(r.failures.quote_not_in_source).toBe(0);
+ expect(r.quarantined).toHaveLength(0);
+ expect(r.exact).toBe(1);
+ });
+
+ test('page-side markup and strikethrough fold too; a case difference still repairs to a verbatim slice', () => {
+ const src = groundSource('/t/chat.md', 'user: We ~~might~~ will ship the importer on Friday for real.');
+ const r = verifyBody('She said "we **might** will ship the `importer` on friday for real."', [src]);
+ expect(r.quarantined).toHaveLength(0);
+ expect(r.normalized).toBe(1);
+ expect(r.body).toBe('She said "We ~~might~~ will ship the importer on Friday for real."');
+ });
+
+ test('a fabricated quote wrapped in markup still flags', () => {
+ const src = groundSource('/t/chat.md', 'user: You should run `gbrain doctor` to check the **sync** step.');
+ const r = verifyBody('He said "run **gbrain repair** to delete the `sync` step"', [src]);
+ expect(r.failures.quote_not_in_source).toBe(1);
+ });
+
+ test('`_` and a lone `~` are still words', () => {
+ expect(normForGrounding('my_var ~5 min')).toBe('my_var ~5 min');
+ expect(normForGrounding('**a** `b` ~~c~~ ~~~d')).toBe('a b c d');
+ });
+
+ test('the offset map points every kept non-space code unit at its original index', () => {
+ const s = 'run `gbrain doctor` **now**';
+ const { norm, map } = normalizeForGrounding(s);
+ expect(norm).toBe('run gbrain doctor now');
+ expect(map.length).toBe(norm.length);
+ for (let i = 0; i < norm.length; i++) if (norm[i] !== ' ') expect(s[map[i]!]!.toLowerCase()).toBe(norm[i]!);
+ const at = norm.indexOf('gbrain doctor now');
+ expect(s.slice(map[at], map[at + 'gbrain doctor now'.length - 1]! + 1)).toBe('gbrain doctor` **now');
+ });
+
+ test('tolerant sources fold markup alongside link syntax', () => {
+ const src = groundSource('/t/notes.md', 'The **[launch plan](plans/launch)** needs a `migration` step first.', { tolerant: true });
+ const r = verifyBody('It said "the launch plan needs a migration step first"', [src], { checks: 'quotes' });
+ expect(r.quarantined).toHaveLength(0);
+ });
+});
+
+describe('the cycle date the prompt supplied is not an invented date (#6258)', () => {
+ const src = groundSource('/t/2026-09-04-chat.md', 'user: I fixed the importer bug today.');
+
+ test('verifyDreamPage exempts checkedAt and still flags another absent date', () => {
+ const page = verifyDreamPage(
+ { compiled_truth: 'On 2026-10-06 the user fixed the importer bug.\n\nThe follow-up is due 2026-10-20 at the latest.', timeline: '', frontmatter: {} },
+ [src], { prior: null, checkedAt: '2026-10-06' }, emptyQuoteVerifyStats());
+ const records = (page.frontmatter.unverified_claims ?? []) as Array<{ reason: string; detail: string }>;
+ expect(records.map(r => [r.reason, r.detail])).toEqual([['number_not_in_source', '2026-10-20']]);
+ expect(page.compiled_truth).toContain('On 2026-10-06 the user fixed the importer bug.');
+ });
+
+ test('verifyBody exempts only the keys it is given', () => {
+ const body = 'On 2026-10-06 the user fixed the importer bug.';
+ expect(verifyBody(body, [src]).failures.number_not_in_source).toBe(1);
+ expect(verifyBody(body, [src], { exemptNumericKeys: new Set(['date:2026-10-06']) }).failures.number_not_in_source).toBe(0);
+ expect(verifyBody('On October 6th the user fixed the importer bug.', [src], { exemptNumericKeys: new Set(['date:2026-10-06']) }).failures.number_not_in_source).toBe(1);
+ });
+});