Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): strict quote_verify grounds a verbatim quote with closing punctuation inside the marks (#6952)
time-attackaea1824ea6c4
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.mdindex 7bcb35eba8..957ba9eec0 100644--- a/docs/architecture/key-files/core-cycle-patterns.md+++ b/docs/architecture/key-files/core-cycle-patterns.md@@ -9,7 +9,7 @@ Patterns, drift reports and the cycle modules listed after them.- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. `cycle.consolidate.enabled` (default on; an explicit falsy value returns `skipped`, #6667) is read inside the phase; `dream --phase consolidate --once` bypasses it. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically. Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private. #5575 ENG-3: fact tiers are read per bucket and external_untrusted facts cluster in a separate pass, so an external claim never shares a take with owner facts. Each cluster's take is written at `derive:consolidate` = min(cluster fact tiers, agent_written): unmanaged, the take insert or re-promotion, consolidation marks and valid_until writeback are one `derivedMaintenanceTransaction` (a re-promotion lowers the existing take to min(existing, cluster), even a resolved one); managed, the request carries `declareDerivation`. Edges: take -> every cluster fact. The unmanaged path runs the write gate (`decideTakeWrite`, config read once per run via `loadImportSanityConfig`) on each... (line truncated to 2000 chars)-- `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... (line truncated to 2000 chars)+- `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. In strict mode (dream synthesis) a quote that misses whole is retried on its core (`quoteCore`: edge elision and closing punctuation set aside) at the exact and normalized rungs; an exact core keeps the writer's quote, a normalized core is replaced by the verbatim source slice. `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... (line truncated to 2000 chars)- `src/core/cycle/triage-backoff.ts` — Backoff for unreliable dream-triage verdicts (#6069). `runTriagePass` calls `recordUnreliableTriage` for a truncated, refused or unparseable judge response: it upserts a `dream_verdicts` marker through `putDreamVerdict` (`score` NULL, `content_type` `triage_unreliable`, reasons `unreliable:<kind>` + `attempt:<n>`, the triage model and `TRIAGE_VERSION`) and writes one stderr line with the stop reason, response length and a 12-hex sha256 prefix, never the response text. A row that is a valid verdict for the current model is kept, and a cancelled run writes nothing. `backoffUntil` defers judging while the marker for the same model and version is younger than 24h × 2^(attempt−1), capped at 7 days; `force` (`dream retriage --force`), a model change or a content-hash change re-judges at once. Every score reader (`isTriageCacheValid`, retriage, triage-decide, the rescue gate) treats the NULL score as a miss; the 30-day TTL sweep removes old markers. `TRIAGE_BACKOFF_WHY` / `TRIAGE_BACKOFF_FIX` feed `details.triage.unreliable_backoff`. Pinned by `test/synthesize-triage-backoff.test.ts`. GBRA-130 B-6: `VerdictCacheWrites` isolates each verdict write (`synthesize.triage_verdict_cache`): a refused write is listed in `details.triage.verdict_cache_failures` and its verdict still decides the pass; a 22P02/22P05 refusal backs off as `uncacheable`. Both engines' `putDreamVerdict` apply `wellFormedJson`. Pinned by `test/pathological/b6-triage-verdict-surrogate.test.ts`.- `src/core/cycle/attribution-checks.ts` — #5425 [UC4]: `dream.attribution_checks` (`ATTRIBUTION_CHECKS_KEY`, registered in `KNOWN_CONFIG_KEYS`; `config set` takes a boolean word through `CYCLE_GUARDED_KEYS` in `cycle/config-guards.ts`), the one default-off switch for the two mechanical attribution checks: the propose_takes holder downgrade (`propose-takes-attribution.ts`) and the synthesis `superseded_in_source` quarantine (`synthesize-verify.ts`). `attributionChecksEnabled(engine)` is `isConfigTruthy` over the stored value and false on any read error. The default flips only on a held-out gbrain-evals receipt, the same bar as the prompt rules `dream.synthesize.attribution_rules` / `dream.propose_takes.attribution_rules`.diff --git a/src/core/cycle/synthesize-verify.ts b/src/core/cycle/synthesize-verify.tsindex 1d36d02d15..a317627770 100644--- a/src/core/cycle/synthesize-verify.ts+++ b/src/core/cycle/synthesize-verify.ts@@ -686,7 +686,7 @@ const PUNCT_EDGE = /[.,;:!?]/;* in another's mouth.*/export function groundQuote(inner: string, t: GroundedTranscript): GroundResult {- if (!t.tolerant) return groundQuoteSpan(inner, t, true);+ if (!t.tolerant) return groundStrictQuote(inner, t);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);@@ -700,6 +700,21 @@ export function groundQuote(inner: string, t: GroundedTranscript): GroundResultreturn groundQuoteSpan(inner, t, true);}+/**+ * Strict grounding (dream synthesis). A quote that misses only because the+ * writer put closing punctuation or elision inside the marks grounds on its+ * core: an exact core keeps the writer's edges, a normalized core is replaced+ * by the verbatim source slice. No bracket or quote-style folding.+ */+function groundStrictQuote(inner: string, t: GroundedTranscript): GroundResult {+ const full = groundQuoteSpan(inner, t, true);+ if (full.status !== 'none') return full;+ const core = quoteCore(inner);+ if (core === inner || core.split(/\s+/).filter(Boolean).length < 2) return full;+ const r = groundQuoteSpan(core, t, false);+ return r.status === 'none' ? full : r;+}+function groundQuoteSpan(inner: string, t: GroundedTranscript, near: boolean): GroundResult {let crossed = false;diff --git a/test/cycle-synthesize-verify.test.ts b/test/cycle-synthesize-verify.test.tsindex db0f3661ca..47e9b83388 100644--- a/test/cycle-synthesize-verify.test.ts+++ b/test/cycle-synthesize-verify.test.ts@@ -134,6 +134,35 @@ describe('groundQuote — the repair ladder', () => {});});+describe('groundQuote — strict closing punctuation inside the marks (#6952)', () => {+ const content = '**alice-example** (10:02): The deal desk is always open at the right price for us.\n\n**bob-example** (10:03): Fine, send terms.\n';+ const strict = groundSource('conversations/2026-10-01-acme-example', content);+ const start = content.indexOf('always open at the right price');+ const span: Array<[number, number]> = [[start, start + 'always open at the right price'.length]];++ test.each(['.', ',', '?', '!', '…'])('a verbatim quote ending in %s grounds exact on its core', (mark) => {+ expect(groundQuote(`always open at the right price${mark}`, strict)).toEqual({ status: 'exact', spans: span });+ });++ test('a normalized core substitutes the verbatim source slice', () => {+ expect(groundQuote('ALWAYS open at the right price.', strict)).toEqual({+ status: 'normalized', replacement: 'always open at the right price', spans: span,+ });+ });++ test('verifyBody keeps the quote and quarantines nothing', () => {+ const body = '## Reflection\n\nalice-example said the desk is "always open at the right price." That framing recurs.\n';+ const r = verifyBody(body, [strict]);+ expect(r.quarantined).toEqual([]);+ expect(r.body).toBe(body);+ });++ test('strict grounding still refuses absent words and keeps no bracket folding', () => {+ expect(groundQuote('always open at the wrong price.', strict).status).toBe('none');+ expect(groundQuote('[T]he deal desk is always open.', strict).status).toBe('none');+ });+});+describe('verifyBody', () => {// The principle sentence carries an INTERIOR em-dash + curly apostrophe —// a page quote written with a hyphen + straight apostrophe is normalized-