Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.59.18.0 fix(dream): quarantine unverified synthesized claims, verify edits to existing pages, real paired stats in eval compare (#5685)
Garry Tan045a613814b1
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex d95ba77bd9..d387ace420 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.17.0",+ "version": "0.59.18.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 27ff33e827..759d93b3d8 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.17.0",+ "version": "0.59.18.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 1d8df89cb8..a5851c2e65 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.59.17.0 -->+<!-- gbrain-runbook-stamp: 0.59.18.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c0f5043efd..fe0f9b2597 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,49 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.59.18.0] - 2026-09-29++**Dream no longer keeps made-up quotes, wrong-speaker quotes or invented numbers as memory, and `gbrain eval compare` computes the statistics it claims.**++When the nightly dream cycle turns a conversation into brain pages, a mechanical check compares each quote with the transcript. Until now, a quote it could not find lost its quotation marks and stayed on the page as ordinary text, so an invented sentence became searchable memory. Pages that already existed (person pages, earlier reflections) were not checked at all, a close-match repair could splice in the next speaker's words, and numbers the transcript never mentioned were only counted.++Now any sentence that fails the check leaves the page body and is kept word for word in the page's `unverified_claims` frontmatter, which `get_page` shows but search, recall and think do not read. A sentence fails when its quote appears in no source transcript, only matches across two speakers, is attributed to someone other than the person who said it, or when it states a number or date the transcript does not contain. Pages that already existed are checked on the sentences the run added, against the transcripts that wrote them. Timeline entries, facts and links derived from a failed sentence are removed with it. Each kept quote records its source file, character span and speaker in `grounding.quotes`.++Measured on a fixed three-cycle experiment (3 transcripts, a scripted model that writes 13 supported claims and 17 invented ones, including edits into existing pages), counting what search and recall can read after the third cycle:++| After 3 dream cycles | v0.59.13.0 | v0.59.18.0 |+| --- | --- | --- |+| Invented claims in active memory (of 17) | 17 | 2 |+| of which fabricated quotes (of 6) | 6 | 0 |+| of which speaker-swapped quotes (of 3) | 3 | 0 |+| of which invented numbers (of 6) | 6 | 0 |+| of which unquoted inventions with no number (of 2) | 2 | 2 |+| Supported claims kept (of 13) | 13 | 13 |++The fixture was written alongside the check, so treat it as a regression pin, not a hallucination rate for a real model. Plain-prose inventions with no quote or number are not mechanically checkable and still get through.++`gbrain eval compare` printed "paired bootstrap with Bonferroni correction" but computed only side-by-side averages. It now computes paired statistics from per-question rows: for runs whose ledger record points at their per-question output, it joins the rows by question and reports a 95% bootstrap interval, a p-value and a Holm-corrected p-value for each metric. Runs without per-question rows are labeled aggregate-only, with no significance claim.++### To take advantage of v0.59.18.0++Run `gbrain upgrade`. There is no migration. The check applies to the next dream cycle; existing pages are not rescanned. To review what was held back, run `gbrain get <slug>` and read `unverified_claims`. To compare two LongMemEval runs with real statistics, record both with `gbrain eval longmemeval --record --output <file>` and run `gbrain eval compare --baseline <run_id> --candidate <run_id>`.++### Itemized changes++- `synthesize-verify.ts` checks sentence-sized claim units (sentences, list items, table rows) instead of bare quote spans, and quarantines a failing unit whole instead of removing its quotation marks.+- Close-match quote repairs stay inside one speaker's turn and are trimmed to the matched words (write-path audit C-6); any match that touches a speaker label is refused.+- Attribution check: when a sentence names a transcript speaker, the quote must come from that speaker's turn.+- Numbers and dates are compared by value, so `$250K`, `$250,000` and `250 thousand` agree, as do `2026-03-14` and `March 14th`; the transcript file name counts as a source for dates.+- Verification covers every page a child wrote. A page created during the run is checked whole; an older page is checked on the sentences missing from its revision before the run (`page_versions`), against every transcript that wrote it. Epochs come from the child jobs' creation time, so resumed children still count their own pages.+- The unmanaged write-back re-projects timeline entries, facts, takes and links from the verified body in the same transaction. The managed path already re-projected timeline entries, facts and takes through its page publication.+- New telemetry in `details.synthesis.quote_verify`: `quarantined_claims`, `pages_with_quarantine`, `preexisting_diffed`, `skipped_unchanged` and one counter per failure reason. `stripped`, `skipped_preexisting` and `numeric_claim_warns` are gone.+- `gbrain eval compare`: `--baseline`, `--candidate`, `--draws`, `--seed`; JSON gains `paired` and `paired_unavailable`; Markdown gains a "Paired comparisons" table with a significant / not significant verdict. A per-question file path in the ledger must resolve inside the repository root; paths that escape it are refused and never read. The statistics module (`src/core/eval/paired-bootstrap.ts`) is a port of the gbrain-evals situation-recall comparator with a two-sided p-value.++### For contributors++- New tests: `test/cycle-repeated-consolidation.test.ts` (fails on v0.59.13.0, passes here), `test/eval-paired-bootstrap.test.ts`; extended `test/cycle-synthesize-verify.test.ts`, `test/eval-compare.test.ts`, `test/cycle-write-path-mini-eval.test.ts`.+- `bun run scripts/repeated-consolidation-experiment.ts [--per-cycle]` prints the experiment as JSON ($0, no network). Record in `docs/eval/FIX_WAVE_BASELINES.md`.+## [0.59.17.0] - 2026-09-28**Forgetting one person's fact no longer erases it for everyone, and several maintenance jobs stop quietly losing or overwriting your notes.**diff --git a/VERSION b/VERSIONindex 284dbf1b09..d06303e067 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.59.17.0+0.59.18.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex ec2c4a4bd0..0deee6fad7 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -1304,8 +1304,9 @@ Unit tests and what they cover:- `test/cycle-lock-steal.serial.test.ts` — runCycle steal-abort arc end-to-end: a mid-run steal produces a structured partial report (`reason: 'lock_stolen'`), runs no further phases, and never touches the successor's lock row; a steal-free cycle completes and releases normally.- `test/cycle-any-abort-signal.test.ts` — `anyAbortSignal` combining: pre-aborted inputs, late aborts propagating their reason, duck-typed signal stubs (no `addEventListener`) observed via poll, and `dispose()` detaching the caller-signal listener + clearing the poll timer (the daemon leak class).- `test/cycle-triage-rescue.test.ts` — the dream triage gate: `passesTriageGate` band arithmetic (floor inclusive, at/above threshold never "rescued"), content-type allowlisting, segment verification through `normForGrounding` (case/curly-quote/dash folding matches, fabricated segments never do), the ≥40-char + dedupe-by-normalized-quote rules, and fail-closed behavior on every malformed verdict shape (null score, missing/short/non-string segments) with `minSegments: 0` as the kill switch.-- `test/cycle-synthesize-verify.test.ts` — the mechanical quote verify/repair pass: span extraction with code fences / inline code / wikilinks / link targets masked, odd-mark paragraphs counted `unbalanced`, the repair ladder (exact keep → normalized replace with the verbatim slice → near-match replace → strip the marks keeping the text, never fabricate), the offset-map invariant that every replacement is a real transcript slice, ambiguity fall-through, `skipped_preexisting` scoping by content-hash slug suffix, warn-only numeric/date claim counting, write-back through `importFromContent` only when a span changed, and per-page fail-open.+- `test/cycle-synthesize-verify.test.ts` — the mechanical claim verification pass: span extraction with code fences / inline code / wikilinks / link targets masked, odd-mark paragraphs counted `unbalanced`, the quote ladder (exact keep → normalized replace with the verbatim slice → near-match replace trimmed to the matched tokens inside one speaker turn), refusal of any match that crosses a speaker label, wrong-speaker attribution, canonical number and date grounding, claim units (a failing sentence, list item or table row leaves the body whole and lands in `unverified_claims`), source-span + speaker provenance in `grounding.quotes`, diff-scoped verification of pre-existing pages against their pre-run `page_versions` revision, and per-page fail-open.- `test/cycle-write-path-mini-eval.test.ts` — the hermetic **$0** write-path mini-eval. A frozen 3-transcript mini-corpus (high / buried / routine bands, placeholder names, deliberately disjoint from the paid Cat 35 corpus so there is no tuning coupling) drives the REAL `runPhaseSynthesize` on PGLite: real triage parse + gate incl. the rescue, real fan-out + oneshot drain, real quote verify/repair, real provenance stamp + reverse-write + telemetry. The ONLY stub is the gateway chat transport (`__setChatTransportForTests`), serving a scripted judge and a scripted child. Scope honesty matters here: a scripted child CANNOT measure whether a prompt change improved model output — that stays the paid benchmark's job (receipts in `docs/eval/FIX_WAVE_BASELINES.md`). This is the no-API-key regression pin for the MECHANICAL write path, and its salient-unit presence score is the canary that catches emission, chunk-slug-rewrite, and repair-over-deletion regressions in the normal unit lane.+- `test/cycle-repeated-consolidation.test.ts` + `test/helpers/repeated-consolidation.ts` — hermetic three-cycle consolidation pin: real `runCycle` (`synthesize` → `extract` → `extract_facts`) on PGLite with a scripted agentic child (gateway tool loop) that writes supported claims, fabricated quotes, speaker swaps and invented numbers into new and existing pages. Pins zero checkable invented claims in active memory (page text, timeline rows, facts), every supported claim kept, and the two unquoted inventions the mechanical check cannot see. `scripts/repeated-consolidation-experiment.ts` prints the same measurements as JSON for a before/after comparison.- `test/cycle-synthesize-triage.test.ts` / `test/cycle-synthesize-triage-calibration.test.ts` — triage gate wiring inside `runTriagePass` (reports carry `rescued`/`verified_segments`, `details.triage` rescue + token counters, dry-run parity), plus the 25-fixture calibration corpus (10 high / 10 low / 5 buried, all synthetic placeholders) enforcing band-consistent parsing, a ≥80% band-accuracy rubric-drift pin, and that ≥4 of the 5 buried fixtures reach the gate. `TRIAGE_VERSION` participates in cache validity, so a rubric bump re-judges rather than serving stale verdicts.- `test/dream-retriage.test.ts` — `gbrain dream retriage` reads THE shared gate: reconcile-queue never cancels a rescued job, `--audit-rejects` excludes rescued files from the reject sample, alongside the spend-gate / dry-run / liveness arcs.- `test/facts-extract-idea-kind.test.ts` — the `idea` extractor kind: taxonomy coercion (known kinds survive verbatim, `idea` stays `idea`, unknown kinds coerce to `fact`), prompt shape (the two precomputed system-prompt variants differ in EXACTLY one clause — the low-tier line — both carry the idea definition and the widened enum, and repeat calls return the identical string so prompt caching still hits), and admission wiring (no admission or an admission allowing `low` → label-honestly; a high-only admission → skip-low).diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 567e9ad3f3..383cf4a29e 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -7,6 +7,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/enrich.ts` + `src/core/enrich/thin.ts` + `src/core/cycle/enrich-thin.ts` — `gbrain enrich --thin`: batch-develops stub (thin) pages via **brain-internal grounded synthesis**. gbrain's model tooling sees only brain-internal context (search / get_page / facts / backlinks), not the web, so enrich consolidates what the brain ALREADY knows about an entity (scattered across meetings, other pages, deals, facts) into one cited page via ONE `gateway.chat` call per page; web research stays the agent-driven `enrich` SKILL's job. `runEnrichCore(engine, opts, signal)` refuses managed mutation before provider work until its resume cursor can retain prepared writes (dry-run remains available); legacy writes expose pending/failed request IDs. It is strict per-source (multi-source iteration is the caller's job) and drives `enrichOne` per candidate: `withRefreshingLock('enrich:<src>:<slug>')` → coherent `readPageSnapshot` (content, tags, revision) → deterministic retrieve (hybridSearch + getBacklinks + facts + raw_data, source-scoped, sanitized via `INJECTION_PATTERNS`) → `assessGrounding` gate (skip < `MIN_CONTEXT_CHARS`, no LLM) → `buildEnrichPrompt` (grounded dossier, `[Source: slug]` citations, SKIP sentinel) → synth → `put_page` handler (`remote:false`, observed revision and caller-allocated request UUID, atomic projections and receipt) stamping `enriched_at` + `enriched_by:'cli:enrich'`. Candidate selection is the SQL-native `engine.listEnrichCandidates(opts)` (`src/core/engine.ts` interface + `EnrichCandidate`/`EnrichCandidatesOpts`/`ENRICH_ORDER_SQL` in `src/core/types.ts` + pg/pglite impls): thin-filter + per-page source-correct inbound count (`to_page_id = p.id`, `mentions` excluded) + `enriched_at` recency guard + whitelisted ORDER BY + LIMIT, lightweight projection (NO bodies). Resume via `src/core/op-checkpoint.ts` (local `enrichFingerprint`); budget via `BudgetTracker` + `withBudgetTracker` (best-effort under `--workers > 1` — `runSlidingPool` aborts new claims on `BUDGET_EXHAUSTED` but does NOT cancel in-flight `gateway.chat`; pin `--workers 1` for a hard ceiling). `sanitizeContext` (thin.ts) neutralizes the `<context>…</context>` data-envelope delimiters (injection escape, mirrors the `</trajectory>` convention); the `--background` multi-source fan-out idempotency key carries the run fingerprint via exported `backgroundIdempotencyKey(sid, args)` (a bare `enrich:${sid}` would return stale completed jobs); `runEnrichCore` flags `budget_exhausted` post-hoc when `tracker.totalSpent > tracker.cap` even when the gateway swallowed the final-call throw (via read-only `BudgetTracker.cap` getter); `body()` flushes the checkpoint on `BudgetExhausted` before it propagates so resume doesn't re-charge. The opt-in `enrich_thin` cycle phase (default OFF via `cycle.enrich_thin.enabled`) trickles `max_pages_per_tick` (default 3) per source with per-source cost cap enforced as `min(per_source_cap, brain_wide_remaining)` + brain-wide total + walltime caps. Wired into `cycle.ts` (`CyclePhase`/`ALL_PHASES` between `conversation_facts_backfill` and `skillopt`/`embed`; `PHASE_SCOPE='source'`; `NEEDS_LOCK`; dispatch), `cli.ts` (`CLI_ONLY` + `CLI_ONLY_SELF_HELP` + `THIN_CLIENT_REFUSED_COMMANDS` + dispatch), `jobs.ts` (Minion `enrich` handler, strict per-source, NOT in `PROTECTED_JOB_NAMES`). DI seam `opts.synthesizeFn` keeps tests hermetic (no API key, no mock.module). Pinned by `test/enrich/thin.test.ts`, `test/enrich/idempotency.test.ts`, `test/enrich-cycle-phase.test.ts`, `test/e2e/enrich-pglite.test.ts` (grew-cited, skip, ordering, multi-source, recency, resume, budget abort + checkpoint flush, final-call overage, lock-skip, provenance), `test/e2e/engine-parity.test.ts` (`listEnrichCandidates` pg↔pglite parity).+- `src/commands/eval-compare.ts` — `gbrain eval compare [--suite S] [--modes ...] [--runs ...] [--baseline RUN_ID --candidate RUN_ID] [--draws N] [--seed N] [--md|--json] [--input PATH]`. Reads the run ledger `<repo>/.gbrain-evals/eval-results.jsonl`, keeps the newest record per (suite, mode) and renders the mode table plus any aggregate `metrics`. Paired statistics come only from per-query rows: a record whose `params.output` names its per-question JSONL (`gbrain eval longmemeval --record --output`) is joined with its pair on `question_id`, and each per-query metric both rows carry (`recall_all@k`, `recall_any@k`, `qa_accuracy` from `judge_correct`) gets a paired cluster bootstrap 95% CI, a two-sided sign-flip p-value and a Holm p-value across the report's comparisons (`src/core/eval/paired-bootstrap.ts`). Pairs are every mode pair in a suite, or exactly `--baseline`/`--candidate`. Significant means Holm p ≤ 0.05 and a CI that excludes 0. A `params.output` path must resolve inside the repository root after following symlinks (`pathWithinRoot`); a `..`, absolute or symlinked path outside it is refused and never read. Runs without rows are listed in `paired_unavailable`, and a report with no comparisons says it is aggregate-only; `_meta.methodology` describes only what was computed. Pinned by `test/eval-compare.test.ts`.+- `src/commands/eval-cross-modal.ts` — multi-model quality gate. Three different-provider frontier models score the OUTPUT against the TASK on a 5-dim list. Verdict `pass` (exit 0) / `fail` (exit 1) / `inconclusive` (exit 2; <2/3 model successes). Reuses `src/core/ai/gateway.ts:chat()` so config/auth/aliasing comes from the gateway recipe registry — no parallel provider stack. Self-configures the gateway (`configureGateway(loadConfig() + process.env)`) since the cli.ts dispatch bypasses `connectEngine()`. Default cycles 3 in TTY, 1 in non-TTY (partial cost guardrail) via the shared `resolveCycleDefault(explicit, isTty)` in `src/core/eval/cycle-default.ts`; the cost-estimate banner appends `cycleDefaultSuffix(...)` (`for 1 cycle(s) (non-interactive default; --cycles N for more)`) when the value is the silent non-TTY fallback, so the 1-vs-3 difference isn't hidden. Receipts land at `gbrainPath('eval-receipts')/<slug>-<sha8-of-output>.json`. `--batch <jsonl> [--limit N] [--concurrent N] [--max-usd FLOAT] [--yes]` fans out cross-modal scoring across a LongMemEval-shape JSONL; mutually exclusive with `--task` (fail-fast usage error if both set); filters `kind: "by_type_summary"` rows; pre-flight cost estimate refuses if `> --max-usd` without `--yes` (default cap 5.00 USD). Semaphore-bounded fan-out via inline `runWithLimit<T>(items, limit, fn)` (exported for unit tests): max N questions in-flight × 3 model slots = ceiling of 3N parallel API calls (default `--concurrent 3` → 9). Per-question receipts land in a per-batch tempdir and are deleted at end of run; the summary receipt inlines per-question verdicts as JSON, not file paths. Exit precedence (batch-level policy, NOT inherited from aggregate.ts): ERROR > FAIL > INCONCLUSIVE > PASS. DI seam: `runEvalCrossModal(args, opts?: {runEval?: typeof runEval})` mirrors `runEvalLongMemEval(args, {client?})`; tests pass `opts.runEval` to bypass real LLM calls AND the gateway availability check. Pinned by `test/eval-cross-modal-batch.test.ts`.- `src/commands/eval-export.ts` — streams `eval_candidates` rows as NDJSON to stdout with `schema_version: 1` prefix on every line. EPIPE-safe, progress heartbeats on stderr, stable id-desc tiebreaker so `--since` windows never dupe/miss rows.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 0b41d0b84e..95c2a07ec6 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. Reuses the pure quote-repair helpers in `synthesize-verify.ts`; the unmanaged path retains its existing fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper.+- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the child write epochs the phase passes as `sinceByTranscript`); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper.- `src/core/cycle/anomaly.ts` — Pure stats helpers for `find_anomalies`. `meanStddev` returns sample stddev (n-1 denominator) and (0,0) for empty input. `computeAnomaliesFromBuckets(baseline, today, sigma, limit)` takes densified daily-count buckets + today's counts per cohort, returns `AnomalyResult[]`. Zero-stddev fallback: cohort fires when `count > mean + 1`, with `sigma_observed = count - mean` as a finite sort proxy (no NaN). Brand-new cohorts (no baseline) have `mean=0, stddev=0` so the fallback fires at count >= 2. Sorted by `sigma_observed` desc, top `limit` (default 20). `page_slugs` capped at 50 per cohort.@@ -37,9 +37,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/recompute-emotional-weight.ts` — Cycle phase orchestrator. One read plus bounded writes: `engine.batchLoadEmotionalInputs(slugs?)` → `computeEmotionalWeight` (per-row pure function) → `engine.setEmotionalWeightBatch(slice)` in slices of 1000 rows. Between slices it checks `opts.signal` (throws → `fail`), awaits `opts.yieldDuringPhase` (cycle-lock refresh / steal detection), fires `opts.onProgress`, and yields a macrotask (`setTimeout(0)`) so PGLite's synchronous statement execution never wedges the main thread for a whole-brain pass; `runCycle` wires these exactly like consolidate (`racedTimePhase` + `buildYieldDuringPhase` + `cycleSignal` + `progress.tick`). Both engines' `setEmotionalWeightBatch` rewrite only rows whose weight changes (`IS DISTINCT FROM` in the WHERE — no trigger fan-out on same-value rows) and return rows CHANGED; `details.pages_recomputed` = pages evaluated (feeds the cycle totals), `details.pages_updated` = rows changed. Reads config `emotional_weight.high_tags` (JSON array, falls back to default seed list on parse error) and `emotional_weight.user_holder`. Empty `affectedSlugs` short-circuits with zero-work success. dry-run reports the would-write count without touching the DB. Engine throw bubbles into `status: 'fail'` with code `RECOMPUTE_EMOTIONAL_WEIGHT_FAIL` so the cycle continues.-- `src/core/cycle/synthesize-verify.ts` — Mechanical quote verify/repair on newly-created dream pages (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/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). `verifyAndRepairDreamPages(engine, writtenRefs, transcriptsByPath)` scopes to pages whose slug carries the transcript's content-hash suffix (page↔transcript binding; modified pre-existing people/pattern pages are skipped + counted `skipped_preexisting` — they may quote other sources), extracts paired-quote spans from the page BODY (code fences/inline code/wikilinks/link targets masked; paragraph-paired; odd-mark paragraphs skipped + counted `unbalanced`; min span 15 chars, ≤200 spans/page), and runs the repair ladder per span: exact substring → keep; normalized match → replace with the verbatim original slice; near match (word-trigram anchors, ≥0.8 token overlap, ambiguity within 0.05 falls through) → replace; else STRIP the quote marks keeping the text — NEVER fabricates, never deletes content. Warn-only counter: numeric/date claims ($amounts, percents, ISO/month dates, 4+ digit numbers, deduped, fences skipped) absent from the normalized transcript → `numeric_claim_warns`. Write-back ONLY when a span changed, through the canonical `importFromContent` pipeline (page+tags+chunks+links in one transaction, content_hash recomputed, `noEmbed` — the phase-end sweep backfills; provenance nulls preserve the first-write record); bare `engine.putPage` is insufficient (pages row only — the embed sweep would embed stale chunk_text). Fail-open per page (read-back miss / write throw → count + 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 harness `test/cycle-write-path-mini-eval.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). `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors 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. 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`, `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 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`) and automatic links (`prepareAutomaticLinks`) from the verified body in the same transaction, so no derived row outlives its quarantined claim. 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`).-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/e2e/dream-synthesize-chunking.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 OPEN with a stderr warn). `--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. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `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 child-written page BEFORE reverse-rendering, 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 quote verify/repair pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on newly-created pages; 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.+- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/e2e/dream-synthesize-chunking.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 OPEN with a stderr warn). `--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. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `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 child-written page BEFORE reverse-rendering, 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.- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`.diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.mdindex 3940c5ca8e..02ba87497f 100644--- a/docs/architecture/key-files/evaluation.md+++ b/docs/architecture/key-files/evaluation.md@@ -25,6 +25,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/eval/cycle-default.ts` — single source of truth for the eval cycle-count default. Exports `DEFAULT_CYCLES_TTY = 3`, `DEFAULT_CYCLES_NONTTY = 1`, `resolveCycleDefault(explicit, isTty): {cycles, usedNonTtyDefault}`, and `cycleDefaultSuffix(r)` (returns ` (non-interactive default; --cycles N for more)` only when the non-TTY default was applied, else `''`). Consumed by `eval-cross-modal.ts`, `eval-takes-quality.ts` (run + regress), and `takes-quality-eval/runner.ts` (core uses only the constant — library stays TTY-agnostic; the CLI owns the TTY=3 upgrade + banner annotation). `eval-suspected-contradictions.ts` applies the same transparency to its `$5`/`$1` budget default via a `budgetUsdExplicit` flag (the budget is overwritten in-place so explicitness can't be inferred post-hoc). Not shared with `resolveWorkersWithClamp` (different domain, no engine, no dedup). Pinned by `test/eval/cycle-default.test.ts`, `test/eval-suspected-contradictions-budget-default.test.ts`.+- `src/core/eval/paired-bootstrap.ts` — paired, clustered comparison statistics for per-query eval rows, ported from the gbrain-evals situation-recall comparator (`eval/runner/situation-recall-regression.ts`). `pairedClusterStatistics(pairs, { seed, draws })` returns n, clusters, means, delta, wins/losses/ties, a percentile 95% CI from whole-cluster bootstrap resamples, and a two-sided sign-flip p-value (exact enumeration at ≤16 clusters, else Monte Carlo with the (k+1)/(n+1) correction); no discordant pairs → CI [0, 0], p = 1; fewer than two clusters → unbounded CI, p = 1. `holmAdjusted` is the Holm step-down. Deterministic via the same seeded mulberry32 generator. Requires ≥1000 draws and finite values. Consumed by `src/commands/eval-compare.ts`. Pinned by `test/eval-paired-bootstrap.test.ts`.+- `src/core/eval/ranked-docs.ts` — dependency-free page-level ranking primitive shared by the retrieval eval harness, NamedThingBench, and the qrels correctness gate. `dedupeRankedKeys()` preserves the first/best occurrence of each `${source_id}::${slug}` or slug key before any cutoff, so repeated chunks neither inflate relevance gain nor consume document ranks. Precision retains its fixed-`k` denominator; Recall and nDCG are structurally bounded to `[0,1]`. Pinned across `test/eval.test.ts`, `test/retrieval-quality-harness.test.ts`, `test/bench/qrels-file.test.ts`, and `test/bench/correctness-gate.test.ts`.- `src/core/takes-quality-eval/pricing.ts` — fail-closed budget pricing for `eval takes-quality run --budget-usd N`. `MODEL_PRICING` is a curated `provider:model` allowlist (default panel + likely overrides) whose VALUES are derived from `model-pricing.ts` via `canonicalLookup`; an allowlisted id missing from canonical throws at module load. Schema is `{input_per_1m, output_per_1m}`. A model NOT on the allowlist aborts the run with an actionable error rather than guessing (distinct from `cross-modal-eval/runner.ts`, which silently estimates zero on unknown models — both now source numbers from canonical).diff --git a/docs/eval/FIX_WAVE_BASELINES.md b/docs/eval/FIX_WAVE_BASELINES.mdindex bf1b1bf364..bb06962fb4 100644--- a/docs/eval/FIX_WAVE_BASELINES.md+++ b/docs/eval/FIX_WAVE_BASELINES.md@@ -23,6 +23,51 @@ touch `~/.gbrain` per the eval discipline — results land in`<repo>/.gbrain-evals/eval-results.jsonl`). Record the gate verdict + headlinemetrics here per run.+## Grounding gate: repeated consolidation (2026-09-29, v0.59.18.0)++Hermetic experiment for gbrain 10x plan amendment 7. Three real dream cycles+(`runCycle` with `synthesize`, `extract`, `extract_facts`) on a fixed PGLite+brain; each cycle adds one fixed transcript between two named speakers. The+only stub is the gateway chat transport: a scripted triage verdict and a+scripted synthesis child in agentic mode through the gateway tool loop (the+one production mode whose children can write into existing pages; the default+oneshot mode can only create new hash-suffixed pages). The child writes a new+reflection page per cycle, rewrites the cycle-1 page in cycles 2 and 3, and+appends to a human-authored person page in cycle 2. Active memory = live page+`compiled_truth` + `timeline`, `timeline_entries`, and unexpired `facts`, with+quotation marks ignored so an unquoted leftover still counts. $0, no network.++```bash+bun run scripts/repeated-consolidation-experiment.ts --per-cycle+# master: copy test/helpers/repeated-consolidation.ts and the script into an+# origin/master worktree (b80cad61e, v0.59.13.0) and run the same command.+```++| After cycle 3 | master `b80cad61e` | this branch |+|---|---|---|+| Invented claims active (of 17) | 17 | 2 |+| Fabricated quotes active (of 6) | 6 | 0 |+| Speaker-swapped quotes active (of 3) | 3 | 0 |+| Invented numbers active (of 6) | 6 | 0 |+| Unquoted inventions active (of 2) | 2 | 2 |+| Source-supported claims kept (of 13) | 13 | 13 |+| Human-authored person-page line intact | yes | yes |++- Per cycle, invented claims active on master: 5 after cycle 1, 11 after+ cycle 2, 17 after cycle 3 (they accumulate). Branch: 1, 1, 2 (the two+ unquoted inventions, one per cycle that wrote one).+- The 13 supported claims include four reformatted values (`$40,000` for+ `$40K`, `$1.2 million` for `$1.2M`, `September 15th`, `October 20th`), so+ the number check was exercised for false positives; none were lost.+- A first branch run found a second leak: the verifier's write-back removed a+ sentence from the page but left the timeline row the child's write had+ projected from it. The write-back now re-projects timeline, facts, takes+ and links in the same transaction.+- Limits: the fixture was written alongside the checker, so this is a+ regression pin, not a hallucination rate. Plain-prose inventions with no+ quote or number are not mechanically checkable. The paid hallucination+ benchmark is a separate, later measurement.+## Read-path wave (2026-09-28, v0.59.13.0)Page-grain fusion, identity tiers that keep the reranker order, soft autodiff --git a/docs/eval/METRIC_GLOSSARY.md b/docs/eval/METRIC_GLOSSARY.mdindex 3f34eac059..c4440d9a26 100644--- a/docs/eval/METRIC_GLOSSARY.md+++ b/docs/eval/METRIC_GLOSSARY.md@@ -92,11 +92,11 @@ Every metric `gbrain eval *` and `gbrain search stats` reports has a plain-Engli## Statistical-Significance Metrics-### p-value (paired bootstrap)+### p-value (paired sign-flip randomization test)**Key:** `p_value`-**Plain English:** How likely the observed difference between two modes is just noise. Lower = stronger evidence the difference is real. We compute paired bootstrap with 10,000 resamples and Bonferroni correction across the 12 comparisons (3 modes × 4 metrics).+**Plain English:** How likely the observed difference between two runs is just noise. Lower = stronger evidence the difference is real. Computed from per-question rows by randomly flipping which run each question's result belongs to, then Holm-corrected across every comparison in the report.**Range:** 0..1, lower = stronger signal. Below 0.05 is the common "statistically significant" threshold; below 0.01 is strong evidence.@@ -104,7 +104,7 @@ Every metric `gbrain eval *` and `gbrain search stats` reports has a plain-Engli**Key:** `confidence_interval`-**Plain English:** The range we're 95% sure the true value falls inside, given the sample we measured. Narrower CI = more reliable estimate. Computed via bootstrap resampling.+**Plain English:** The range we're 95% sure the true value falls inside, given the sample we measured. Narrower CI = more reliable estimate. Computed by resampling questions with replacement (paired bootstrap).**Range:** Two-tuple [low, high]. If 0 is inside the CI for a Δ, the difference isn't statistically significant.diff --git a/docs/eval/SEARCH_MODE_METHODOLOGY.md b/docs/eval/SEARCH_MODE_METHODOLOGY.mdindex 41041263e9..d18557b787 100644--- a/docs/eval/SEARCH_MODE_METHODOLOGY.md+++ b/docs/eval/SEARCH_MODE_METHODOLOGY.md@@ -68,7 +68,7 @@ Honest list. We name what would let a critic dismiss the numbers.- **The dev slice is inside the published 470.** Knob choices made on the 40 dev questions leak into the full-470 headline by construction; the 430-question decision set is the number a critic should read, and both are published side by side. Nothing is tuned on the frozen corpus beyond the pre-registered single mechanism per gap.- **Expansion variants are non-deterministic.** Haiku multi-query variants differ run to run, so budget cells are compared only on RECORDED variants (`--expansion-replay`), which makes the budget the sole difference between cells but means the replayed cells share one draw of the variant lottery.- **Reranker receipts depend on a hosted model.** `voyage:rerank-2.5` rows are reproducible only while that snapshot is served; the harness records the reranker model per run and fails a "reranker on" run that silently fell open.-- **Paired bootstrap assumes question-level independence.** Multi-hop questions within the same conversation thread aren't independent; the bootstrap CI is slightly tighter than reality.+- **Clusters are questions.** Rows are resampled by `question_id`. Questions that share a conversation thread are not independent, so the interval can be slightly tighter than reality.- **Single brain instance per benchmark.** The benchmark spins up an in-memory PGLite per question. This does not reproduce a long-running production brain's state; current semantic result-cache hit rates are zero because result reuse is disabled.## 6. Per-question raw outputs@@ -117,13 +117,34 @@ Additions to the watch-list require a CHANGELOG line.## Statistical-significance discipline-When `gbrain eval compare --md` reports a Δ between two modes, it computes:--- **Paired bootstrap** with 10,000 resamples per metric. Each resample draws _question-level_ pairs (same question, mode A vs mode B), so question-level variance is differenced out.-- **Bonferroni correction** across the 12 comparisons (3 modes × 4 metrics). The reported p-value is the comparison's raw p-value × 12 (clamped at 1.0).-- **95% confidence intervals** computed from the bootstrap distribution.--If the CI for a Δ includes 0 OR the Bonferroni-adjusted p-value exceeds 0.05, the difference is **not** statistically significant. The MD report says "not significant" verbatim.+`gbrain eval compare` computes statistics only from per-query rows. A run+contributes rows when its ledger record names its per-question output in+`params.output` (`gbrain eval longmemeval --record --output <file>` writes+both). The per-question file must sit inside the repository root; a path+that escapes it (`..`, an outside absolute path, or a symlink) is refused and+listed in `paired_unavailable`. For each pair of runs (every mode pair in a suite, or exactly+`--baseline RUN_ID --candidate RUN_ID`), rows are joined on `question_id` and+each per-query metric both rows carry (`recall_all@k`, `recall_any@k`,+`qa_accuracy` from `judge_correct`) is compared with:++- **Paired cluster bootstrap**, 10,000 resamples by default (`--draws`,+ `--seed`, default seed 42). Clusters are questions, so question-level+ variance is differenced out. The 95% confidence interval is the percentile+ interval of the resampled mean difference.+- **Two-sided sign-flip randomization p-value** over clusters: exact+ enumeration at 16 or fewer clusters, otherwise Monte Carlo flips with the+ (k+1)/(n+1) correction.+- **Holm correction** across every comparison in the report.++A difference is reported as significant only when the Holm p-value is at+most 0.05 and the 95% CI excludes 0; otherwise the Markdown report says+"not significant" verbatim. The statistics code+(`src/core/eval/paired-bootstrap.ts`) is a port of the gbrain-evals+situation-recall comparator, with a two-sided p-value.++When no per-query rows are available, the report is labeled aggregate-only+and no interval or p-value is computed. Aggregate `metrics` columns are+shown as recorded and carry no significance claim.## Glossarydiff --git a/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.mdindex 8e4c617134..2baf3ab395 100644--- a/docs/guides/cron-schedule.md+++ b/docs/guides/cron-schedule.md@@ -150,9 +150,13 @@ per-transcript synthesis subagents. The dials:gate, so a reconcile sweep never cancels rescued jobs. Telemetry:`details.triage.rescue_checked` / `rescue_fired`.- `dream.synthesize.quote_verify` (default on) — the mechanical post-write- quote verify/repair pass on newly-created dream pages (paraphrased "quotes"- are repaired to verbatim transcript slices or unquoted; never invented).- The off switch is the incident escape hatch; telemetry lands in+ claim check on every page a synthesis child wrote. Paraphrased quotes are+ repaired to verbatim transcript slices; a sentence whose quote grounds+ nowhere, spans two speakers, is attributed to the wrong speaker, or states a+ number or date the transcript lacks is moved out of the page body into+ frontmatter `unverified_claims`, so search, recall and think never see it.+ Pages that already existed are checked only on the sentences this run+ added. The off switch is the incident escape hatch; telemetry lands in`details.synthesis.quote_verify`.- `dream.synthesize.max_turns` (default 16) — synthesis turn budget foragentic children and oneshot fallbacks (the default oneshot path — see@@ -238,9 +242,11 @@ Three more fields answer "what did that cost and did it land":- `children_zero_pages` — children that completed but wrote no page. A numberthat climbs here means the model is producing valid-but-empty output, whicha green phase status alone would hide.-- `quote_verify` — what the post-write quote pass touched: spans checked,- repaired, and stripped, pages skipped as pre-existing, unbalanced paragraphs,- and the warn-only ungrounded numeric/date claim count.+- `quote_verify` — what the post-write claim check touched: quotes checked+ and repaired, sentences quarantined (with counts per reason:+ `quote_not_in_source`, `quote_crosses_speakers`, `speaker_mismatch`,+ `number_not_in_source`), pre-existing pages checked by diff, and unbalanced+ paragraphs.Per-call spend also lands in the `chat_usage_log` ledger with a phase tag:the orchestrator's own calls under `phase:synthesize`, each drained childdiff --git a/llms-full.txt b/llms-full.txtindex 46bac6b30c..77aa5f7c7a 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -4993,9 +4993,13 @@ per-transcript synthesis subagents. The dials:gate, so a reconcile sweep never cancels rescued jobs. Telemetry:`details.triage.rescue_checked` / `rescue_fired`.- `dream.synthesize.quote_verify` (default on) — the mechanical post-write- quote verify/repair pass on newly-created dream pages (paraphrased "quotes"- are repaired to verbatim transcript slices or unquoted; never invented).- The off switch is the incident escape hatch; telemetry lands in+ claim check on every page a synthesis child wrote. Paraphrased quotes are+ repaired to verbatim transcript slices; a sentence whose quote grounds+ nowhere, spans two speakers, is attributed to the wrong speaker, or states a+ number or date the transcript lacks is moved out of the page body into+ frontmatter `unverified_claims`, so search, recall and think never see it.+ Pages that already existed are checked only on the sentences this run+ added. The off switch is the incident escape hatch; telemetry lands in`details.synthesis.quote_verify`.- `dream.synthesize.max_turns` (default 16) — synthesis turn budget foragentic children and oneshot fallbacks (the default oneshot path — see@@ -5081,9 +5085,11 @@ Three more fields answer "what did that cost and did it land":- `children_zero_pages` — children that completed but wrote no page. A numberthat climbs here means the model is producing valid-but-empty output, whicha green phase status alone would hide.-- `quote_verify` — what the post-write quote pass touched: spans checked,- repaired, and stripped, pages skipped as pre-existing, unbalanced paragraphs,- and the warn-only ungrounded numeric/date claim count.+- `quote_verify` — what the post-write claim check touched: quotes checked+ and repaired, sentences quarantined (with counts per reason:+ `quote_not_in_source`, `quote_crosses_speakers`, `speaker_mismatch`,+ `number_not_in_source`), pre-existing pages checked by diff, and unbalanced+ paragraphs.Per-call spend also lands in the `chat_usage_log` ledger with a phase tag:the orchestrator's own calls under `phase:synthesize`, each drained childdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 3c24a55e53..bb1c01b809 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.59.17.0",+ "version": "0.59.18.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex 38c1ba8823..895f6d1622 100644--- a/package.json+++ b/package.json@@ -190,7 +190,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.59.17.0",+ "version": "0.59.18.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex bea0689911..94711fc4b5 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.59.17.0",+ "version": "0.59.18.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 9028eb0dbc..5b42be7161 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.59.17.0",+ "version": "0.59.18.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 72ab0d5877..82432d66c6 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.17.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.18.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-coding/skills/_brain-filing-rules.md b/plugin-variants/gbrain-coding/skills/_brain-filing-rules.mdindex c323eb350e..7a324945c6 100644--- a/plugin-variants/gbrain-coding/skills/_brain-filing-rules.md+++ b/plugin-variants/gbrain-coding/skills/_brain-filing-rules.md@@ -151,8 +151,9 @@ to add a new directory the synthesis subagent may write to:EXACTLY from the source transcript — if you cannot reproduce a spanexactly, paraphrase it WITHOUT quotation marks. Do not paraphrasememorable phrasings you can quote exactly. A mechanical, zero-LLM verify- pass re-checks every quoted span after the write and repairs or unquotes- whatever it cannot ground (`dream.synthesize.quote_verify`, default on).+ pass re-checks every quote, speaker attribution and number after the write,+ repairs what it can, and moves any sentence it cannot ground out of the+ page into `unverified_claims` (`dream.synthesize.quote_verify`, default on).2. Cross-reference compulsively: every new page MUST link to existing brain content.3. Slug discipline: lowercase alphanumeric and hyphens only, slash-separated. NO underscores, NO file extensions.4. Edited transcripts produce NEW slugs (content-hash suffix changes) — never silently overwrite a prior reflection.diff --git a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md b/plugin-variants/gbrain-coding/skills/maintain/SKILL.mdindex 3a4b39da6f..9e306da0e9 100644--- a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md@@ -179,15 +179,20 @@ scores only) then `gbrain dream retriage --reconcile-queue`; `--force`re-judges everything from scratch. Retriage reads the SAME gate the cycledoes, so a reconcile sweep never cancels a job the rescue admitted.-**Quote verify/repair (post-write, zero LLM):** after slug collection and+**Claim verification (post-write, zero LLM):** after slug collection andbefore the reverse-write, `dream.synthesize.quote_verify` (default on) checks-every quoted span on the pages this phase just created against the transcript-it came from. An exact match is kept; a span that differs only in whitespace,-curly quotes, dashes, or case is replaced with the verbatim transcript slice;-a near match is repaired the same way; anything that still can't be grounded-keeps its TEXT but loses its quotation marks. Nothing is ever fabricated and-no content is deleted. Numeric and date claims absent from the transcript are-counted as warnings, not edits. Telemetry lands in+every page this phase's children wrote against the transcripts that produced+it. Pages created this run are checked whole; pages that already existed are+checked only on the sentences this run added. An exact quote is kept; a quote+that differs only in whitespace, curly quotes, dashes, or case, or a close+paraphrase inside one speaker's turn, is replaced with the verbatim transcript+slice. A sentence is quarantined when a quote grounds nowhere or only across+two speakers, when it attributes a real quote to the wrong speaker, or when it+states a number or date the transcript lacks. Quarantined sentences leave the+page body (and the timeline, facts and links derived from it) and are kept+verbatim in frontmatter `unverified_claims`, which `get_page` shows but search,+recall and think do not read. Grounded quotes record their source span and+speaker in `grounding.quotes`. Nothing is ever fabricated. Telemetry lands in`details.synthesis.quote_verify`; the config key is the incident off switch.**Patterns phase:** runs after `extract` (so the graph state is fresh).diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 9b2415cc90..e3199f761d 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.59.17.0",+ "version": "0.59.18.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 79af49475a..f06c3d4dff 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.59.17.0",+ "version": "0.59.18.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex e7be3c3c58..b34efb8aec 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.17.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.18.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin-variants/gbrain-daily/skills/_brain-filing-rules.md b/plugin-variants/gbrain-daily/skills/_brain-filing-rules.mdindex c323eb350e..7a324945c6 100644--- a/plugin-variants/gbrain-daily/skills/_brain-filing-rules.md+++ b/plugin-variants/gbrain-daily/skills/_brain-filing-rules.md@@ -151,8 +151,9 @@ to add a new directory the synthesis subagent may write to:EXACTLY from the source transcript — if you cannot reproduce a spanexactly, paraphrase it WITHOUT quotation marks. Do not paraphrasememorable phrasings you can quote exactly. A mechanical, zero-LLM verify- pass re-checks every quoted span after the write and repairs or unquotes- whatever it cannot ground (`dream.synthesize.quote_verify`, default on).+ pass re-checks every quote, speaker attribution and number after the write,+ repairs what it can, and moves any sentence it cannot ground out of the+ page into `unverified_claims` (`dream.synthesize.quote_verify`, default on).2. Cross-reference compulsively: every new page MUST link to existing brain content.3. Slug discipline: lowercase alphanumeric and hyphens only, slash-separated. NO underscores, NO file extensions.4. Edited transcripts produce NEW slugs (content-hash suffix changes) — never silently overwrite a prior reflection.diff --git a/plugin/README.md b/plugin/README.mdindex b9c2d6e841..ef9b095821 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.17.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.18.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/plugin/skills/_brain-filing-rules.md b/plugin/skills/_brain-filing-rules.mdindex c323eb350e..7a324945c6 100644--- a/plugin/skills/_brain-filing-rules.md+++ b/plugin/skills/_brain-filing-rules.md@@ -151,8 +151,9 @@ to add a new directory the synthesis subagent may write to:EXACTLY from the source transcript — if you cannot reproduce a spanexactly, paraphrase it WITHOUT quotation marks. Do not paraphrasememorable phrasings you can quote exactly. A mechanical, zero-LLM verify- pass re-checks every quoted span after the write and repairs or unquotes- whatever it cannot ground (`dream.synthesize.quote_verify`, default on).+ pass re-checks every quote, speaker attribution and number after the write,+ repairs what it can, and moves any sentence it cannot ground out of the+ page into `unverified_claims` (`dream.synthesize.quote_verify`, default on).2. Cross-reference compulsively: every new page MUST link to existing brain content.3. Slug discipline: lowercase alphanumeric and hyphens only, slash-separated. NO underscores, NO file extensions.4. Edited transcripts produce NEW slugs (content-hash suffix changes) — never silently overwrite a prior reflection.diff --git a/plugin/skills/maintain/SKILL.md b/plugin/skills/maintain/SKILL.mdindex 3a4b39da6f..9e306da0e9 100644--- a/plugin/skills/maintain/SKILL.md+++ b/plugin/skills/maintain/SKILL.md@@ -179,15 +179,20 @@ scores only) then `gbrain dream retriage --reconcile-queue`; `--force`re-judges everything from scratch. Retriage reads the SAME gate the cycledoes, so a reconcile sweep never cancels a job the rescue admitted.-**Quote verify/repair (post-write, zero LLM):** after slug collection and+**Claim verification (post-write, zero LLM):** after slug collection andbefore the reverse-write, `dream.synthesize.quote_verify` (default on) checks-every quoted span on the pages this phase just created against the transcript-it came from. An exact match is kept; a span that differs only in whitespace,-curly quotes, dashes, or case is replaced with the verbatim transcript slice;-a near match is repaired the same way; anything that still can't be grounded-keeps its TEXT but loses its quotation marks. Nothing is ever fabricated and-no content is deleted. Numeric and date claims absent from the transcript are-counted as warnings, not edits. Telemetry lands in+every page this phase's children wrote against the transcripts that produced+it. Pages created this run are checked whole; pages that already existed are+checked only on the sentences this run added. An exact quote is kept; a quote+that differs only in whitespace, curly quotes, dashes, or case, or a close+paraphrase inside one speaker's turn, is replaced with the verbatim transcript+slice. A sentence is quarantined when a quote grounds nowhere or only across+two speakers, when it attributes a real quote to the wrong speaker, or when it+states a number or date the transcript lacks. Quarantined sentences leave the+page body (and the timeline, facts and links derived from it) and are kept+verbatim in frontmatter `unverified_claims`, which `get_page` shows but search,+recall and think do not read. Grounded quotes record their source span and+speaker in `grounding.quotes`. Nothing is ever fabricated. Telemetry lands in`details.synthesis.quote_verify`; the config key is the incident off switch.**Patterns phase:** runs after `extract` (so the graph state is fresh).diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex ed2e9d350f..9a1bda18c6 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -14,7 +14,7 @@ src/commands/serve-http.ts 3098 ratchet registration and grant routes extracted;src/core/ai/gateway.ts 4441 ratchet +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilingssrc/commands/sync.ts 5995 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration; +1 cancellation guard before company dispatchsrc/core/cycle.ts 3208 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail-src/core/cycle/synthesize.ts 3218 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates+src/core/cycle/synthesize.ts 3222 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiringsrc/core/cycle/extract-atoms.ts 1752 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integrationsrc/core/engine.ts 2665 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contractsrc/core/import-file.ts 2236 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchordiff --git a/scripts/repeated-consolidation-experiment.ts b/scripts/repeated-consolidation-experiment.tsnew file mode 100644index 0000000000..3f03b0f71d--- /dev/null+++ b/scripts/repeated-consolidation-experiment.ts@@ -0,0 +1,22 @@+#!/usr/bin/env bun+/**+ * Hermetic repeated-consolidation experiment: three dream cycles+ * (synthesize → extract → extract_facts) on a fixed PGLite brain with a+ * scripted model that invents quotes, swaps speakers and invents numbers.+ * Prints the measurements as JSON. $0: no network, no paid calls.+ *+ * bun run scripts/repeated-consolidation-experiment.ts [--per-cycle]+ *+ * To compare two trees, copy test/helpers/repeated-consolidation.ts and this+ * script into a checkout of the other tree and run it there.+ */+import { runRepeatedConsolidation } from '../test/helpers/repeated-consolidation.ts';++const perCycle = process.argv.includes('--per-cycle');+const m = await runRepeatedConsolidation();+const { per_cycle, ...summary } = m;+console.log(JSON.stringify(perCycle ? m : summary, null, 2));+if (per_cycle.some(c => Object.values(c.statuses).some(s => s !== 'ok'))) {+ process.stderr.write('warning: a cycle phase did not finish ok; the measurements are not comparable\n');+ process.exitCode = 1;+}diff --git a/skills/_brain-filing-rules.md b/skills/_brain-filing-rules.mdindex c323eb350e..7a324945c6 100644--- a/skills/_brain-filing-rules.md+++ b/skills/_brain-filing-rules.md@@ -151,8 +151,9 @@ to add a new directory the synthesis subagent may write to:EXACTLY from the source transcript — if you cannot reproduce a spanexactly, paraphrase it WITHOUT quotation marks. Do not paraphrasememorable phrasings you can quote exactly. A mechanical, zero-LLM verify- pass re-checks every quoted span after the write and repairs or unquotes- whatever it cannot ground (`dream.synthesize.quote_verify`, default on).+ pass re-checks every quote, speaker attribution and number after the write,+ repairs what it can, and moves any sentence it cannot ground out of the+ page into `unverified_claims` (`dream.synthesize.quote_verify`, default on).2. Cross-reference compulsively: every new page MUST link to existing brain content.3. Slug discipline: lowercase alphanumeric and hyphens only, slash-separated. NO underscores, NO file extensions.4. Edited transcripts produce NEW slugs (content-hash suffix changes) — never silently overwrite a prior reflection.diff --git a/skills/maintain/SKILL.md b/skills/maintain/SKILL.mdindex 3a4b39da6f..9e306da0e9 100644--- a/skills/maintain/SKILL.md+++ b/skills/maintain/SKILL.md@@ -179,15 +179,20 @@ scores only) then `gbrain dream retriage --reconcile-queue`; `--force`re-judges everything from scratch. Retriage reads the SAME gate the cycledoes, so a reconcile sweep never cancels a job the rescue admitted.-**Quote verify/repair (post-write, zero LLM):** after slug collection and+**Claim verification (post-write, zero LLM):** after slug collection andbefore the reverse-write, `dream.synthesize.quote_verify` (default on) checks-every quoted span on the pages this phase just created against the transcript-it came from. An exact match is kept; a span that differs only in whitespace,-curly quotes, dashes, or case is replaced with the verbatim transcript slice;-a near match is repaired the same way; anything that still can't be grounded-keeps its TEXT but loses its quotation marks. Nothing is ever fabricated and-no content is deleted. Numeric and date claims absent from the transcript are-counted as warnings, not edits. Telemetry lands in+every page this phase's children wrote against the transcripts that produced+it. Pages created this run are checked whole; pages that already existed are+checked only on the sentences this run added. An exact quote is kept; a quote+that differs only in whitespace, curly quotes, dashes, or case, or a close+paraphrase inside one speaker's turn, is replaced with the verbatim transcript+slice. A sentence is quarantined when a quote grounds nowhere or only across+two speakers, when it attributes a real quote to the wrong speaker, or when it+states a number or date the transcript lacks. Quarantined sentences leave the+page body (and the timeline, facts and links derived from it) and are kept+verbatim in frontmatter `unverified_claims`, which `get_page` shows but search,+recall and think do not read. Grounded quotes record their source span and+speaker in `grounding.quotes`. Nothing is ever fabricated. Telemetry lands in`details.synthesis.quote_verify`; the config key is the incident off switch.**Patterns phase:** runs after `extract` (so the graph state is fresh).diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 9dc36ff7f2..b27ab816e0 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -2,7 +2,7 @@"RESOLVER.md": "d4a01e2475db5b7efe87d5a789947085c446d249fe90cdb87ff929117986f537","_AGENT_README.md": "0b755aa945df0da0f27cb3323904f54b99b3dfaf8065033e6cf9108ac4be38bb","_brain-filing-rules.json": "cf850df6a7425464c6d63b3ace71991cc93497fa0cc8cd21acd31883e17939c6",- "_brain-filing-rules.md": "23f5d08d705eb975b69611dbfbe878b7e4f3d0eec2470a52160372df8b462ad1",+ "_brain-filing-rules.md": "b8f6844fd7ab6fbe4a4e7a95e7089466b37d63127730040c766927f55b1ad138","_friction-protocol.md": "51353207240142024ff1facc25f225712275ecdb4a034ffffdd83740c8d328e3","_output-rules.md": "0722ec2ecea7f9fa2f065cf12dfe1347956a9709d29898bf9fe95e875c64b800","academic-verify/SKILL.md": "1c19e27e75249d869da428ce8d060075feef8fbbfe146af58b305d11a260ebbc",@@ -92,7 +92,7 @@"idea-lineage/SKILL.md": "bbf37781d93b71ddc7909ecc5ab635872c874fb8591995dbf88b45ffeac6b1de","idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41","ingest/SKILL.md": "dc40ecc0072806fb8c7bb6ab9cf1f103842e05653eb55d67632d7e3ffc4dd7d2",- "maintain/SKILL.md": "92111d9203e940a6f068f9b3abe7516e7831de9a7e77d234bb6da6125c3d663a",+ "maintain/SKILL.md": "74244af50a4faf3d3b2f16250cae0d01c2911fa50d2fca1a02f936f9dc2a21d6","manifest.json": "357aa185d380f0a357cb15cd513317e290cbc5fcf5ca4e3860b0e829fdcbf1e4","mcp-access/SKILL.md": "d96d0720d3f15f442e2f87803354206795f04ae114869a2cf608aa5c9955585d","measure-before-you-fix/SKILL.md": "1fd3b40ab65cbd08f50dea16107701859165469be3c85c57d779c7b4bbf92db8",diff --git a/src/commands/eval-compare.ts b/src/commands/eval-compare.tsindex ba73763a58..7cf917c006 100644--- a/src/commands/eval-compare.ts+++ b/src/commands/eval-compare.ts@@ -5,19 +5,24 @@* `gbrain eval run-all` plus any manually-logged completions), groups by* (suite, mode), and produces a side-by-side table.*- * Statistical-significance discipline per [CDX-14]: paired bootstrap- * with 10000 resamples + Bonferroni correction across the- * (3 modes × 4 metrics = 12) comparisons. Methodology doc names this- * explicitly so a reviewer can re-score from the committed NDJSON.+ * Statistics are computed only from per-query rows. A run record that+ * points at its per-question output (`params.output`, written by+ * `gbrain eval longmemeval --record --output`) contributes rows; pairs of+ * runs are joined on question_id and compared with a paired cluster+ * bootstrap (95% CI), a two-sided sign-flip randomization p-value, and Holm+ * correction across every comparison in the report+ * (src/core/eval/paired-bootstrap.ts). When no per-query rows are+ * available the report says it is aggregate-only and computes nothing.** Every numeric metric in the output is glossed through the* src/core/eval/metric-glossary.ts module per [CDX-25]: ONE* _meta.metric_glossary block per response, NOT sibling _gloss fields.*/-import { readFileSync, existsSync } from 'fs';-import { join } from 'path';+import { readFileSync, existsSync, realpathSync } from 'fs';+import { isAbsolute, join, relative, sep } from 'path';import { buildMetricGlossaryMeta } from '../core/eval/metric-glossary.ts';+import { holmAdjusted, pairedClusterStatistics } from '../core/eval/paired-bootstrap.ts';import { SEARCH_MODES, type SearchMode } from '../core/search/mode.ts';export interface CompareOpts {@@ -28,6 +33,10 @@ export interface CompareOpts {json: boolean;md: boolean;inputPath?: string;+ baseline?: string;+ candidate?: string;+ draws: number;+ seed: number;}function parseCompareArgs(args: string[]): CompareOpts {@@ -37,6 +46,8 @@ function parseCompareArgs(args: string[]): CompareOpts {modes: 'all',json: false,md: true,+ draws: 10_000,+ seed: 42,};for (let i = 0; i < args.length; i++) {const a = args[i];@@ -63,7 +74,16 @@ function parseCompareArgs(args: string[]): CompareOpts {if (a === '--json') { opts.json = true; opts.md = false; continue; }if (a === '--md') { opts.md = true; opts.json = false; continue; }if (a === '--input') { opts.inputPath = args[++i]; continue; }+ if (a === '--baseline') { opts.baseline = args[++i]; continue; }+ if (a === '--candidate') { opts.candidate = args[++i]; continue; }+ if (a === '--draws' || a === '--seed') {+ const v = Number(args[++i]);+ if (!Number.isInteger(v) || v < (a === '--draws' ? 1000 : 0)) throw new Error(`${a}: expected an integer${a === '--draws' ? ' >= 1000' : ''}`);+ if (a === '--draws') opts.draws = v; else opts.seed = v;+ continue;+ }}+ if ((opts.baseline === undefined) !== (opts.candidate === undefined)) throw new Error('--baseline and --candidate go together');return opts;}@@ -78,6 +98,12 @@ function printHelp(): void {` --md Markdown output (default; CHANGELOG-paste-ready).\n` +` --json JSON output (CI / programmatic consumption).\n` +` --input PATH Override eval-results.jsonl location.\n` ++ ` --baseline RUN_ID Compare exactly this run ...\n` ++ ` --candidate RUN_ID ... against this one (default: every mode pair).\n` ++ ` --draws N Bootstrap resamples (default 10000).\n` ++ ` --seed N Resampling seed (default 42).\n\n` ++ `Paired statistics need per-query rows: a run record whose params.output\n` ++ `names its per-question JSONL. Without them the report is aggregate-only.\n` +` -h, --help Show this help.\n`,);}@@ -93,6 +119,148 @@ interface ParsedRecord {duration_ms?: number;error?: string;metrics?: Record<string, number>;+ params?: Record<string, unknown>;+}++type QueryRow = Record<string, unknown>;++/** Per-query metrics read from per-question rows, named as in the glossary. */+const PER_QUERY_METRICS: Array<{ name: string; value: (row: QueryRow) => number | undefined }> = [+ { name: 'recall_all@k', value: r => typeof r.recall_all_hit === 'boolean' ? Number(r.recall_all_hit) : undefined },+ { name: 'recall_any@k', value: r => typeof r.recall_any_hit === 'boolean' ? Number(r.recall_any_hit) : undefined },+ { name: 'qa_accuracy', value: r => typeof r.judge_correct === 'boolean' && typeof r.judge_error !== 'string' ? Number(r.judge_correct) : undefined },+];++export interface PairedComparison {+ suite: string;+ baseline_run: string;+ candidate_run: string;+ baseline_mode: string;+ candidate_mode: string;+ metric: string;+ n: number;+ clusters: number;+ baseline_mean: number;+ candidate_mean: number;+ delta: number;+ ci95: [number, number];+ p_value: number;+ holm_p_value: number;+ wins: number;+ losses: number;+ ties: number;+ significant: boolean;+}++/**+ * `candidate` resolved against `root`, following symlinks, or null when it+ * lands outside the root (through `..`, an absolute path, or a symlink).+ */+export function pathWithinRoot(root: string, candidate: string): string | null {+ const base = realpathSync(root);+ const target = isAbsolute(candidate) ? candidate : `${base}${sep}${candidate}`;+ const real = existsSync(target) ? realpathSync(target) : target;+ // relative() normalizes `..` segments of a path that does not exist yet.+ const rel = relative(base, real);+ return rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) ? null : real;+}++/** Per-question rows of a run (last row per question_id), or why there are none. */+function readPerQueryRows(record: ParsedRecord, repoRoot: string): { rows: Map<string, QueryRow> } | { reason: string } {+ const output = record.params?.output;+ if (typeof output !== 'string' || !output) return { reason: 'record has no params.output per-query file' };+ const path = pathWithinRoot(repoRoot, output);+ if (!path) return { reason: `refused per-query file outside the repository root (${repoRoot}): ${output}` };+ if (!existsSync(path)) return { reason: `per-query file not found: ${output}` };+ const rows = new Map<string, QueryRow>();+ for (const line of readFileSync(path, 'utf-8').split('\n')) {+ if (!line.trim()) continue;+ try {+ const row = JSON.parse(line) as QueryRow;+ if (row && typeof row.question_id === 'string' && row.kind !== 'by_type_summary') rows.set(row.question_id, row);+ } catch {+ // Same tolerance as the run ledger: a torn line never tanks the report.+ }+ }+ return rows.size ? { rows } : { reason: `per-query file has no question rows: ${output}` };+}++/**+ * Paired comparisons for each (baseline, candidate) run pair: rows joined on+ * question_id, one comparison per metric both rows carry, questions as+ * clusters, Holm across the whole family.+ */+export function pairedComparisons(+ pairs: Array<[ParsedRecord, ParsedRecord]>,+ repoRoot: string,+ opts: { draws: number; seed: number },+): { comparisons: PairedComparison[]; unavailable: Array<{ run_id: string; reason: string }> } {+ const unavailable = new Map<string, string>();+ const cache = new Map<string, Map<string, QueryRow> | null>();+ const rowsOf = (r: ParsedRecord) => {+ if (!cache.has(r.run_id)) {+ const loaded = readPerQueryRows(r, repoRoot);+ if ('reason' in loaded) unavailable.set(r.run_id, loaded.reason);+ cache.set(r.run_id, 'rows' in loaded ? loaded.rows : null);+ }+ return cache.get(r.run_id) ?? null;+ };+ const raw: Array<Omit<PairedComparison, 'holm_p_value' | 'significant'>> = [];+ for (const [b, c] of pairs) {+ const bRows = rowsOf(b), cRows = rowsOf(c);+ if (!bRows || !cRows) continue;+ for (const metric of PER_QUERY_METRICS) {+ const observations = [...bRows].flatMap(([qid, row]) => {+ const other = cRows.get(qid);+ const bv = metric.value(row), cv = other ? metric.value(other) : undefined;+ return bv === undefined || cv === undefined ? [] : [{ cluster: qid, baseline: bv, candidate: cv }];+ });+ if (!observations.length) continue;+ const st = pairedClusterStatistics(observations, opts);+ raw.push({+ suite: c.suite, baseline_run: b.run_id, candidate_run: c.run_id, baseline_mode: b.mode, candidate_mode: c.mode,+ metric: metric.name, n: st.n, clusters: st.clusters, baseline_mean: st.baseline_mean, candidate_mean: st.candidate_mean,+ delta: st.delta, ci95: [st.lower95, st.upper95], p_value: st.p_value, wins: st.wins, losses: st.losses, ties: st.ties,+ });+ }+ }+ const holm = holmAdjusted(raw.map(r => r.p_value));+ const comparisons = raw.map((r, i) => ({+ ...r,+ holm_p_value: holm[i],+ significant: holm[i] <= 0.05 && (r.ci95[0] > 0 || r.ci95[1] < 0),+ }));+ return { comparisons, unavailable: [...unavailable].map(([run_id, reason]) => ({ run_id, reason })) };+}++function methodologyText(comparisons: PairedComparison[], opts: { draws: number; seed: number }): string {+ if (!comparisons.length) {+ return 'Aggregate-only: no per-query rows were available for the selected runs, so no confidence intervals or significance tests were computed. Aggregate metrics are shown as recorded.';+ }+ return `Paired cluster bootstrap over per-query rows joined on question_id (${opts.draws} resamples, seed ${opts.seed}; clusters = questions); `+ + 'two-sided sign-flip randomization p-values (exact at 16 or fewer clusters); '+ + `Holm correction across the ${comparisons.length} comparison(s) in this report. A difference is significant only when the Holm p-value is at most 0.05 and the 95% CI excludes 0. `+ + 'See docs/eval/SEARCH_MODE_METHODOLOGY.md.';+}++function fmt(x: number): string {+ return Number.isFinite(x) ? x.toFixed(4) : String(x);+}++function renderPaired(comparisons: PairedComparison[], unavailable: Array<{ run_id: string; reason: string }>, methodology: string): string {+ const lines = ['## Paired comparisons', ''];+ if (comparisons.length) {+ lines.push('| Suite | Baseline → Candidate | Metric | Pairs (clusters) | Baseline | Candidate | Δ | 95% CI | p | Holm p | Wins / losses / ties | Verdict |');+ lines.push('|---|---|---|---|---|---|---|---|---|---|---|---|');+ for (const c of comparisons) {+ lines.push(`| ${c.suite} | \`${c.baseline_run}\` (${c.baseline_mode}) → \`${c.candidate_run}\` (${c.candidate_mode}) | ${c.metric} | ${c.n} (${c.clusters}) | ${fmt(c.baseline_mean)} | ${fmt(c.candidate_mean)} | ${fmt(c.delta)} | [${fmt(c.ci95[0])}, ${fmt(c.ci95[1])}] | ${fmt(c.p_value)} | ${fmt(c.holm_p_value)} | ${c.wins} / ${c.losses} / ${c.ties} | ${c.significant ? 'significant' : 'not significant'} |`);+ }+ lines.push('');+ }+ for (const u of unavailable) lines.push(`- \`${u.run_id}\`: ${u.reason}`);+ if (unavailable.length) lines.push('');+ lines.push(`_${methodology}_`, '');+ return lines.join('\n');}function readEvalResults(repoRoot: string, override?: string): ParsedRecord[] {@@ -231,16 +399,35 @@ export async function runEvalCompare(args: string[]): Promise<void> {if (r?.metrics) Object.keys(r.metrics).forEach(k => allMetrics.add(k));}}++ let runPairs: Array<[ParsedRecord, ParsedRecord]> = [];+ if (opts.baseline && opts.candidate) {+ const find = (id: string) => records.find(r => r.run_id === id);+ const b = find(opts.baseline), c = find(opts.candidate);+ if (!b || !c) throw new Error(`run not found in eval-results.jsonl: ${!b ? opts.baseline : opts.candidate}`);+ runPairs = [[b, c]];+ } else {+ for (const modes of Object.values(grouped)) {+ const present = SEARCH_MODES.map(m => modes[m]).filter((r): r is ParsedRecord => r !== null);+ for (let i = 0; i < present.length; i++) for (let j = i + 1; j < present.length; j++) runPairs.push([present[i], present[j]]);+ }+ }+ const { comparisons, unavailable } = pairedComparisons(runPairs, repoRoot, opts);+ comparisons.forEach(c => allMetrics.add(c.metric));+ if (comparisons.length) ['p_value', 'confidence_interval'].forEach(k => allMetrics.add(k));const glossary = buildMetricGlossaryMeta(Array.from(allMetrics));+ const methodology = methodologyText(comparisons, opts);if (opts.json) {process.stdout.write(JSON.stringify({schema_version: 2,records: filtered,grouped,+ paired: comparisons,+ paired_unavailable: unavailable,_meta: {metric_glossary: glossary,- methodology: 'Paired bootstrap (10,000 resamples) + Bonferroni correction across 3 modes × 4 metrics. See docs/eval/SEARCH_MODE_METHODOLOGY.md.',+ methodology,},}, null, 2));return;@@ -253,4 +440,5 @@ export async function runEvalCompare(args: string[]): Promise<void> {}process.stdout.write(renderMarkdown(grouped, glossary));+ process.stdout.write(renderPaired(comparisons, unavailable, methodology));}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex a51fd7bd31..a837b19ea2 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -51,7 +51,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'embed': ['--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--yes'],'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],'enrich': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],- 'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],+ 'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],'export': ['--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type'],'extract': ['--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--dir', '--dry-run', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--repair-attendance', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],'extract-conversation-facts': ['--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embedding', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--segment-limit', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--workers', '--yes'],diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.tsindex b865ce079a..49c0758df7 100644--- a/src/core/cycle/synthesize-postprocess.ts+++ b/src/core/cycle/synthesize-postprocess.ts@@ -9,7 +9,7 @@ import type { WriteRequest } from '../persistence/model.ts';import { publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { writeResponse } from '../persistence/service.ts';import type { DiscoveredTranscript } from './transcript-discovery.ts';-import { emptyQuoteVerifyStats, normalizeForGrounding, repairDreamPageMarkdown, type GroundedTranscript } from './synthesize-verify.ts';+import { emptyQuoteVerifyStats, groundSource, resolveVerifyPrior, verifyDreamPage, type GroundedSource } from './synthesize-verify.ts';interface OutputRef { slug: string; source_id: string; raw_source?: string; }interface RetainedOutput { job_id: number | bigint; job_key: string; request: WriteRequest; }@@ -21,7 +21,7 @@ export async function postprocessManagedSynthesis(childIds: number[],jobRawSource: Map<number, string>,transcripts: DiscoveredTranscript[],- opts: { cycleDate: string; quoteVerify: boolean; signal?: AbortSignal },+ opts: { cycleDate: string; quoteVerify: boolean; sinceByTranscript: Map<string, Date>; signal?: AbortSignal },) {const stats = emptyQuoteVerifyStats();const writtenRefs: OutputRef[] = [];@@ -37,8 +37,7 @@ export async function postprocessManagedSynthesis(WHERE t.job_id=ANY($1::int[]) AND t.tool_name='brain_put_page' AND t.status='complete'ORDER BY p.sequence DESC`, [childIds, authority.writer.sourceId, authority.writer.sourceIncarnation]);const byPath = new Map(transcripts.map(t => [t.filePath, t]));- let groundedPath: string | undefined;- let grounded: GroundedTranscript | undefined;+ let grounded: GroundedSource | undefined;for (const ref of [...refs].sort((a, b) => (a.raw_source ?? '').localeCompare(b.raw_source ?? ''))) {throwIfAborted(opts.signal, '[dream] synthesis postprocessing');if (ref.source_id !== authority.writer.sourceId) throw new OperationError('source_changed', 'The synthesis output source changed.');@@ -72,21 +71,21 @@ export async function postprocessManagedSynthesis(throw new OperationError('revision_conflict', 'The synthesis output changed after the child committed.');}const firstDate = snapshot.page.frontmatter.dream_created_cycle_date || snapshot.page.frontmatter.dream_cycle_date || opts.cycleDate;- const page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,+ let page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, raw_source: path } };- content = serializePageToMarkdown(page, snapshot.tags);if (opts.quoteVerify) {- if (!ref.slug.includes(`-${transcript.contentHash.slice(0, 6)}`)) stats.skipped_preexisting++;+ const since = opts.sinceByTranscript.get(transcript.filePath);+ const prior = since ? await resolveVerifyPrior(engine, snapshot.page, ref.source_id, since) : null;+ if (prior === 'unchanged') stats.skipped_unchanged++;else {- if (groundedPath !== path) {- groundedPath = path;- grounded = { content: transcript.content, ...normalizeForGrounding(transcript.content) };- }- const repaired = repairDreamPageMarkdown(content, grounded!, stats);- if (repaired !== content) stats.pages_repaired++;- content = repaired;+ if (prior) stats.preexisting_diffed++;+ const source = grounded?.path === transcript.filePath ? grounded : (grounded = groundSource(transcript.filePath, transcript.content));+ const verified = verifyDreamPage(page, [source], { prior, checkedAt: opts.cycleDate }, stats);+ if (verified.changed) stats.pages_repaired++;+ page = { ...page, compiled_truth: verified.compiled_truth, timeline: verified.timeline, frontmatter: verified.frontmatter as typeof page.frontmatter };}}+ content = serializePageToMarkdown(page, snapshot.tags);}throwIfAborted(opts.signal, '[dream] synthesis postprocessing');await publishMaintenancePage(engine, authority, ref.slug, content, { requestId, expectedRevision: revision });diff --git a/src/core/cycle/synthesize-verify.ts b/src/core/cycle/synthesize-verify.tsindex 248f7ea39c..2f75ae078c 100644--- a/src/core/cycle/synthesize-verify.ts+++ b/src/core/cycle/synthesize-verify.ts@@ -1,55 +1,69 @@/**- * synthesize-verify.ts — mechanical quote verify/repair on dream pages (F1b/F4b,- * eval write-path fix wave).+ * synthesize-verify.ts — mechanical claim verification on dream pages+ * (F1b/F4b, eval write-path fix wave; grounding gate, gbrain 10x amendment 7).*- * The synthesis prompt mandates verbatim quotes; measured against the Cat 35- * benchmark, fewer than half of quoted spans in produced pages were substrings- * of the source transcript — the model paraphrases inside quotation marks.- * This pass runs right after the children's put_page writes and BEFORE- * stampDreamProvenance / reverseWriteRefs / the phase-end embed sweep, so the- * provenance stamp, the markdown file, and the embedded chunks all carry the- * repaired body.+ * The synthesis prompt mandates verbatim quotes and source-exact numbers;+ * measured against the Cat 35 benchmark, fewer than half of quoted spans in+ * produced pages were substrings of the source transcript. This pass runs+ * right after the children's put_page writes and BEFORE stampDreamProvenance /+ * reverseWriteRefs / the phase-end embed sweep, so the provenance stamp, the+ * markdown file, and the embedded chunks all carry the verified body.*- * writtenRefs ──▶ scope filter ──▶ per-page repair ladder ──▶ write-back- * (slug,src, only NEW pages per quoted span: only when a- * raw_source) whose slug carries 1. exact substring → keep span changed,- * │ this transcript's 2. normalized match → replace with- * │ hash6 suffix the VERBATIM transcript span- * ▼ (people/pattern 3. near match (rare-trigram anchor,- * skipped_* edits skipped) ≥0.8 token overlap) → replace- * counters 4. else STRIP the quote marks- * (honest paraphrase, never invent)+ * writtenRefs ──▶ group by page ──▶ claim units (sentences, list items,+ * (slug,src, sources = every table rows) that are NEW:+ * raw_source) transcript that - whole body for pages created+ * wrote the page during this run+ * - only units absent from the+ * pre-run revision (page_versions)+ * for pages that already existed+ * per new unit:+ * quotes → exact / normalized / near+ * (verbatim transcript slice, never+ * across a speaker turn)+ * attribution → the named speaker must+ * be the turn's speaker+ * numbers → must occur in a source+ * any failure → the WHOLE unit leaves the+ * body and is kept in frontmatter+ * `unverified_claims`*- * Ladder invariant: NEVER fabricate — every replacement is a verbatim slice of- * the source transcript; when nothing grounds, the span loses its quotation- * marks but keeps its text. Whole-page verification is scoped to pages this- * transcript CREATED (slug carries the transcript's content-hash suffix, which- * binds page↔transcript identity); pre-existing pages a child modified- * (people/patterns) may quote OTHER sources and are skipped, counted.+ * Invariants:+ * - NEVER fabricate: every replacement is a verbatim slice of a source+ * transcript, trimmed to the matched tokens inside one speaker turn.+ * - NEVER keep an unsupported derived assertion as authoritative text: the+ * unit is removed from compiled_truth/timeline (so it has no chunks, no+ * search_vector weight, no timeline/facts extraction, no think/context+ * evidence) and preserved verbatim in `unverified_claims` for review.+ * Frontmatter is not chunked or searched, so the record is visible to+ * get_page readers but excluded from authoritative recall.+ * - Provenance: every grounded quote records its source path, the+ * character span in that source, and the speaker of that turn in+ * frontmatter `grounding.quotes`.*- * Failure contract (fail-open, pacer precedent — a verify bug never kills the- * phase): unbalanced quote marks → skip that paragraph's spans of that mark- * type + count; page read-back miss → skip page + count; write-back throw →+ * Failure contract (fail-open per page, pacer precedent — a verify bug never+ * kills the phase): page read-back miss → count + skip; write-back throw →* log slug+source, count, continue. Zero LLM calls; pure string ops with hard- * probe/size caps so adversarial page or transcript content degrades to- * "strip" or "skip", never to unbounded CPU.+ * probe/size caps.** Write-back reuses the SAME canonical pipeline the children's put_page tool* executes — importFromContent (page + tags + chunks + link extraction in one* transaction, content_hash recomputed) with noEmbed: the phase-end embed- * sweep backfills, exactly like the oneshot runner's deferEmbeds writes. A- * bare engine.putPage would upsert only the pages row and leave stale- * chunk_text for the sweep to embed.+ * sweep backfills.** Kill switch: `dream.synthesize.quote_verify` (default on), read by* loadSynthConfig — the incident escape hatch for the one mechanism that* rewrites page bodies.*/+import { basename } from 'node:path';import type { BrainEngine } from '../engine.ts';import { importFromContent } from '../import-file.ts';import { serializePageToMarkdown } from '../markdown.ts';import { throwIfAborted } from '../abort-check.ts';+import type { Page } from '../types.ts';+import { prepareCanonicalProjections } from '../persistence/canonical-projections.ts';+import { prepareAutomaticLinks } from '../persistence/links-preparation.ts';+import { isAutoLinkEnabled } from '../link-extraction.ts';/** Minimum quoted-span inner length considered a "quote" (shorter spans are* scare quotes / titles, not transcript quotations). */@@ -59,28 +73,41 @@ const MAX_QUOTES_PER_PAGE = 200;/** Near-match acceptance floor (token overlap) and ambiguity margin. */const NEAR_MATCH_FLOOR = 0.8;const NEAR_MATCH_AMBIGUITY = 0.05;+/** A near-match repair longer than this multiple of the quote is refused. */+const NEAR_MATCH_MAX_GROWTH = 1.3;/** Rung-3 CPU bounds: candidate windows scored, TOTAL trigram indexOf probes* (a long ungroundable quote must not do thousands of full-transcript scans* on the event loop), trigrams considered (stride-sampled above this), and* the largest normalized quote rung 3 will attempt at all — a multi-thousand- * char "quote" that isn't exact/normalized is fabricated in practice and- * goes straight to strip. */+ * char "quote" that isn't exact/normalized is fabricated in practice. */const MAX_ANCHOR_CANDIDATES = 50;const MAX_ANCHOR_PROBES = 200;const MAX_NEAR_TRIGRAMS = 50;const MAX_NEAR_QUOTE_NORM_CHARS = 2000;/** Near-match window shaping: growth over the quote's normalized length and- * fixed char slack on each side (word-boundary snapped after). */+ * fixed char slack on each side (clipped to one speaker turn, then trimmed to+ * the matched tokens). */const WINDOW_GROWTH = 1.2;const WINDOW_SLACK_BEFORE = 20;const WINDOW_SLACK_AFTER = 40;-/** F4b soft cap: unique numeric/date claims checked per page (warn-only- * telemetry — a bounded sample keeps its signal on numbers-dense pages). */+/** Occurrences of an exact/normalized quote considered for speaker checks. */+const MAX_OCCURRENCES = 8;+/** Unique numeric/date claims checked per page (CPU bound). */const MAX_NUMERIC_CLAIMS_PER_PAGE = 200;+/** Frontmatter record caps (newest kept) so repeated cycles stay bounded. */+const MAX_UNVERIFIED_RECORDS = 100;+const MAX_PROVENANCE_RECORDS = 200;+const PROVENANCE_TEXT_CHARS = 160;++export const UNVERIFIED_CLAIMS_KEY = 'unverified_claims';+export const GROUNDING_KEY = 'grounding';+/** Body left behind when every unit on a page failed verification (the+ * engine refuses to blank a non-empty body for maintenance writers). */+export const ALL_CLAIMS_QUARANTINED_BODY = 'All claims on this page failed source verification; they are kept in `unverified_claims` for review.';/** Shared code/link masking (offset-preserving): fenced blocks, inline code,* wikilinks, and markdown link targets are replaced with spaces so quote- * marks inside them never pair with prose quotes. */+ * marks and slug dates inside them never register as prose claims. */function maskNonProse(body: string): string {return body.replace(/```[\s\S]*?(?:```|$)/g, m => ' '.repeat(m.length))@@ -91,17 +118,30 @@ function maskNonProse(body: string): string {export interface QuoteVerifyStats {pages_checked: number;+ /** Pages whose body or grounding record was written back. */pages_repaired: number;+ /** Pages with at least one quarantined claim. */+ pages_with_quarantine: number;+ /** Pre-existing pages verified against their pre-run revision (diff only). */+ preexisting_diffed: number;+ /** Pre-existing pages with no revision recorded during this run (unchanged). */+ skipped_unchanged: number;quotes_total: number;exact: number;normalized_fixed: number;near_fixed: number;- stripped: number;unbalanced: number;- skipped_preexisting: number;+ /** Claim units removed from the body into `unverified_claims`. */+ quarantined_claims: number;+ /** Quotes found in no source transcript. */+ quote_not_in_source: number;+ /** Quotes whose only source match crossed a speaker turn. */+ quote_crosses_speakers: number;+ /** Quotes attributed to a speaker other than the one who said them. */+ speaker_mismatch: number;+ /** Numeric/date claims found in no source transcript. */+ number_not_in_source: number;skipped_no_transcript: number;- /** F4b warn-only: numeric/date claims in page bodies absent from the transcript. */- numeric_claim_warns: number;/** Pages where read-back or write-back failed (fail-open, logged). */errors: number;}@@ -110,15 +150,20 @@ export function emptyQuoteVerifyStats(): QuoteVerifyStats {return {pages_checked: 0,pages_repaired: 0,+ pages_with_quarantine: 0,+ preexisting_diffed: 0,+ skipped_unchanged: 0,quotes_total: 0,exact: 0,normalized_fixed: 0,near_fixed: 0,- stripped: 0,unbalanced: 0,- skipped_preexisting: 0,+ quarantined_claims: 0,+ quote_not_in_source: 0,+ quote_crosses_speakers: 0,+ speaker_mismatch: 0,+ number_not_in_source: 0,skipped_no_transcript: 0,- numeric_claim_warns: 0,errors: 0,};}@@ -203,16 +248,203 @@ export function normForGrounding(s: string): string {return foldForGrounding(s, false) as string;}+/** One speaker-turn anchor (`**Name** (ts):`, `role (tN):`, `Name:`), in+ * ORIGINAL transcript offsets. `labelEnd` is where the turn's words begin. */+export interface SpeakerTurn {+ labelStart: number;+ labelEnd: number;+ speaker: string;+}+export interface GroundedTranscript {content: string;norm: string;map: number[];+ /** Speaker-turn anchors, ascending. Absent or empty: no turn structure. */+ turns?: SpeakerTurn[];+}++/** A transcript prepared for verification: grounding text, speaker turns,+ * the canonical numbers and dates it states, and the speaker-mention+ * patterns used for attribution checks. */+export interface GroundedSource extends GroundedTranscript {+ path: string;+ turns: SpeakerTurn[];+ numbers: Set<string>;+ nameNorm: string;+ speakers: Array<{ key: string; label: string; re: RegExp }>;}export interface TranscriptForVerify {content: string;- /** First 6 hex chars of the transcript content hash — the slug binding. */- hash6: string;+}++const ROLE_ALIASES: Record<string, string> = {+ user: 'user', human: 'user', me: 'user',+ assistant: 'assistant', ai: 'assistant', bot: 'assistant',+ system: 'system',+};+const ROLE_MENTION: Record<string, string> = {+ user: 'user|human',+ assistant: 'assistant',+ system: 'system',+};+const BOLD_ANCHOR_RE = /^[ \t]*\*\*([^*\n]{1,60}?)\*\*(?:[ \t]*\([^)\n]{0,40}\))?[ \t]*:/;+const PLAIN_ANCHOR_RE = /^[ \t]*(?:\[[^\]\n]{1,40}\][ \t]*)?([A-Za-z][A-Za-z0-9.'_-]*(?: [A-Za-z][A-Za-z0-9.'_-]*){0,3})(?:[ \t]*\([^)\n]{0,40}\))?[ \t]*:(?=[ \t]|\r?$)/;++/** Canonical speaker identity: role labels fold to their role, names to lowercase. */+export function speakerKey(label: string): string {+ const k = label.trim().toLowerCase();+ return ROLE_ALIASES[k] ?? k;+}++/**+ * Speaker turns from line-start anchors. Bold anchors (the transcript+ * renderer's format) always count; plain `Label:` anchors count when the+ * label is a role word or opens at least two lines, so a prose line such as+ * `Note: ...` is not mistaken for a speaker.+ */+export function parseSpeakerTurns(content: string): SpeakerTurn[] {+ const turns: SpeakerTurn[] = [];+ const plain: SpeakerTurn[] = [];+ const plainCounts = new Map<string, number>();+ let offset = 0;+ for (const line of content.split('\n')) {+ const bold = BOLD_ANCHOR_RE.exec(line);+ if (bold) {+ turns.push({ labelStart: offset, labelEnd: offset + bold[0].length, speaker: bold[1].trim() });+ } else {+ const p = PLAIN_ANCHOR_RE.exec(line);+ if (p) {+ const speaker = p[1].trim();+ plain.push({ labelStart: offset, labelEnd: offset + p[0].length, speaker });+ plainCounts.set(speaker.toLowerCase(), (plainCounts.get(speaker.toLowerCase()) ?? 0) + 1);+ }+ }+ offset += line.length + 1;+ }+ for (const t of plain) {+ const k = t.speaker.toLowerCase();+ if (ROLE_ALIASES[k] || (plainCounts.get(k) ?? 0) >= 2) turns.push(t);+ }+ return turns.sort((a, b) => a.labelStart - b.labelStart);+}++function turnIndexAt(turns: SpeakerTurn[], offset: number): number {+ let lo = 0, hi = turns.length - 1, found = -1;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ if (turns[mid].labelStart <= offset) { found = mid; lo = mid + 1; } else hi = mid - 1;+ }+ return found;+}++/** Speaker of the turn containing an original-offset position, or null. */+export function speakerAt(turns: SpeakerTurn[] | undefined, offset: number): string | null {+ if (!turns?.length) return null;+ const i = turnIndexAt(turns, offset);+ return i >= 0 ? turns[i].speaker : null;+}++/** True when [start, end) touches a speaker label, i.e. spans two turns. */+function crossesTurn(turns: SpeakerTurn[] | undefined, start: number, end: number): boolean {+ if (!turns?.length) return false;+ let lo = 0, hi = turns.length - 1, first = turns.length;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ if (turns[mid].labelEnd > start) { first = mid; hi = mid - 1; } else lo = mid + 1;+ }+ return first < turns.length && turns[first].labelStart < end;+}++/** First normalized index whose original offset is >= `orig`. */+function normIndexAt(map: number[], orig: number): number {+ let lo = 0, hi = map.length;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (map[mid] < orig) lo = mid + 1; else hi = mid;+ }+ return lo;+}++function escapeRegExp(s: string): string {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++function speakerMentionPatterns(turns: SpeakerTurn[]): GroundedSource['speakers'] {+ const byKey = new Map<string, string>();+ for (const t of turns) if (!byKey.has(speakerKey(t.speaker))) byKey.set(speakerKey(t.speaker), t.speaker);+ const out: GroundedSource['speakers'] = [];+ for (const [key, label] of byKey) {+ const role = ROLE_MENTION[key];+ let alts: string[];+ let flags = 'u';+ if (role) {+ alts = [role];+ flags += 'i';+ } else {+ alts = [escapeRegExp(label)];+ const first = label.split(' ')[0];+ if (label.includes(' ') && first.length >= 3 && !ROLE_ALIASES[first.toLowerCase()]) alts.push(escapeRegExp(first));+ if (label[0] === label[0].toLowerCase()) flags += 'i';+ }+ out.push({ key, label, re: new RegExp(`(?<![\\p{L}\\p{N}_-])(?:${alts.join('|')})(?![\\p{L}\\p{N}_-])`, flags) });+ }+ return out;+}++const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];+const MONTH_ALT = 'jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec';+const MULTIPLIERS: Record<string, number> = { k: 1e3, thousand: 1e3, m: 1e6, mm: 1e6, million: 1e6, b: 1e9, bn: 1e9, billion: 1e9 };++function canonNumber(n: number): string {+ return String(Math.round(n * 1000) / 1000);+}++/**+ * Every number and date a text states, in canonical forms, so "$250K",+ * "$250,000" and "250 thousand" agree, and "2026-03-14" agrees with+ * "March 14th". Keys: plain values ("250000"), percents ("5%"), ISO dates+ * ("date:2026-03-14") and month-day pairs ("md:3-14").+ */+export function numericFacts(text: string): Set<string> {+ const out = new Set<string>();+ const s = normForGrounding(text);+ for (const m of s.matchAll(/(\d[\d,]*(?:\.\d+)?)\s*(k|mm|m|bn|b|thousand|million|billion)?(?![a-z])/g)) {+ const base = Number.parseFloat(m[1].replace(/,/g, ''));+ if (!Number.isFinite(base)) continue;+ out.add(canonNumber(base));+ if (m[2]) out.add(canonNumber(base * MULTIPLIERS[m[2]]));+ }+ for (const m of s.matchAll(/(\d+(?:\.\d+)?)\s*(?:%|percent\b)/g)) out.add(`${canonNumber(Number.parseFloat(m[1]))}%`);+ for (const m of s.matchAll(/\b(\d{4})-(\d{2})-(\d{2})\b/g)) {+ out.add(`date:${m[1]}-${m[2]}-${m[3]}`);+ out.add(`md:${Number(m[2])}-${Number(m[3])}`);+ }+ for (const m of s.matchAll(new RegExp(`\\b(${MONTH_ALT})[a-z]*\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?\\b`, 'g'))) {+ out.add(`md:${MONTHS.indexOf(m[1]) + 1}-${Number(m[2])}`);+ }+ for (const m of s.matchAll(new RegExp(`\\b(\\d{1,2})(?:st|nd|rd|th)?\\s+(?:of\\s+)?(${MONTH_ALT})[a-z]*\\b`, 'g'))) {+ out.add(`md:${MONTHS.indexOf(m[2]) + 1}-${Number(m[1])}`);+ }+ return out;+}++/** Prepare one transcript for verification. */+export function groundSource(path: string, content: string): GroundedSource {+ const { norm, map } = normalizeForGrounding(content);+ const turns = parseSpeakerTurns(content);+ const name = basename(path);+ return {+ path,+ content,+ norm,+ map,+ turns,+ numbers: numericFacts(`${content}\n${name}`),+ nameNorm: normForGrounding(name),+ speakers: speakerMentionPatterns(turns),+ };}/**@@ -284,40 +516,60 @@ export function extractQuoteSpans(body: string): { spans: Array<{ start: number;}export type GroundResult =- | { status: 'exact' }- | { status: 'normalized' | 'near'; replacement: string }- | { status: 'none' };+ | { status: 'exact'; spans: Array<[number, number]> }+ | { status: 'normalized' | 'near'; replacement: string; spans: Array<[number, number]> }+ | { status: 'none'; reason: 'not_found' | 'crosses_speakers' };++const PUNCT_EDGE = /[.,;:!?]/;/**- * Ground one quoted span against the transcript. Returns the verbatim- * transcript slice to substitute when the span is a normalized or near match;- * 'none' when nothing grounds (caller strips the quote marks).+ * Ground one quoted span against a transcript. Returns the verbatim+ * transcript slice to substitute for a normalized or near match, the+ * original-offset spans of the accepted occurrences (for speaker and+ * source-span provenance), or 'none'. A match that spans two speaker turns+ * is never accepted: quoting across a turn boundary puts one speaker's words+ * in another's mouth.*/export function groundQuote(inner: string, t: GroundedTranscript): GroundResult {- if (t.content.includes(inner)) return { status: 'exact' };+ let crossed = false;++ // Rung 1: exact substring.+ const exact: Array<[number, number]> = [];+ for (let at = t.content.indexOf(inner), n = 0; at >= 0 && n < MAX_OCCURRENCES; at = t.content.indexOf(inner, at + 1), n++) {+ if (crossesTurn(t.turns, at, at + inner.length)) crossed = true;+ else exact.push([at, at + inner.length]);+ }+ if (exact.length) return { status: 'exact', spans: exact };const q = normalizeForGrounding(inner);- if (q.norm.length === 0) return { status: 'none' };+ if (q.norm.length === 0) return { status: 'none', reason: 'not_found' };// Rung 2: normalized whole-span match → map back to the original slice.- const pos = t.norm.indexOf(q.norm);- if (pos >= 0) {+ const normalized: Array<[number, number]> = [];+ for (let pos = t.norm.indexOf(q.norm), n = 0; pos >= 0 && n < MAX_OCCURRENCES; pos = t.norm.indexOf(q.norm, pos + 1), n++) {const start = t.map[pos];const endIdx = t.map[pos + q.norm.length - 1];- // Defensive: a map hole or empty slice must never become a "verbatim"- // repair (the desync class the map invariant now prevents; belt+braces).- if (start === undefined || endIdx === undefined) return { status: 'none' };- const replacement = t.content.slice(start, endIdx + 1);- if (replacement.length === 0) return { status: 'none' };- return replacement === inner ? { status: 'exact' } : { status: 'normalized', replacement };+ // Defensive: a map hole must never become a "verbatim" repair.+ if (start === undefined || endIdx === undefined) continue;+ if (crossesTurn(t.turns, start, endIdx + 1)) crossed = true;+ else normalized.push([start, endIdx + 1]);+ }+ if (normalized.length) {+ const [start, end] = normalized[0];+ const replacement = 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 };}// Rung 3: near match. Anchor on word trigrams from the quote; score- // candidate windows by token overlap; accept a single clear winner ≥ floor.- // Hard-bounded: total probes, trigrams (stride-sampled), quote size.- if (q.norm.length > MAX_NEAR_QUOTE_NORM_CHARS) return { status: 'none' };+ // candidate windows (clipped to the anchor's speaker turn) by token+ // overlap; accept a single clear winner ≥ floor, trimmed to the matched+ // tokens. Hard-bounded: total probes, trigrams (stride-sampled), quote size.+ const none: GroundResult = { status: 'none', reason: crossed ? 'crosses_speakers' : 'not_found' };+ if (q.norm.length > MAX_NEAR_QUOTE_NORM_CHARS) return none;const qTokens = q.norm.split(' ').filter(w => w.length > 0);- if (qTokens.length < 4) return { status: 'none' };+ if (qTokens.length < 4) return none;+ const qBare = new Set(qTokens.map(w => w.replace(/[^\p{L}\p{N}]/gu, '')).filter(w => w.length > 0));const triCount = qTokens.length - 2;const stride = Math.max(1, Math.ceil(triCount / MAX_NEAR_TRIGRAMS));const candidates: Array<{ start: number; end: number; score: number }> = [];@@ -331,13 +583,18 @@ export function groundQuote(inner: string, t: GroundedTranscript): GroundResultconst at = t.norm.indexOf(gram, from);if (at < 0) break;from = at + 1;- // Window: extend around the anchor to the quote's normalized length- // (WINDOW_GROWTH) + fixed slack, snapped to word boundaries.+ let lo = 0, hi = t.norm.length;+ if (t.turns?.length) {+ const ti = turnIndexAt(t.turns, t.map[at]);+ if (ti >= 0) lo = normIndexAt(t.map, t.turns[ti].labelEnd);+ if (ti + 1 < t.turns.length) hi = normIndexAt(t.map, t.turns[ti + 1].labelStart);+ if (at < lo) continue;+ }const targetLen = q.norm.length;- let winStart = Math.max(0, at - Math.floor(g / Math.max(1, qTokens.length) * targetLen) - WINDOW_SLACK_BEFORE);- let winEnd = Math.min(t.norm.length, winStart + Math.ceil(targetLen * WINDOW_GROWTH) + WINDOW_SLACK_AFTER);- while (winStart > 0 && t.norm[winStart] !== ' ') winStart--;- while (winEnd < t.norm.length && t.norm[winEnd] !== ' ') winEnd++;+ let winStart = Math.max(lo, at - Math.floor(g / Math.max(1, qTokens.length) * targetLen) - WINDOW_SLACK_BEFORE);+ let winEnd = Math.min(hi, winStart + Math.ceil(targetLen * WINDOW_GROWTH) + WINDOW_SLACK_AFTER);+ while (winStart > lo && t.norm[winStart] !== ' ') winStart--;+ while (winEnd < hi && t.norm[winEnd] !== ' ') winEnd++;if (seenStarts.has(winStart)) continue;seenStarts.add(winStart);const winTokens = t.norm.slice(winStart, winEnd).split(' ').filter(w => w.length > 0);@@ -353,187 +610,474 @@ export function groundQuote(inner: string, t: GroundedTranscript): GroundResult}candidates.sort((a, b) => b.score - a.score);const best = candidates[0];- if (!best || best.score < NEAR_MATCH_FLOOR) return { status: 'none' };+ if (!best || best.score < NEAR_MATCH_FLOOR) return none;const second = candidates.find(c => c.start !== best.start);if (second && best.score - second.score < NEAR_MATCH_AMBIGUITY && second.score >= NEAR_MATCH_FLOOR) {- // Two plausible homes — refusing to guess beats repairing to the wrong- // span (ambiguity falls through to strip).- return { status: 'none' };+ // Two plausible homes — refusing to guess beats repairing to the wrong span.+ return none;}- const oStart = t.map[best.start];- const oEndIdx = t.map[Math.max(best.start, best.end - 1)];- if (oStart === undefined || oEndIdx === undefined) return { status: 'none' };- const replacement = t.content.slice(oStart, oEndIdx + 1).trim();- if (replacement.length === 0) return { status: 'none' };- return { status: 'near', replacement };+ // Trim the window to the first and last tokens the quote shares with it.+ const tokens: Array<{ start: number; end: number }> = [];+ for (const m of t.norm.slice(best.start, best.end).matchAll(/\S+/g)) {+ const bare = m[0].replace(/[^\p{L}\p{N}]/gu, '');+ if (qBare.has(bare)) tokens.push({ start: best.start + (m.index ?? 0), end: best.start + (m.index ?? 0) + m[0].length });+ }+ if (!tokens.length) return none;+ const oFirst = t.map[tokens[0].start];+ const oLast = t.map[tokens[tokens.length - 1].end - 1];+ if (oFirst === undefined || oLast === undefined) return none;+ let a = oFirst, b = oLast + 1;+ const innerTrim = inner.trim();+ if (!PUNCT_EDGE.test(innerTrim[0] ?? '')) while (a < b && PUNCT_EDGE.test(t.content[a])) a++;+ if (!PUNCT_EDGE.test(innerTrim[innerTrim.length - 1] ?? '')) while (b > a && PUNCT_EDGE.test(t.content[b - 1])) b--;+ const replacement = t.content.slice(a, b).trim();+ if (replacement.length === 0) return none;+ if (normForGrounding(replacement).length > Math.ceil(q.norm.length * NEAR_MATCH_MAX_GROWTH)) return none;+ if (crossesTurn(t.turns, a, b)) return { status: 'none', reason: 'crosses_speakers' };+ return { status: 'near', replacement, spans: [[a, b]] };}+const NUMERIC_CLAIM_RES: Array<{ re: RegExp; key: (m: RegExpMatchArray) => string[] }> = [+ // Currency, optionally scaled ($2M, $250,000, $1.5 billion).+ { re: /\$\s?(\d[\d,]*(?:\.\d+)?)\s*(k|mm|m|bn|b|thousand|million|billion)?(?![a-z])/gi,+ key: m => [canonNumber(Number.parseFloat(m[1].replace(/,/g, '')) * (m[2] ? MULTIPLIERS[m[2].toLowerCase()] : 1))] },+ // Scaled plain amounts (3 million users).+ { re: /\b(\d[\d,]*(?:\.\d+)?)\s+(thousand|million|billion)\b/gi,+ key: m => [canonNumber(Number.parseFloat(m[1].replace(/,/g, '')) * MULTIPLIERS[m[2].toLowerCase()])] },+ { re: /\b(\d+(?:\.\d+)?)\s*(?:%|percent\b)/gi, key: m => [`${canonNumber(Number.parseFloat(m[1]))}%`] },+ { re: /\b(\d{4})-(\d{2})-(\d{2})\b/g, key: m => [`date:${m[1]}-${m[2]}-${m[3]}`, `md:${Number(m[2])}-${Number(m[3])}`] },+ { re: new RegExp(`\\b(${MONTH_ALT})[a-z]*\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?\\b`, 'gi'),+ key: m => [`md:${MONTHS.indexOf(m[1].toLowerCase()) + 1}-${Number(m[2])}`] },+ // Thousands-separated or 4+ digit numbers (years, counts, ids).+ { re: /\b\d{1,3}(?:,\d{3})+(?:\.\d+)?\b|\b\d{4,}\b/g, key: m => [canonNumber(Number.parseFloat(m[0].replace(/,/g, '')))] },+];+/**- * F4b (warn-only): count numeric/date claims in the body that do not ground- * in the transcript. Currency, percents, 4+ digit numbers, ISO dates, and- * month-name dates. No repair, no LLM — telemetry a future grounding gate- * (filed TODO E7) can act on. Bounded: first MAX_NUMERIC_CLAIMS_PER_PAGE- * unique claims (a numbers-dense table must not scan the transcript- * thousands of times for warn-only telemetry).+ * 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.*/-export function countUngroundedNumericClaims(body: string, t: GroundedTranscript): number {- // Same mask as quote extraction — wikilinks and link targets included:- // dream pages MUST carry wikilinks, and slugs embed dates/ids- // (`meetings/2026-08-30`, `…-a1b2c3`) that would otherwise register as- // structurally-ungroundable "claims" and inflate the very baseline the- // filed grounding-gate follow-up (E7) would threshold on.- const masked = maskNonProse(body);- const claimRe = /\$[\d,]+(?:\.\d+)?[kmbKMB]?|\b\d+(?:\.\d+)?%|\b\d{4}-\d{2}-\d{2}\b|\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]* \d{1,2}\b|\b\d{4,}\b/gi;- let warns = 0;+export function unsupportedNumericClaims(text: string, sources: GroundedSource[]): string[] {+ const out: string[] = [];const seen = new Set<string>();- for (const m of masked.match(claimRe) ?? []) {- if (seen.size >= MAX_NUMERIC_CLAIMS_PER_PAGE) break;- const claim = normForGrounding(m);- if (claim.length === 0 || seen.has(claim)) continue;- seen.add(claim);- if (!t.norm.includes(claim)) warns++;+ const covered: Array<[number, number]> = [];+ for (const { re, key } of NUMERIC_CLAIM_RES) {+ for (const m of text.matchAll(re)) {+ const at = m.index ?? 0;+ if (covered.some(([s, e]) => at >= s && at < e)) continue;+ covered.push([at, at + m[0].length]);+ const claim = normForGrounding(m[0]);+ if (!claim || seen.has(claim) || seen.size >= MAX_NUMERIC_CLAIMS_PER_PAGE) continue;+ seen.add(claim);+ const keys = key(m);+ const supported = sources.some(src =>+ keys.some(k => src.numbers.has(k)) || src.norm.includes(claim) || src.nameNorm.includes(claim));+ if (!supported) out.push(m[0].trim());+ }}- return warns;+ return out;}-/** Split a serialized page into its frontmatter block and body. */-function splitFrontmatter(md: string): { fm: string; body: string } {- if (md.startsWith('---\n')) {- const end = md.indexOf('\n---\n', 4);- if (end >= 0) return { fm: md.slice(0, end + 5), body: md.slice(end + 5) };- }- return { fm: '', body: md };-}+const LIST_MARKER_RE = /^(?:[-*+]|\d+[.)]|>|#{1,6})[ \t]+/;+const EMPTY_LINE_AFTER_REMOVAL_RE = /^\s*(?:[-*+]|\d+[.)]|>|#{1,6})?\s*$/;+const REMOVED = '\uFFFF';/**- * Repair one page body against its transcript. Pure: returns the repaired- * body + per-ladder counts; the caller decides whether to write back.+ * Claim units: sentences within a line, whole list items, whole table rows.+ * A boundary never falls inside a quoted span, so every quote belongs to+ * exactly one unit. Offsets exclude surrounding whitespace and list markers.*/-export function repairBody(body: string, t: GroundedTranscript): {+export function claimUnits(body: string, spans: Array<{ start: number; end: number }>): Array<{ start: number; end: number }> {+ const inQuote = new Uint8Array(body.length + 1);+ const closeAt = new Set<number>();+ for (const sp of spans) {+ for (let i = sp.start + 1; i < sp.end; i++) inQuote[i] = 1;+ closeAt.add(sp.end);+ }+ const raw: Array<[number, number]> = [];+ let unitStart = 0;+ let lineStart = 0;+ let tableLine = body.trimStart().startsWith('|');+ for (let i = 0; i < body.length; i++) {+ const ch = body[i];+ if (ch === '\n' && !inQuote[i]) {+ raw.push([unitStart, i]);+ unitStart = i + 1;+ lineStart = i + 1;+ tableLine = body.slice(lineStart, lineStart + 200).trimStart().startsWith('|');+ continue;+ }+ if (tableLine || inQuote[i]) continue;+ const next = body[i + 1];+ const atGap = next === undefined || /\s/.test(next);+ if (atGap && (/[.!?]/.test(ch) || (closeAt.has(i) && /[.!?]/.test(body[i - 1] ?? '')))) {+ raw.push([unitStart, i + 1]);+ unitStart = i + 1;+ }+ }+ raw.push([unitStart, body.length]);+ const units: Array<{ start: number; end: number }> = [];+ for (let [s, e] of raw) {+ while (s < e && /\s/.test(body[s])) s++;+ const marker = LIST_MARKER_RE.exec(body.slice(s, Math.min(e, s + 12)));+ if (marker && (s === 0 || body[s - 1] === '\n' || /^[ \t]*$/.test(body.slice(body.lastIndexOf('\n', s - 1) + 1, s)))) s += marker[0].length;+ while (e > s && /\s/.test(body[e - 1])) e--;+ if (e > s) units.push({ start: s, end: e });+ }+ return units;+}++export type ClaimFailure = 'quote_not_in_source' | 'quote_crosses_speakers' | 'speaker_mismatch' | 'number_not_in_source';++export interface QuarantinedClaim {+ text: string;+ reason: ClaimFailure;+ detail: string;+}++export interface QuoteProvenance {+ text: string;+ source: string;+ span: [number, number];+ speaker: string | null;+}++export interface BodyVerification {body: string;changed: boolean;quotes: number;exact: number;normalized: number;near: number;- stripped: number;unbalanced: number;-} {+ quarantined: QuarantinedClaim[];+ provenance: QuoteProvenance[];+ failures: Record<ClaimFailure, number>;+}++function groundAcross(inner: string, sources: GroundedSource[]): { result: Exclude<GroundResult, { status: 'none' }>; source: GroundedSource } | { result: Extract<GroundResult, { status: 'none' }> } {+ const rank = { exact: 3, normalized: 2, near: 1 } as const;+ let best: { result: Exclude<GroundResult, { status: 'none' }>; source: GroundedSource } | null = null;+ let crossed = false;+ for (const source of sources) {+ const g = groundQuote(inner, source);+ if (g.status === 'none') { if (g.reason === 'crosses_speakers') crossed = true; continue; }+ if (!best || rank[g.status] > rank[best.result.status]) best = { result: g, source };+ if (g.status === 'exact') break;+ }+ return best ?? { result: { status: 'none', reason: crossed ? 'crosses_speakers' : 'not_found' } };+}++function blank(s: string, ranges: Array<[number, number]>): string {+ let out = s;+ for (const [a, b] of ranges) out = out.slice(0, a) + ' '.repeat(b - a) + out.slice(b);+ return out;+}++function clip(s: string, n = PROVENANCE_TEXT_CHARS): string {+ const flat = s.replace(/\s+/g, ' ').trim();+ return flat.length > n ? `${flat.slice(0, n - 3)}...` : flat;+}++/**+ * Verify one body (compiled_truth or timeline) against its source+ * transcripts. Pure. With `priorNorm` (the normalized pre-run revision of a+ * page that already existed), only units absent from it are checked; every+ * other unit is left exactly as it was.+ */+export function verifyBody(body: string, sources: GroundedSource[], opts: { priorNorm?: 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 };+ const edits: Array<{ start: number; end: number; text: string }> = [];+ const quarantined: QuarantinedClaim[] = [];+ const provenance: QuoteProvenance[] = [];+ let quotes = 0, exact = 0, normalized = 0, near = 0;++ for (const u of claimUnits(body, spans)) {+ const text = body.slice(u.start, u.end);+ if (opts.priorNorm !== undefined && opts.priorNorm.includes(normForGrounding(text))) continue;+ const unitSpans = spans.filter(sp => sp.start >= u.start && sp.end < u.end);+ const quoteRanges = unitSpans.map(sp => [sp.start - u.start, sp.end - u.start + 1] as [number, number]);+ const attribution = blank(text, quoteRanges);+ const mentioned = new Map<string, string>();+ for (const src of sources) for (const sp of src.speakers) if (sp.re.test(attribution)) mentioned.set(sp.key, sp.label);++ const unitFailures: Array<{ reason: ClaimFailure; detail: string }> = [];+ const fail = (reason: ClaimFailure, detail: string) => { failures[reason]++; unitFailures.push({ reason, detail }); };+ const unitEdits: typeof edits = [];+ const unitProvenance: QuoteProvenance[] = [];+ for (const sp of unitSpans) {+ quotes++;+ const g = groundAcross(sp.inner, sources);+ if (g.result.status === 'none') {+ fail(g.result.reason === 'crosses_speakers' ? 'quote_crosses_speakers' : 'quote_not_in_source', clip(sp.inner));+ continue;+ }+ const { result, source } = g as { result: Exclude<GroundResult, { status: 'none' }>; source: GroundedSource };+ const speakers = result.spans.map(([a]) => speakerAt(source.turns, a)).filter((s): s is string => s !== null);+ if (mentioned.size > 0 && speakers.length > 0 && !speakers.some(s => mentioned.has(speakerKey(s)))) {+ fail('speaker_mismatch', `attributed to ${[...mentioned.values()].join(', ')}; said by ${speakers[0]}: ${clip(sp.inner, 80)}`);+ continue;+ }+ if (result.status === 'exact') exact++;+ else {+ if (result.status === 'normalized') normalized++; else near++;+ // Collapse interior newlines: splicing a transcript line break inside+ // a quoted span would split the markdown paragraph and orphan the marks.+ unitEdits.push({ start: sp.start + 1, end: sp.end, text: result.replacement.replace(/\s*\n\s*/g, ' ') });+ }+ unitProvenance.push({+ text: clip(result.status === 'exact' ? sp.inner : result.replacement),+ source: source.path,+ span: result.spans[0],+ speaker: speakers[0] ?? null,+ });+ }+ const numbers = unsupportedNumericClaims(blank(masked.slice(u.start, u.end), quoteRanges), sources);+ for (const n of numbers) fail('number_not_in_source', n);++ if (unitFailures.length > 0) {+ quarantined.push({ text: clip(text, 2000), reason: unitFailures[0].reason, detail: unitFailures.map(f => f.detail).join('; ') });+ edits.push({ start: u.start, end: u.end, text: REMOVED });+ } else {+ edits.push(...unitEdits);+ provenance.push(...unitProvenance);+ }+ }+let out = body;- let exact = 0, normalized = 0, near = 0, stripped = 0;- // Repair back-to-front so earlier span offsets stay valid.- for (const sp of [...spans].sort((a, b) => b.start - a.start)) {- const g = groundQuote(sp.inner, t);- if (g.status === 'exact') { exact++; continue; }- if (g.status === 'normalized' || g.status === 'near') {- if (g.status === 'normalized') normalized++; else near++;- // Collapse interior newline runs to a single space: the match was found- // under a normalization that folds ALL whitespace, so this is- // equivalent text — but splicing a transcript line break inside a- // quoted span would split the markdown paragraph and leave the opening- // and closing marks in different paragraphs (permanently unverifiable- // on any later pass).- const flat = g.replacement.replace(/\s*\n\s*/g, ' ');- out = out.slice(0, sp.start + 1) + flat + out.slice(sp.end);- continue;+ for (const e of edits.sort((a, b) => b.start - a.start)) out = out.slice(0, e.start) + e.text + out.slice(e.end);+ if (out.includes(REMOVED)) {+ const lines: string[] = [];+ for (const line of out.split('\n')) {+ if (!line.includes(REMOVED)) { lines.push(line); continue; }+ const rest = line.split(REMOVED).join('').replace(/([^ \t])[ \t]{2,}/g, '$1 ').replace(/[ \t]+$/, '');+ if (!EMPTY_LINE_AFTER_REMOVAL_RE.test(rest)) lines.push(rest);}- // Strip: drop the enclosing quote marks, keep the text — an honest- // paraphrase instead of a false verbatim claim. Never delete content.- stripped++;- out = out.slice(0, sp.start) + sp.inner + out.slice(sp.end + 1);+ out = lines.join('\n').replace(/\n{3,}/g, '\n\n').replace(/^\n+/, '').replace(/\n+$/, body.endsWith('\n') ? '\n' : '');}- return { body: out, changed: out !== body, quotes: spans.length, exact, normalized, near, stripped, unbalanced };+ return { body: out, changed: out !== body, quotes, exact, normalized, near, unbalanced, quarantined, provenance, failures };}-export function repairDreamPageMarkdown(md: string, transcript: GroundedTranscript, stats: QuoteVerifyStats): string {- const { fm, body } = splitFrontmatter(md);- const repaired = repairBody(body, transcript);+export interface VerifiablePage {+ compiled_truth: string;+ timeline: string;+ frontmatter: Record<string, unknown>;+}++interface UnverifiedRecord extends QuarantinedClaim { sources: string[]; detected_at: string }++function recordList<T>(fm: Record<string, unknown> | undefined, key: string, pick?: string): T[] {+ const v = pick ? (fm?.[key] as Record<string, unknown> | undefined)?.[pick] : fm?.[key];+ return Array.isArray(v) ? v.filter(x => x && typeof x === 'object') as T[] : [];+}++/**+ * Verify a whole dream page: both bodies, then the frontmatter records.+ * `prior` is the page's pre-run revision when it already existed (only new+ * units are checked, and its records carry forward); null for a page this+ * run created. Quarantined units accumulate in `unverified_claims`; grounded+ * quotes accumulate source-span + speaker provenance in `grounding.quotes`.+ */+export function verifyDreamPage(+ page: VerifiablePage,+ sources: GroundedSource[],+ opts: { prior: VerifiablePage | null; checkedAt: string },+ stats: QuoteVerifyStats,+): VerifiablePage & { changed: boolean } {+ 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 });stats.pages_checked++;- stats.quotes_total += repaired.quotes;- stats.exact += repaired.exact;- stats.normalized_fixed += repaired.normalized;- stats.near_fixed += repaired.near;- stats.stripped += repaired.stripped;- stats.unbalanced += repaired.unbalanced;- stats.numeric_claim_warns += countUngroundedNumericClaims(repaired.body, transcript);- return fm + repaired.body;+ for (const r of [truth, timeline]) {+ stats.quotes_total += r.quotes;+ stats.exact += r.exact;+ stats.normalized_fixed += r.normalized;+ stats.near_fixed += r.near;+ stats.unbalanced += r.unbalanced;+ stats.quarantined_claims += r.quarantined.length;+ for (const k of Object.keys(r.failures) as ClaimFailure[]) stats[k] += r.failures[k];+ }+ const newlyQuarantined = [...truth.quarantined, ...timeline.quarantined];+ if (newlyQuarantined.length > 0) stats.pages_with_quarantine++;++ let compiled = truth.body;+ if (!compiled.trim() && (page.compiled_truth ?? '').trim() && !timeline.body.trim()) compiled = ALL_CLAIMS_QUARANTINED_BODY;++ const sourcePaths = sources.map(s => s.path);+ const unverified = new Map<string, UnverifiedRecord>();+ for (const r of [+ ...recordList<UnverifiedRecord>(opts.prior?.frontmatter, UNVERIFIED_CLAIMS_KEY),+ ...recordList<UnverifiedRecord>(page.frontmatter, UNVERIFIED_CLAIMS_KEY),+ ...newlyQuarantined.map(q => ({ ...q, sources: sourcePaths, detected_at: opts.checkedAt })),+ ]) {+ if (typeof r.text === 'string') unverified.set(normForGrounding(r.text), r);+ }+ const bodyNorm = normForGrounding(`${compiled}\n${timeline.body}`);+ const quotes = new Map<string, QuoteProvenance>();+ for (const q of [...recordList<QuoteProvenance>(opts.prior?.frontmatter, GROUNDING_KEY, 'quotes'), ...truth.provenance, ...timeline.provenance]) {+ if (typeof q.text !== 'string' || !bodyNorm.includes(normForGrounding(q.text.replace(/\.\.\.$/, '')))) continue;+ quotes.set(`${q.source} ${q.span?.[0]} ${q.span?.[1]}`, q);+ }++ const frontmatter: Record<string, unknown> = { ...page.frontmatter };+ if (unverified.size > 0) frontmatter[UNVERIFIED_CLAIMS_KEY] = [...unverified.values()].slice(-MAX_UNVERIFIED_RECORDS);+ if (quotes.size > 0 || unverified.size > 0 || opts.prior?.frontmatter?.[GROUNDING_KEY]) {+ frontmatter[GROUNDING_KEY] = {+ checked_at: opts.checkedAt,+ sources: sourcePaths,+ quotes: [...quotes.values()].slice(-MAX_PROVENANCE_RECORDS),+ };+ } else {+ delete frontmatter[GROUNDING_KEY];+ }+ const changed = compiled !== page.compiled_truth || timeline.body !== (page.timeline ?? '')+ || JSON.stringify(frontmatter) !== JSON.stringify(page.frontmatter);+ return { compiled_truth: compiled, timeline: timeline.body, frontmatter, changed };+}++/** Database clock reading taken before a run's writes; pages created at or+ * after it are the run's own, earlier pages are verified by diff. */+export async function readVerifyEpoch(engine: BrainEngine): Promise<Date> {+ const rows = await engine.executeRaw<{ now: unknown }>('SELECT now() AS now');+ return new Date(rows[0]?.now as string);}/**- * Orchestrator entry: verify/repair every newly-created page from this- * phase's writtenRefs. `transcriptsByPath` maps a transcript filePath →- * its full content + hash6 (the slug-binding suffix). Refs are grouped by- * transcript so each GroundedTranscript (content + norm + offset map, ~10x- * the transcript's bytes) is built once and released before the next —- * resident overhead is bounded to ONE transcript regardless of phase size.+ * Per-transcript write epochs: the earliest creation time of the child jobs+ * that synthesized each transcript. A resumed or coalesced child created in+ * an earlier run keeps its original epoch, so the pages it wrote then still+ * count as its own. Transcripts without a job row fall back to `fallback`.+ */+export async function loadChildWriteEpochs(+ engine: BrainEngine,+ childIds: number[],+ jobRawSource: Map<number, string>,+ fallback: Date,+): Promise<Map<string, Date>> {+ const out = new Map<string, Date>();+ for (const path of jobRawSource.values()) out.set(path, fallback);+ if (!childIds.length) return out;+ const rows = await engine.executeRaw<{ id: number | string; created_at: unknown }>(+ 'SELECT id, created_at FROM minion_jobs WHERE id = ANY($1::int[])', [childIds]);+ for (const row of rows) {+ const path = jobRawSource.get(Number(row.id));+ const at = new Date(row.created_at as string);+ if (!path || Number.isNaN(at.getTime())) continue;+ if (at < (out.get(path) ?? fallback)) out.set(path, at);+ }+ return out;+}++/**+ * The revision of a page as it stood before `since`: the first version+ * snapshot taken at or after `since` (writes snapshot the prior state before+ * overwriting). Null when nothing overwrote the page since then.+ */+export async function loadPreRunRevision(engine: BrainEngine, slug: string, sourceId: string, since: Date): Promise<VerifiablePage | null> {+ const rows = await engine.executeRaw<{ compiled_truth: string; timeline: string | null; frontmatter: unknown }>(+ `SELECT pv.compiled_truth, pv.timeline, pv.frontmatter+ FROM page_versions pv JOIN pages p ON p.id = pv.page_id+ WHERE p.slug = $1 AND p.source_id = $2 AND pv.snapshot_at >= $3::timestamptz+ ORDER BY pv.snapshot_at ASC, pv.id ASC LIMIT 1`,+ [slug, sourceId, since.toISOString()],+ );+ const row = rows[0];+ if (!row) return null;+ const fm = typeof row.frontmatter === 'string' ? JSON.parse(row.frontmatter) : row.frontmatter;+ return { compiled_truth: row.compiled_truth ?? '', timeline: row.timeline ?? '', frontmatter: (fm ?? {}) as Record<string, unknown> };+}++/**+ * The verification scope of one written page: null prior for a page created+ * at or after `since`, the pre-run revision for an older page, or 'unchanged'+ * when an older page has no revision since then.+ */+export async function resolveVerifyPrior(engine: BrainEngine, page: Pick<Page, 'slug' | 'created_at'>, sourceId: string, since: Date): Promise<VerifiablePage | null | 'unchanged'> {+ if (new Date(page.created_at).getTime() >= since.getTime()) return null;+ return (await loadPreRunRevision(engine, page.slug, sourceId, since)) ?? 'unchanged';+}++/**+ * Orchestrator entry: verify every page this phase's children wrote.+ * Sources are the transcripts of every child that wrote the page (a page+ * two transcripts touched is checked against both). A page's epoch is the+ * earliest `sinceByTranscript` entry of its sources, else `since`. Pages+ * created at or after it are verified whole; older pages are verified only+ * on the units their pre-epoch revision lacks. A small LRU keeps+ * resident grounding state bounded to a few transcripts.*/export async function verifyAndRepairDreamPages(engine: BrainEngine,refs: Array<{ slug: string; source_id: string; raw_source?: string }>,transcriptsByPath: Map<string, TranscriptForVerify>,- opts: { signal?: AbortSignal } = {},+ opts: { since: Date; sinceByTranscript?: Map<string, Date>; checkedAt?: string; signal?: AbortSignal },): Promise<QuoteVerifyStats> {const stats = emptyQuoteVerifyStats();- // Dedupe defensively by (source, slug) and group by transcript.- const seen = new Set<string>();- const byTranscript = new Map<string, Array<{ slug: string; source_id: string }>>();+ const checkedAt = opts.checkedAt ?? new Date().toISOString().slice(0, 10);+ const pages = new Map<string, { slug: string; source_id: string; paths: string[] }>();for (const ref of refs) {const key = `${ref.source_id} ${ref.slug}`;- if (seen.has(key)) continue;- seen.add(key);- const t = ref.raw_source ? transcriptsByPath.get(ref.raw_source) : undefined;- if (!t) { stats.skipped_no_transcript++; continue; }- // Scope: only pages this transcript CREATED — the slug carries the- // transcript's hash6 (or hash6-c<idx> for chunked children). A modified- // pre-existing page (people/patterns) may quote OTHER sources; whole-page- // verification against one transcript would strip their valid quotes.- if (!ref.slug.includes(`-${t.hash6}`)) { stats.skipped_preexisting++; continue; }- const group = byTranscript.get(ref.raw_source as string);- if (group) group.push({ slug: ref.slug, source_id: ref.source_id });- else byTranscript.set(ref.raw_source as string, [{ slug: ref.slug, source_id: ref.source_id }]);- }-- for (const [rawSource, group] of byTranscript) {- throwIfAborted(opts.signal, '[dream] quote verify');- const t = transcriptsByPath.get(rawSource)!;- const { norm, map } = normalizeForGrounding(t.content);- const grounded: GroundedTranscript = { content: t.content, norm, map };+ const known = ref.raw_source && transcriptsByPath.has(ref.raw_source) ? ref.raw_source : undefined;+ const entry = pages.get(key) ?? { slug: ref.slug, source_id: ref.source_id, paths: [] };+ if (known && !entry.paths.includes(known)) entry.paths.push(known);+ pages.set(key, entry);+ }+ const cache = new Map<string, GroundedSource>();+ const sourceFor = (path: string): GroundedSource => {+ let g = cache.get(path);+ if (g) { cache.delete(path); cache.set(path, g); return g; }+ g = groundSource(path, transcriptsByPath.get(path)!.content);+ cache.set(path, g);+ if (cache.size > 4) cache.delete(cache.keys().next().value as string);+ return g;+ };- for (const ref of group) {- throwIfAborted(opts.signal, '[dream] quote verify');- try {- const page = await engine.getPage(ref.slug, { sourceId: ref.source_id });- if (!page) { stats.errors++; continue; }+ const ordered = [...pages.values()].sort((a, b) => (a.paths[0] ?? '').localeCompare(b.paths[0] ?? ''));+ for (const ref of ordered) {+ throwIfAborted(opts.signal, '[dream] quote verify');+ if (ref.paths.length === 0) { stats.skipped_no_transcript++; continue; }+ try {+ const page = await engine.getPage(ref.slug, { sourceId: ref.source_id });+ if (!page) { stats.errors++; continue; }+ const since = ref.paths.reduce((min, p) => {+ const at = opts.sinceByTranscript?.get(p);+ return at && at < min ? at : min;+ }, opts.since);+ const prior = await resolveVerifyPrior(engine, page, ref.source_id, since);+ if (prior === 'unchanged') { stats.skipped_unchanged++; continue; }+ if (prior) stats.preexisting_diffed++;+ const verified = verifyDreamPage(page, ref.paths.map(sourceFor), { prior, checkedAt }, stats);+ if (verified.changed) {const tags = await engine.getTags(ref.slug, { sourceId: ref.source_id });- const md = serializePageToMarkdown(page, tags);- const repaired = repairDreamPageMarkdown(md, grounded, stats);- if (repaired !== md) {- // Canonical write pipeline — same as the children's put_page tool:- // page + tags + chunks + link extraction, content_hash recomputed.- // noEmbed: the phase-end embed sweep backfills (oneshot deferEmbeds- // parity). Provenance fields null → engine COALESCE keeps the- // first-write record intact.- await importFromContent(engine, ref.slug, repaired, {- noEmbed: true,- remote: false,- sourceId: ref.source_id,- });- stats.pages_repaired++;- }- } catch (e) {- // Fail-open: a verify bug never kills the phase (pacer precedent) —- // but a cooperative abort must still unwind.- throwIfAborted(opts.signal, '[dream] quote verify');- stats.errors++;- const msg = e instanceof Error ? e.message : String(e);- process.stderr.write(`[dream] quote verify ${ref.slug}@${ref.source_id} failed: ${msg}\n`);+ const next = { ...page, compiled_truth: verified.compiled_truth, timeline: verified.timeline, frontmatter: verified.frontmatter };+ const md = serializePageToMarkdown(next, tags);+ // The children's put_page projected timeline, facts, takes and links+ // from the unverified body; re-project from the verified body in the+ // same transaction so no derived row outlives its quarantined claim.+ const parsed = { type: page.type, title: page.title, compiled_truth: next.compiled_truth, timeline: next.timeline, frontmatter: next.frontmatter, tags };+ const project = prepareCanonicalProjections(parsed, ref.slug, ref.source_id);+ const links = await isAutoLinkEnabled(engine) ? await prepareAutomaticLinks(engine, ref.slug, parsed, ref.source_id) : undefined;+ // noEmbed: the phase-end embed sweep backfills. Provenance fields+ // null → engine COALESCE keeps the first-write record intact.+ await importFromContent(engine, ref.slug, md, {+ noEmbed: true, remote: false, sourceId: ref.source_id,+ beforeCommit: async tx => { await project(tx); await links?.apply(tx); },+ });+ stats.pages_repaired++;}- // Cooperative yield per page: the string passes are synchronous CPU;- // the drain's lock heartbeats need the loop to breathe on big phases.- await new Promise(resolve => setTimeout(resolve, 0));+ } catch (e) {+ // Fail-open: a verify bug never kills the phase — but a cooperative+ // abort must still unwind.+ throwIfAborted(opts.signal, '[dream] quote verify');+ stats.errors++;+ const msg = e instanceof Error ? e.message : String(e);+ process.stderr.write(`[dream] quote verify ${ref.slug}@${ref.source_id} failed: ${msg}\n`);}- // grounded (norm + map) goes out of scope here — one transcript resident.+ // Cooperative yield per page: the string passes are synchronous CPU.+ await new Promise(resolve => setTimeout(resolve, 0));}return stats;}diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex f695e28619..731f0fbfd6 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -85,7 +85,7 @@ import { validateSourceId } from '../utils.ts';import { safeSplitIndex } from '../text-safe.ts';import { PAGE_SLUG_SEG } from '../cjk.ts';import { withChatPhase, estimateChatCostUsd } from '../ai/chat-usage.ts';-import { verifyAndRepairDreamPages, normForGrounding, type QuoteVerifyStats, type TranscriptForVerify } from './synthesize-verify.ts';+import { verifyAndRepairDreamPages, normForGrounding, readVerifyEpoch, loadChildWriteEpochs, type QuoteVerifyStats, type TranscriptForVerify } from './synthesize-verify.ts';import { passesTriageGate, rescueConfigOf, DEFAULT_RESCUE_FLOOR, DEFAULT_RESCUE_MIN_SEGMENTS, DEFAULT_RESCUE_CONTENT_TYPES, DEFAULT_RESCUE_CONFIG, type RescueConfig, type RescueVerdictLike } from './triage-rescue.ts';// Slug grammar from validatePageSlug — shared via PAGE_SLUG_SEG (#738).@@ -630,6 +630,9 @@ async function runPhaseSynthesizeInner(const renewPrivateQueueLease = queue.makeThrottledLeaseRenewer(childQueueName, privateQueueOwnerToken, opts.yieldDuringPhase,);+ // Grounding scope: pages created from here on are this run's own and are+ // verified whole; older pages are verified on their newly written units.+ const verifySince = await readVerifyEpoch(engine);const childIds: number[] = [];/** Map child job_id → chunk metadata for D6 orchestrator-side slug rewrite. */const chunkInfo = new Map<number, { idx: number; hash6: string }>();@@ -1067,24 +1070,26 @@ async function runPhaseSynthesizeInner(let writtenRefs = await collectChildPutPageSlugs(engine, childIds, chunkInfo, cycleSourceId, jobRawSource, jobsWithPages);let finalizedRefs = writtenRefs;- // F1b/F4b: mechanical quote verify/repair on this phase's newly-created- // pages, BEFORE the provenance stamp / reverse-write / embed sweep so the- // stamp, the markdown file, and the embedded chunks all carry the- // repaired body. Fail-open (abort still unwinds); kill switch:- // dream.synthesize.quote_verify=false.+ // Grounding gate: verify every page the children wrote (whole page when+ // created this run, new units only otherwise), BEFORE the provenance+ // stamp / reverse-write / embed sweep, so unsupported claims never reach+ // chunks or the markdown body. Fail-open (abort still unwinds); kill+ // switch: dream.synthesize.quote_verify=false.let quoteVerifyStats: QuoteVerifyStats | null = null;+ const sinceByTranscript = await loadChildWriteEpochs(engine, childIds, jobRawSource, verifySince);if (maintenance) {const processed = await postprocessManagedSynthesis(engine, maintenance, writtenRefs, childIds, jobRawSource,- worthProcessing, { cycleDate: summaryDate, quoteVerify: config.quoteVerify, signal: opts.signal });+ worthProcessing, { cycleDate: summaryDate, quoteVerify: config.quoteVerify, sinceByTranscript, signal: opts.signal });writtenRefs = processed.writtenRefs;finalizedRefs = processed.finalizedRefs;quoteVerifyStats = config.quoteVerify ? processed.stats : null;} else if (config.quoteVerify && writtenRefs.length > 0) {const transcriptsForVerify = new Map<string, TranscriptForVerify>(- worthProcessing.map(t => [t.filePath, { content: t.content, hash6: t.contentHash.slice(0, 6) }]),+ worthProcessing.map(t => [t.filePath, { content: t.content }]),);try {- quoteVerifyStats = await verifyAndRepairDreamPages(engine, writtenRefs, transcriptsForVerify, { signal: opts.signal });+ quoteVerifyStats = await verifyAndRepairDreamPages(engine, writtenRefs, transcriptsForVerify,+ { since: verifySince, sinceByTranscript, checkedAt: summaryDate, signal: opts.signal });} catch (e) {throwIfAborted(opts.signal, '[dream] quote verify');process.stderr.write(`[dream] quote verify pass failed open: ${e instanceof Error ? e.message : String(e)}\n`);diff --git a/src/core/eval/metric-glossary.ts b/src/core/eval/metric-glossary.tsindex 5acf98eb6c..e9586ff373 100644--- a/src/core/eval/metric-glossary.ts+++ b/src/core/eval/metric-glossary.ts@@ -95,13 +95,13 @@ export const METRIC_GLOSSARY: Readonly<Record<string, Readonly<MetricGlossEntry>// Statistical-significance metrics (per-mode comparison)// ────────────────────────────────────────────────────────────────────────'p_value': Object.freeze({- industry_term: 'p-value (paired bootstrap)',- eli10: 'How likely the observed difference between two modes is just noise. Lower = stronger evidence the difference is real. We compute paired bootstrap with 10,000 resamples and Bonferroni correction across the 12 comparisons (3 modes × 4 metrics).',+ industry_term: 'p-value (paired sign-flip randomization test)',+ eli10: 'How likely the observed difference between two runs is just noise. Lower = stronger evidence the difference is real. Computed from per-question rows by randomly flipping which run each question\'s result belongs to, then Holm-corrected across every comparison in the report.',range: '0..1, lower = stronger signal. Below 0.05 is the common "statistically significant" threshold; below 0.01 is strong evidence.',}),'confidence_interval': Object.freeze({industry_term: '95% Confidence Interval (CI)',- eli10: 'The range we\'re 95% sure the true value falls inside, given the sample we measured. Narrower CI = more reliable estimate. Computed via bootstrap resampling.',+ eli10: 'The range we\'re 95% sure the true value falls inside, given the sample we measured. Narrower CI = more reliable estimate. Computed by resampling questions with replacement (paired bootstrap).',range: 'Two-tuple [low, high]. If 0 is inside the CI for a Δ, the difference isn\'t statistically significant.',}),diff --git a/src/core/eval/paired-bootstrap.ts b/src/core/eval/paired-bootstrap.tsnew file mode 100644index 0000000000..4b11eb68be--- /dev/null+++ b/src/core/eval/paired-bootstrap.ts@@ -0,0 +1,123 @@+/**+ * Paired, clustered comparison statistics for per-query eval rows.+ *+ * Ported from the gbrain-evals situation-recall comparator+ * (`eval/runner/situation-recall-regression.ts`: cluster bootstrap,+ * sign-swap randomization test, Holm step-down) so a before/after receipt+ * computed here and one computed there mean the same thing. Differences:+ * this port is mean-aggregation only and its p-value is two-sided (eval+ * compare asks "do these differ?", not "did the candidate improve?").+ *+ * pairs (cluster, baseline, candidate)+ * ├── delta = mean(candidate) − mean(baseline) over all pairs+ * ├── 95% CI = percentile interval of `draws` cluster-bootstrap+ * │ resamples (whole clusters drawn with replacement)+ * └── p_value = sign-flip randomization over clusters: exact+ * enumeration at ≤16 clusters, else `draws` Monte+ * Carlo flips with the (k+1)/(n+1) correction+ *+ * Deterministic: a seeded mulberry32 generator drives every draw.+ */++export interface PairedObservation {+ cluster: string;+ baseline: number;+ candidate: number;+}++export interface PairedStatistics {+ n: number;+ clusters: number;+ baseline_mean: number;+ candidate_mean: number;+ delta: number;+ lower95: number;+ upper95: number;+ p_value: number;+ /** Pairs where the candidate scored higher / lower / the same. */+ wins: number;+ losses: number;+ ties: number;+}++/** mulberry32 — the same generator the gbrain-evals comparator uses. */+export function seededRandom(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state += 0x6D2B79F5;+ let t = state;+ t = Math.imul(t ^ t >>> 15, t | 1);+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);+ return ((t ^ t >>> 14) >>> 0) / 4294967296;+ };+}++export function pairedClusterStatistics(pairs: PairedObservation[], opts: { seed: number; draws: number }): PairedStatistics {+ if (!pairs.length) throw new Error('paired statistics need at least one pair');+ if (!Number.isInteger(opts.draws) || opts.draws < 1000) throw new Error('paired statistics need at least 1000 draws');+ if (!pairs.every(p => Number.isFinite(p.baseline) && Number.isFinite(p.candidate))) throw new Error('paired observations must be finite');++ const n = pairs.length;+ const baselineMean = pairs.reduce((s, p) => s + p.baseline, 0) / n;+ const candidateMean = pairs.reduce((s, p) => s + p.candidate, 0) / n;+ const delta = candidateMean - baselineMean;+ const wins = pairs.filter(p => p.candidate > p.baseline).length;+ const losses = pairs.filter(p => p.candidate < p.baseline).length;+ const byCluster = new Map<string, { sum: number; count: number }>();+ for (const p of pairs) {+ const c = byCluster.get(p.cluster) ?? { sum: 0, count: 0 };+ c.sum += p.candidate - p.baseline;+ c.count++;+ byCluster.set(p.cluster, c);+ }+ const clusters = [...byCluster.keys()].sort().map(k => byCluster.get(k)!);+ const base = { n, clusters: clusters.length, baseline_mean: baselineMean, candidate_mean: candidateMean, delta, wins, losses, ties: n - wins - losses };++ if (wins + losses === 0) return { ...base, lower95: 0, upper95: 0, p_value: 1 };+ if (clusters.length < 2) return { ...base, lower95: -Infinity, upper95: Infinity, p_value: 1 };++ const rng = seededRandom(opts.seed);+ const boot = new Float64Array(opts.draws);+ for (let i = 0; i < opts.draws; i++) {+ let sum = 0, count = 0;+ for (let j = 0; j < clusters.length; j++) {+ const c = clusters[Math.floor(rng() * clusters.length)];+ sum += c.sum;+ count += c.count;+ }+ boot[i] = sum / count;+ }+ boot.sort();++ const exact = clusters.length <= 16;+ const flips = exact ? 2 ** clusters.length : opts.draws;+ const observed = Math.abs(delta) - 1e-12;+ let extreme = 0;+ for (let i = 0; i < flips; i++) {+ let sum = 0;+ for (let j = 0; j < clusters.length; j++) {+ const flip = exact ? ((i >>> j) & 1) === 1 : rng() < 0.5;+ sum += flip ? -clusters[j].sum : clusters[j].sum;+ }+ if (Math.abs(sum / n) >= observed) extreme++;+ }+ return {+ ...base,+ lower95: boot[Math.floor(opts.draws * 0.025)],+ upper95: boot[Math.ceil(opts.draws * 0.975) - 1],+ p_value: exact ? extreme / flips : (extreme + 1) / (flips + 1),+ };+}++/** Holm step-down adjustment across one family of comparisons. */+export function holmAdjusted(pValues: number[]): number[] {+ if (!pValues.every(p => Number.isFinite(p) && p >= 0 && p <= 1)) throw new Error('invalid Holm p-value');+ const order = pValues.map((p, index) => ({ p, index })).sort((a, b) => a.p - b.p);+ const adjusted = new Array<number>(pValues.length);+ let previous = 0;+ order.forEach(({ p, index }, rank) => {+ previous = Math.max(previous, Math.min(1, p * (order.length - rank)));+ adjusted[index] = previous;+ });+ return adjusted;+}diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 1fa25f847c..d8de9be222 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.59.17.0 -->+<!-- gbrain-template-stamp: 0.59.18.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/cycle-repeated-consolidation.test.ts b/test/cycle-repeated-consolidation.test.tsnew file mode 100644index 0000000000..d04b4e2e91--- /dev/null+++ b/test/cycle-repeated-consolidation.test.ts@@ -0,0 +1,32 @@+/**+ * Repeated-consolidation regression pin (gbrain 10x plan, amendment 7).+ *+ * Three real dream cycles on a fixed brain with a scripted model that+ * invents quotes, swaps speakers and invents numbers, including edits into+ * existing pages. See test/helpers/repeated-consolidation.ts for the design+ * and scripts/repeated-consolidation-experiment.ts for the printable run.+ *+ * The fixture was written alongside the checker, so this is a regression pin+ * for the mechanical grounding gate, not an estimate of a real model's+ * hallucination rate. Unquoted inventions (no quote, no number) are not+ * mechanically checkable; their count is pinned so a change in either+ * direction is noticed.+ */+import { describe, test, expect } from 'bun:test';+import { runRepeatedConsolidation } from './helpers/repeated-consolidation.ts';++describe('repeated consolidation: three dream cycles with invented claims', () => {+ test('no checkable invented claim becomes active memory; every source-supported claim survives', async () => {+ const m = await runRepeatedConsolidation();+ for (const c of m.per_cycle) expect(c.statuses).toEqual({ synthesize: 'ok', extract: 'ok', extract_facts: 'ok' });++ expect(m.claims_by_kind).toEqual({ valid: 13, fabricated_quote: 6, speaker_swap: 3, invented_number: 6, unquoted_invention: 2 });+ expect(m.invented_active_by_kind).toEqual({ fabricated_quote: 0, speaker_swap: 0, invented_number: 0, unquoted_invention: 2 });+ expect(m.invented_active_ids.sort()).toEqual(['c1-unq', 'c3-unq']);+ expect(m.wrong_attribution_active).toBe(0);++ expect(m.valid_lost_ids).toEqual([]);+ expect(m.source_supported_retention).toBe(1);+ expect(m.human_line_intact).toBe(true);+ }, 120_000);+});diff --git a/test/cycle-synthesize-verify.test.ts b/test/cycle-synthesize-verify.test.tsindex c88adaa132..d208b72202 100644--- a/test/cycle-synthesize-verify.test.ts+++ b/test/cycle-synthesize-verify.test.ts@@ -1,9 +1,10 @@/*** F1b/F4b — mechanical quote verify/repair on dream pages (eval write-path* fix wave). Pure repair-ladder cases + one PGLite write-back integration- * block. The ladder invariant under test everywhere: NEVER fabricate — every- * replacement is a verbatim transcript slice; ungroundable spans lose their- * quote marks but keep their text.+ * block. The invariants under test everywhere: NEVER fabricate — every+ * replacement is a verbatim transcript slice inside one speaker turn — and+ * NEVER keep an unsupported claim as page text: its unit leaves the body and+ * is recorded in frontmatter `unverified_claims`.*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import {@@ -11,9 +12,11 @@ import {normForGrounding,extractQuoteSpans,groundQuote,- repairBody,- countUngroundedNumericClaims,+ verifyBody,+ groundSource,+ unsupportedNumericClaims,verifyAndRepairDreamPages,+ readVerifyEpoch,} from '../src/core/cycle/synthesize-verify.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { importFromContent } from '../src/core/import-file.ts';@@ -107,7 +110,7 @@ describe('groundQuote — the repair ladder', () => {}});- test('heavy paraphrase (low overlap) → none (caller strips)', () => {+ test('heavy paraphrase (low overlap) → none (caller quarantines)', () => {const g = groundQuote('our fundamental product philosophy centers customer delight above metrics', t);expect(g.status).toBe('none');});@@ -127,16 +130,16 @@ describe('groundQuote — the repair ladder', () => {});});-describe('repairBody', () => {+describe('verifyBody', () => {// The principle sentence carries an INTERIOR em-dash + curly apostrophe —// a page quote written with a hyphen + straight apostrophe is normalized-// equal but not byte-equal, which is exactly the rung-2 case. (Inner text// that is byte-identical is EXACT even when the surrounding quote-mark// style differs — quote fidelity is about the quoted content.)const transcript = 'user: We agreed the launch moves to March 14th because the audit slipped. Also: “the brain mustn’t invent quotes — ever.”';- const t = grounded(transcript);+ const src = groundSource('/t/session.txt', transcript);- test('full ladder: exact kept, normalized repaired to verbatim, ungrounded stripped', () => {+ test('full ladder: exact kept, normalized repaired to verbatim, ungrounded unit quarantined', () => {const body = ['Summary paragraph without quotes.','',@@ -146,62 +149,162 @@ describe('repairBody', () => {'','Invented: "our destiny is to reinvent human memory for all mankind forever."',].join('\n');- const r = repairBody(body, t);+ const r = verifyBody(body, [src]);expect(r.quotes).toBe(3);expect(r.exact).toBe(1); // launch-date quote is verbatim alreadyexpect(r.normalized).toBe(1); // hyphen/apostrophe span repaired to the verbatim original- expect(r.stripped).toBe(1); // invented span loses its marksexpect(r.changed).toBe(true);// Replacement is the verbatim INNER slice (page keeps its own quote marks).expect(r.body).toContain('"the brain mustn’t invent quotes — ever."');- // Stripped span keeps its text, loses the quotation marks.- expect(r.body).toContain('Invented: our destiny is to reinvent human memory for all mankind forever.');- expect(r.body).not.toContain('"our destiny');+ // The ungrounded unit is gone from the body, text and marks alike...+ expect(r.body).not.toContain('our destiny');+ expect(r.body).toBe([+ 'Summary paragraph without quotes.',+ '',+ 'Decision: "We agreed the launch moves to March 14th because the audit slipped."',+ '',+ 'Principle: "the brain mustn’t invent quotes — ever."',+ ].join('\n'));+ // ...and preserved verbatim for review, with the reason.+ expect(r.quarantined).toEqual([{+ text: 'Invented: "our destiny is to reinvent human memory for all mankind forever."',+ reason: 'quote_not_in_source',+ detail: 'our destiny is to reinvent human memory for all mankind forever.',+ }]);+ expect(r.failures.quote_not_in_source).toBe(1);+ // Grounded quotes carry source-span + speaker provenance.+ expect(r.provenance).toHaveLength(2);+ for (const p of r.provenance) {+ expect(p.source).toBe('/t/session.txt');+ expect(p.speaker).toBe('user');+ expect(normForGrounding(transcript.slice(p.span[0], p.span[1]))).toBe(normForGrounding(p.text));+ }});test('clean body → changed=false, byte-identical', () => {const body = 'Decision: "We agreed the launch moves to March 14th because the audit slipped." Done.';- const r = repairBody(body, t);+ const r = verifyBody(body, [src]);expect(r.changed).toBe(false);expect(r.body).toBe(body);expect(r.exact).toBe(1);});++ test('only the failing sentence leaves a multi-sentence line; list items and table rows go whole', () => {+ const body = [+ 'The launch moved. The user said "we will triple revenue by next spring for sure." The audit slipped.',+ '- The user said "we will triple revenue by next spring for sure."',+ '- Kept bullet.',+ '| claim | "we will triple revenue by next spring for sure." |',+ ].join('\n');+ const r = verifyBody(body, [src]);+ expect(r.body).toBe('The launch moved. The audit slipped.\n- Kept bullet.');+ expect(r.quarantined).toHaveLength(3);+ });++ test('prior revision: only units absent from it are verified', () => {+ const prior = 'Alice said "a line quoted from some entirely different source conversation".';+ const body = `${prior}\n\nNew: "a fabricated line the child just added to the page."`;+ const r = verifyBody(body, [src], { priorNorm: normForGrounding(prior) });+ expect(r.body).toBe(prior);+ expect(r.quarantined.map(q => q.reason)).toEqual(['quote_not_in_source']);+ });});-describe('repairBody — replacement hygiene (red-team regression)', () => {+describe('speaker provenance (write-path audit C-6)', () => {+ const transcript = [+ 'user (t1): I think the real insight is that memory systems fail at the',+ 'write path, not the read path — everyone measures retrieval.',+ 'user (t2): We decided to ship the “verify-at-write” pass in Q3, budget $250K.',+ 'assistant (t3): Noted. The team agreed the mechanical checker beats an LLM judge.',+ 'user (t4): Next we discuss hiring',+ ].join('\n');+ const src = groundSource('/t/2026-08-30-session.txt', transcript);++ test('near match is trimmed to the matched tokens inside one turn', () => {+ const g = groundQuote('the team decided the mechanical checker beats an LLM judge', src);+ expect(g.status).toBe('near');+ if (g.status === 'near') expect(g.replacement).toBe('The team agreed the mechanical checker beats an LLM judge');+ });++ test('a quote that spans two speaker turns is refused, never spliced', () => {+ const g = groundQuote('beats an LLM judge. user (t4): Next we discuss hiring', src);+ expect(g).toEqual({ status: 'none', reason: 'crosses_speakers' });+ const r = verifyBody('Summary: "Noted. The team agreed the mechanical checker beats an LLM judge.\nuser (t4): Next we discuss hiring"', [src]);+ expect(r.failures.quote_crosses_speakers + r.failures.quote_not_in_source).toBeGreaterThan(0);+ expect(r.body).not.toContain('Next we discuss hiring');+ });++ test('a real quote attributed to the wrong speaker is quarantined; the right speaker is kept', () => {+ const r = verifyBody([+ 'The user said "The team agreed the mechanical checker beats an LLM judge."',+ 'The assistant said "The team agreed the mechanical checker beats an LLM judge."',+ ].join('\n'), [src]);+ expect(r.body).toBe('The assistant said "The team agreed the mechanical checker beats an LLM judge."');+ expect(r.quarantined).toEqual([expect.objectContaining({ reason: 'speaker_mismatch' })]);+ expect(r.provenance[0].speaker).toBe('assistant');+ });++ test('named speakers: labels that open two or more lines count; prose labels do not', () => {+ const named = groundSource('/t/named.txt', [+ 'Alice-example: we should price per seat, not per usage.',+ 'Bob-example: agreed, and the pilot costs $40K.',+ 'Note: this line is not a speaker.',+ 'Alice-example: then we sign the pilot next week.',+ 'Bob-example: fine.',+ ].join('\n'));+ expect(named.turns.map(t => t.speaker)).toEqual(['Alice-example', 'Bob-example', 'Alice-example', 'Bob-example']);+ const r = verifyBody([+ 'Alice-example proposed "we should price per seat, not per usage."',+ 'Bob-example proposed "we should price per seat, not per usage."',+ 'The pilot costs $40K.',+ 'The pilot costs $45K.',+ ].join('\n'), [named]);+ expect(r.body).toBe('Alice-example proposed "we should price per seat, not per usage."\nThe pilot costs $40K.');+ expect(r.quarantined.map(q => q.reason)).toEqual(['speaker_mismatch', 'number_not_in_source']);+ });+});++describe('verifyBody — replacement hygiene (red-team regression)', () => {test('a multi-line transcript match splices as ONE line (quote marks stay in one paragraph)', () => {const transcript = 'user: We agreed the launch moves\nto March 14th because\nthe audit slipped.';- const t = grounded(transcript);+ const src = groundSource('/t/s.txt', transcript);const body = 'Decision: "We agreed the launch moves to March 14th because the audit slipped."';- const r = repairBody(body, t);+ const r = verifyBody(body, [src]);expect(r.normalized).toBe(1);expect(r.body).not.toContain('\n'); // no line break spliced inside the quoteexpect(r.body).toContain('"We agreed the launch moves to March 14th because the audit slipped."');// Re-verifying the repaired body is stable (the marks still pair).- const again = repairBody(r.body, t);+ const again = verifyBody(r.body, [src]);expect(again.unbalanced).toBe(0);- expect(again.stripped).toBe(0);+ expect(again.quarantined).toHaveLength(0);});});-describe('countUngroundedNumericClaims (F4b, warn-only)', () => {- const t = grounded('user: ARR hit $2M in January 2026, churn 5%, headcount 12.');+describe('numeric grounding', () => {+ const src = groundSource('/t/2026-01-15-board.txt', 'user: ARR hit $2M in January 2026, churn 5%, headcount 12.');test('wikilinks and link targets are masked — dated slugs are not "claims" (red-team regression)', () => {- const body = 'See [[meetings/2026-08-30-board]] and [the note](wiki/personal/reflections/2026-08-31-topic-a1b2c3). ARR reached $2M.';- expect(countUngroundedNumericClaims(body, t)).toBe(0);+ const r = verifyBody('See [[meetings/2026-08-30-board]] and [the note](wiki/personal/reflections/2026-08-31-topic-a1b2c3). ARR reached $2M.', [src]);+ expect(r.quarantined).toHaveLength(0);});- test('grounded claims do not warn; invented ones do; fences skipped; deduped', () => {+ test('grounded claims pass; invented ones are reported once each; fences skipped', () => {const body = ['ARR reached $2M with churn at 5%.', // both grounded'Series B raised $50M at a $900M cap.', // 2 invented- 'Again: $50M.', // dup — counted once+ 'Again: $50M.', // same claim, its own unit'```','$77M inside a fence never counts','```',].join('\n');- expect(countUngroundedNumericClaims(body, t)).toBe(2);+ const r = verifyBody(body, [src]);+ expect(r.quarantined.map(q => q.detail)).toEqual(['$50M; $900M', '$50M']);+ expect(r.body).toBe(['ARR reached $2M with churn at 5%.', '```', '$77M inside a fence never counts', '```'].join('\n'));+ });++ test('values compare canonically: scaled amounts, separators, month-day dates, file-name dates', () => {+ expect(unsupportedNumericClaims('ARR was $2,000,000 and $2 million; the board met on 2026-01-15 and January 15th.', [src])).toEqual([]);+ expect(unsupportedNumericClaims('ARR was $2.5M on 2026-01-16.', [src])).toEqual(['$2.5M', '2026-01-16']);});});@@ -217,13 +320,13 @@ describe('extractQuoteSpans — separator drift (ship-review regression: offsets}});- test('fabricated quote after a long separator is still stripped (the escape this fixes)', () => {- const t = grounded('user: routine chatter only, nothing else was said.');+ test('fabricated quote after a long separator is still caught (the escape this fixes)', () => {+ const src = groundSource('/t/s.txt', 'user: routine chatter only, nothing else was said.');const body = 'Intro.\n\n\nClaim: "we decided to acquire acme-example for nine hundred million."';- const r = repairBody(body, t);+ const r = verifyBody(body, [src]);expect(r.quotes).toBe(1);- expect(r.stripped).toBe(1);- expect(r.body).toContain('Claim: we decided to acquire');+ expect(r.quarantined).toHaveLength(1);+ expect(r.body).toBe('Intro.');});test('interior curly-quoted phrase inside a straight-quoted span pairs per type — outer span extracted whole', () => {@@ -293,33 +396,34 @@ describe('groundQuote — CPU bounds (performance-review regression)', () => {});describe('verifyAndRepairDreamPages — fail-open fault injection', () => {- const T = new Map([['/t/x.md', { content: 'user: something quotable that is long enough to be a span here.', hash6: 'aaaaaa' }]]);+ const T = new Map([['/t/x.md', { content: 'user: something quotable that is long enough to be a span here.' }]]);+ const since = new Date(0);+ const page = (compiled_truth: string) => ({ slug: 'x', compiled_truth, timeline: '', frontmatter: {}, type: 'note', title: 'x', created_at: new Date() });test('page read-back miss → errors++, later refs still processed', async () => {const engine = {- getPage: async (slug: string) => slug.includes('missing') ? null : { compiled_truth: 'Body with "something quotable that is long enough to be a span here." ok', timeline: '', frontmatter: {}, type: 'note', title: 'x' },+ getPage: async (slug: string) => slug.includes('missing') ? null : page('clean body, no quotes at all.'),getTags: async () => [],} as never;const stats = await verifyAndRepairDreamPages(engine, [{ slug: 'wiki/personal/reflections/a-missing-aaaaaa', source_id: 'default', raw_source: '/t/x.md' },{ slug: 'wiki/personal/reflections/b-ok-aaaaaa', source_id: 'default', raw_source: '/t/x.md' },- ], T);+ ], T, { since });expect(stats.errors).toBe(1);expect(stats.pages_checked).toBe(1);- expect(stats.exact).toBe(1); // clean page: nothing repaired, no write-back attempted- expect(stats.pages_repaired).toBe(0);+ expect(stats.pages_repaired).toBe(0); // clean page: nothing to write back});test('engine throw during page processing → errors++, loop continues (fail-open)', async () => {let calls = 0;const engine = {- getPage: async () => { calls++; if (calls === 1) throw new Error('boom'); return { compiled_truth: 'clean body, no quotes at all.', timeline: '', frontmatter: {}, type: 'note', title: 'x' }; },+ getPage: async () => { calls++; if (calls === 1) throw new Error('boom'); return page('clean body, no quotes at all.'); },getTags: async () => [],} as never;const stats = await verifyAndRepairDreamPages(engine, [{ slug: 'wiki/personal/reflections/a-throw-aaaaaa', source_id: 'default', raw_source: '/t/x.md' },{ slug: 'wiki/personal/reflections/b-fine-aaaaaa', source_id: 'default', raw_source: '/t/x.md' },- ], T);+ ], T, { since });expect(stats.errors).toBe(1);expect(stats.pages_checked).toBe(1);});@@ -330,7 +434,7 @@ describe('verifyAndRepairDreamPages — fail-open fault injection', () => {const engine = { getPage: async () => null, getTags: async () => [] } as never;await expect(verifyAndRepairDreamPages(engine, [{ slug: 'wiki/personal/reflections/a-aaaaaa', source_id: 'default', raw_source: '/t/x.md' },- ], T, { signal: ac.signal })).rejects.toThrow();+ ], T, { since, signal: ac.signal })).rejects.toThrow();});});@@ -345,53 +449,64 @@ describe('verifyAndRepairDreamPages — PGLite write-back integration', () => {try { await engine.disconnect(); } catch { /* best-effort */ }});- test('repairs the DB page via the canonical pipeline; scopes to hash-suffixed slugs; fail-open counters', async () => {- {- const transcript = 'user: The verdict was “ship the repair pass now — measure later.” That is the whole plan.';- const hash6 = 'abc123';- const slug = `wiki/personal/reflections/2026-08-31-repair-pass-${hash6}`;- const pageMd = [- '---',- 'type: note',- '---',- 'The user concluded: "ship the repair pass now - measure later." Strong conviction.',- '',- 'Fabricated: "we will rewrite the entire engine in Rust next week for fun."',- ].join('\n');- await importFromContent(engine, slug, pageMd, { noEmbed: true, remote: false, sourceId: 'default' });- // A pre-existing people page the child touched — slug carries NO hash- // suffix → must be skipped, never rewritten.- await importFromContent(engine, 'wiki/people/alice-example', '---\ntype: person\n---\nAlice said "something from an entirely different source conversation".', { noEmbed: true, remote: false, sourceId: 'default' });-- const stats = await verifyAndRepairDreamPages(- engine,- [- { slug, source_id: 'default', raw_source: '/t/session.md' },- { slug: 'wiki/people/alice-example', source_id: 'default', raw_source: '/t/session.md' },- { slug: 'wiki/personal/reflections/orphan-def456', source_id: 'default' }, // no raw_source- ],- new Map([['/t/session.md', { content: transcript, hash6 }]]),- );-- expect(stats.pages_checked).toBe(1);- expect(stats.pages_repaired).toBe(1);- expect(stats.quotes_total).toBe(2);- expect(stats.normalized_fixed).toBe(1); // straight → verbatim curly original- expect(stats.stripped).toBe(1); // fabricated quote unquoted- expect(stats.skipped_preexisting).toBe(1);- expect(stats.skipped_no_transcript).toBe(1);- expect(stats.errors).toBe(0);-- const page = await engine.getPage(slug, { sourceId: 'default' });- expect(page).not.toBeNull();- const bodyText = `${page?.compiled_truth ?? ''}\n${page?.timeline ?? ''}`;- // Replacement is the verbatim inner slice; the page keeps its own marks.- expect(bodyText).toContain('"ship the repair pass now — measure later."');- expect(bodyText).toContain('Fabricated: we will rewrite the entire engine in Rust next week for fun.');- expect(bodyText).not.toContain('"we will rewrite');- // Untouched pre-existing page keeps its quote verbatim.- const alice = await engine.getPage('wiki/people/alice-example', { sourceId: 'default' });- expect(`${alice?.compiled_truth ?? ''}`).toContain('"something from an entirely different source conversation"');- }+ test('new pages verified whole; pre-existing pages verified on their new units only; records land in frontmatter', async () => {+ const transcript = 'user: The verdict was “ship the repair pass now — measure later.” That is the whole plan.';+ const OTHER_SOURCE = 'Alice said "something from an entirely different source conversation".';+ // Pre-existing people page, written BEFORE the run's epoch.+ await importFromContent(engine, 'wiki/people/alice-example', `---\ntype: person\n---\n${OTHER_SOURCE}`, { noEmbed: true, remote: false, sourceId: 'default' });+ await new Promise(r => setTimeout(r, 5));+ const since = await readVerifyEpoch(engine);++ // The run: a new hash-suffixed page, a new page WITHOUT a hash suffix+ // (was skipped before this fix), and an edit to the pre-existing page.+ const slug = 'wiki/personal/reflections/2026-08-31-repair-pass-abc123';+ await importFromContent(engine, slug, [+ '---', 'type: note', '---',+ 'The user concluded: "ship the repair pass now - measure later." Strong conviction.',+ '',+ 'Fabricated: "we will rewrite the entire engine in Rust next week for fun."',+ ].join('\n'), { noEmbed: true, remote: false, sourceId: 'default' });+ await importFromContent(engine, 'wiki/people/bob-example', '---\ntype: person\n---\nBob-example said "we are closing a $5M round next month, guaranteed".', { noEmbed: true, remote: false, sourceId: 'default' });+ await importFromContent(engine, 'wiki/people/alice-example', `---\ntype: person\n---\n${OTHER_SOURCE}\n\nThe user said "ship the repair pass now — measure later."\n\nThe user also said "we are shutting down the company next quarter".`, { noEmbed: true, remote: false, sourceId: 'default' });++ const stats = await verifyAndRepairDreamPages(engine, [+ { slug, source_id: 'default', raw_source: '/t/session.md' },+ { slug: 'wiki/people/bob-example', source_id: 'default', raw_source: '/t/session.md' },+ { slug: 'wiki/people/alice-example', source_id: 'default', raw_source: '/t/session.md' },+ { slug: 'wiki/personal/reflections/orphan-def456', source_id: 'default' }, // no raw_source+ ], new Map([['/t/session.md', { content: transcript }]]), { since, checkedAt: '2026-08-31' });++ expect(stats.pages_checked).toBe(3);+ expect(stats.preexisting_diffed).toBe(1);+ expect(stats.skipped_no_transcript).toBe(1);+ expect(stats.normalized_fixed).toBe(1); // straight → verbatim curly original+ expect(stats.quarantined_claims).toBe(3); // one per page+ expect(stats.pages_with_quarantine).toBe(3);+ expect(stats.errors).toBe(0);++ const page = await engine.getPage(slug, { sourceId: 'default' });+ expect(page!.compiled_truth).toBe('The user concluded: "ship the repair pass now — measure later." Strong conviction.');+ expect((page!.frontmatter.unverified_claims as Array<{ text: string; reason: string; sources: string[] }>)).toEqual([+ expect.objectContaining({ text: 'Fabricated: "we will rewrite the entire engine in Rust next week for fun."', reason: 'quote_not_in_source', sources: ['/t/session.md'] }),+ ]);+ const grounding = page!.frontmatter.grounding as { sources: string[]; quotes: Array<{ speaker: string; span: [number, number] }> };+ expect(grounding.sources).toEqual(['/t/session.md']);+ expect(grounding.quotes).toHaveLength(1);+ expect(grounding.quotes[0].speaker).toBe('user');+ expect(transcript.slice(...grounding.quotes[0].span)).toBe('ship the repair pass now — measure later.');++ // New page without a hash suffix: verified whole; the only unit fails.+ const bob = await engine.getPage('wiki/people/bob-example', { sourceId: 'default' });+ expect(bob!.compiled_truth).not.toContain('$5M');++ // Pre-existing page: the other-source quote is untouched, the grounded+ // new quote is kept, the fabricated new quote is quarantined.+ const alice = await engine.getPage('wiki/people/alice-example', { sourceId: 'default' });+ expect(alice!.compiled_truth).toBe(`${OTHER_SOURCE}\n\nThe user said "ship the repair pass now — measure later."`);+ expect((alice!.frontmatter.unverified_claims as unknown[])).toHaveLength(1);++ // Quarantined text has no chunks: keyword search cannot reach it.+ const hits = await engine.searchKeyword('rewrite entire engine Rust', { limit: 5 });+ expect(hits.filter(h => h.slug === slug)).toHaveLength(0);}, 60_000);});diff --git a/test/cycle-write-path-mini-eval.test.ts b/test/cycle-write-path-mini-eval.test.tsindex 8bac8ef2cb..8348dc1855 100644--- a/test/cycle-write-path-mini-eval.test.ts+++ b/test/cycle-write-path-mini-eval.test.ts@@ -87,7 +87,8 @@ const FIXTURES: MiniFixture[] = [// - an EXACT quote (survives untouched),// - a normalized-drift quote (straight apostrophe + hyphen where the// transcript has none → actually: whitespace drift) → repaired verbatim,-// - a FABRICATED quote → stripped (text kept, marks removed),+// - a FABRICATED quote → its unit is quarantined (out of the body, kept in+// frontmatter `unverified_claims`),// plus every expected salient unit as plain prose (the presence canary).const FABRICATED = 'we should rewrite the entire product in a weekend, obviously';@@ -198,7 +199,7 @@ describe('F-Eval: hermetic write-path mini-eval (real phase, scripted transport)verdicts: Array<{ filePath: string; worth: boolean; rescued?: boolean; score: number | null }>;triage: { rescue_fired: number; rescue_checked: number; below_threshold: number; tokens_in: number };synthesis: {- quote_verify: { pages_checked: number; quotes_total: number; exact: number; normalized_fixed: number; near_fixed: number; stripped: number; pages_repaired: number; errors: number } | null;+ quote_verify: { pages_checked: number; quotes_total: number; exact: number; normalized_fixed: number; near_fixed: number; quarantined_claims: number; quote_not_in_source: number; pages_repaired: number; errors: number } | null;spend: { cost_basis: string; children: { tokens_in: number }; triage: { tokens_in: number } };children_zero_pages: number;};@@ -216,13 +217,14 @@ describe('F-Eval: hermetic write-path mini-eval (real phase, scripted transport)expect(details.triage.below_threshold).toBe(1); // routine only — rescued is NOT below-thresholdexpect(details.pages_written).toBe(2);- // ── Repair ladder on the REAL written pages (per page: 1 exact, 1 repaired, 1 stripped).+ // ── Repair ladder on the REAL written pages (per page: 1 exact, 1 repaired, 1 quarantined).const qv = details.synthesis.quote_verify!;expect(qv.pages_checked).toBe(2);expect(qv.errors).toBe(0);expect(qv.exact).toBe(2);expect(qv.normalized_fixed).toBe(2);- expect(qv.stripped).toBe(2);+ expect(qv.quote_not_in_source).toBe(2);+ expect(qv.quarantined_claims).toBe(2);expect(qv.pages_repaired).toBe(2);// ── Salient-unit presence canary: every expected unit, normalized, in a written page body.@@ -246,8 +248,16 @@ describe('F-Eval: hermetic write-path mini-eval (real phase, scripted transport)const mdPaths = details.written_slugs.map(s => join(brainDir, `${s}.md`));for (const p of mdPaths) expect(existsSync(p)).toBe(true);const mdAll = mdPaths.map(p => readFileSync(p, 'utf8')).join('\n');- expect(normForGrounding(mdAll)).toContain(normForGrounding(FABRICATED));- expect(mdAll).not.toContain(`"${FABRICATED}"`); // stripped, not quoted+ // The fabricated quote is out of every page body (no chunks, no+ // search) and preserved for review in frontmatter.+ for (const slug of details.written_slugs) {+ const page = await engine.getPage(slug, { sourceId: 'default' });+ expect(normForGrounding(`${page!.compiled_truth}\n${page!.timeline}`)).not.toContain(normForGrounding(FABRICATED));+ const records = page!.frontmatter.unverified_claims as Array<{ text: string; reason: string }>;+ expect(records.map(r => r.reason)).toEqual(['quote_not_in_source']);+ expect(records[0].text).toContain(FABRICATED);+ }+ expect(mdAll).toContain('unverified_claims:');// The drifted quote was repaired to a verbatim transcript slice.expect(normForGrounding(mdAll)).toContain(normForGrounding('rewrite renewal emails as value receipts sixty days before the invoice'));diff --git a/test/eval-compare.test.ts b/test/eval-compare.test.tsindex 1fcaa7184b..1a0d6c8b27 100644--- a/test/eval-compare.test.ts+++ b/test/eval-compare.test.ts@@ -1,12 +1,14 @@/*** v0.32.3 — eval-compare report tests.- * Pins the markdown + JSON shape and the metric-glossary integration.+ * Pins the markdown + JSON shape, the metric-glossary integration, and the+ * paired statistics computed from per-query rows (aggregate-only runs must+ * say so and compute nothing).*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';-import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { runEvalCompare } from '../src/commands/eval-compare.ts';+import { pathWithinRoot, runEvalCompare } from '../src/commands/eval-compare.ts';let tmp: string;@@ -90,7 +92,11 @@ describe('runEvalCompare', () => {expect(report.grouped.longmemeval.tokenmax.metrics['ndcg@10']).toBe(0.762);expect(report._meta.metric_glossary['recall@10']).toBeDefined();expect(report._meta.metric_glossary['ndcg@10']).toBeDefined();- expect(report._meta.methodology).toContain('bootstrap');+ // No per-query rows: nothing statistical is computed, and it says so.+ expect(report.paired).toEqual([]);+ expect(report._meta.methodology).toStartWith('Aggregate-only');+ expect(report._meta.methodology).not.toContain('Bonferroni');+ expect(report.paired_unavailable.map((u: { run_id: string }) => u.run_id).sort()).toEqual(SAMPLE_RECORDS.map(r => r.run_id).sort());});test('--md output names every mode + metric', async () => {@@ -132,4 +138,139 @@ describe('runEvalCompare', () => {const report = JSON.parse(out);expect(report.grouped.longmemeval.conservative.metrics['recall@10']).toBe(0.9);});++ test('--md output labels an aggregate-only report', async () => {+ const path = writeJsonl(SAMPLE_RECORDS);+ const out = await captureRun(() => runEvalCompare(['--md', '--input', path]));+ expect(out).toContain('## Paired comparisons');+ expect(out).toContain('Aggregate-only: no per-query rows');+ expect(out).not.toContain('| Suite | Baseline');+ });+});++// Per-query fixtures: 40 questions. The candidate fixes 12 baseline misses+// and breaks 2 baseline hits on recall_all; recall_any is identical.+function perQueryFile(name: string, hits: (i: number) => boolean): string {+ const path = join(tmp, name);+ const rows = Array.from({ length: 40 }, (_, i) => ({+ question_id: `q${String(i).padStart(2, '0')}`,+ recall_all_hit: hits(i),+ recall_any_hit: true,+ }));+ writeFileSync(path, [...rows.map(r => JSON.stringify(r)), JSON.stringify({ kind: 'by_type_summary' })].join('\n') + '\n', 'utf-8');+ return path;+}++describe('runEvalCompare — paired statistics from per-query rows', () => {+ // Per-query files must live under the repository root; outside a git+ // checkout the root is the working directory, so run from the tmp dir.+ let cwd: string;+ beforeAll(() => { cwd = process.cwd(); process.chdir(tmp); });+ afterAll(() => { process.chdir(cwd); });++ const baseHit = (i: number) => i < 20; // 20/40+ const candHit = (i: number) => (i < 20 && i !== 0 && i !== 1) || (i >= 20 && i < 32); // 18 kept + 12 fixed = 30/40+ const records = () => [+ { ...SAMPLE_RECORDS[0], run_id: 'base-run', mode: 'balanced', params: { output: perQueryFile('base.jsonl', baseHit) } },+ { ...SAMPLE_RECORDS[1], run_id: 'cand-run', mode: 'balanced', ran_at: '2026-05-13T10:00:00Z', params: { output: perQueryFile('cand.jsonl', candHit) } },+ ];++ test('--baseline/--candidate computes a paired bootstrap over the joined questions', async () => {+ const path = writeJsonl(records());+ const out = await captureRun(() => runEvalCompare(['--json', '--input', path, '--baseline', 'base-run', '--candidate', 'cand-run']));+ const report = JSON.parse(out);+ const all = report.paired.find((c: { metric: string }) => c.metric === 'recall_all@k');+ expect(all).toMatchObject({ n: 40, clusters: 40, wins: 12, losses: 2, ties: 26, baseline_mean: 0.5, candidate_mean: 0.75 });+ expect(all.delta).toBeCloseTo(0.25, 10);+ expect(all.ci95[0]).toBeGreaterThan(0);+ expect(all.ci95[1]).toBeLessThan(0.5);+ // Sign-flip over questions is the sign test on the 14 discordant pairs:+ // exact two-sided p = 2 * (1 + 14 + 91) / 2^14 = 0.01294 (Monte Carlo here).+ expect(all.p_value).toBeGreaterThan(0.008);+ expect(all.p_value).toBeLessThan(0.02);+ const any = report.paired.find((c: { metric: string }) => c.metric === 'recall_any@k');+ expect(any).toMatchObject({ delta: 0, p_value: 1, ci95: [0, 0], significant: false });+ // Holm across the two-comparison family.+ expect(all.holm_p_value).toBeCloseTo(Math.min(1, all.p_value * 2), 10);+ expect(all.significant).toBe(true);+ expect(report._meta.methodology).toContain('Paired cluster bootstrap');+ expect(report._meta.methodology).toContain('Holm correction across the 2 comparison(s)');+ });++ test('deterministic: the same seed reproduces the same numbers; the seed is honored', async () => {+ const path = writeJsonl(records());+ const args = ['--json', '--input', path, '--baseline', 'base-run', '--candidate', 'cand-run'];+ const a = JSON.parse(await captureRun(() => runEvalCompare(args))).paired;+ const b = JSON.parse(await captureRun(() => runEvalCompare(args))).paired;+ const c = JSON.parse(await captureRun(() => runEvalCompare([...args, '--seed', '7']))).paired;+ expect(a).toEqual(b);+ expect(c[0].ci95).not.toEqual(a[0].ci95);+ });++ test('mode pairs compare automatically; --md renders the table with a verdict', async () => {+ const path = writeJsonl([+ { ...records()[0], mode: 'conservative' },+ { ...records()[1], mode: 'tokenmax' },+ ]);+ const out = await captureRun(() => runEvalCompare(['--md', '--input', path]));+ expect(out).toContain('| longmemeval | `base-run` (conservative) → `cand-run` (tokenmax) | recall_all@k | 40 (40) |');+ expect(out).toContain('| significant |');+ expect(out).toContain('| not significant |');+ });++ test('a run whose per-query file is missing is listed, not silently skipped', async () => {+ const path = writeJsonl([records()[0], { ...records()[1], params: { output: join(tmp, 'gone.jsonl') } }]);+ const report = JSON.parse(await captureRun(() => runEvalCompare(['--json', '--input', path, '--baseline', 'base-run', '--candidate', 'cand-run'])));+ expect(report.paired).toEqual([]);+ expect(report.paired_unavailable).toEqual([{ run_id: 'cand-run', reason: expect.stringContaining('not found') }]);+ expect(report._meta.methodology).toStartWith('Aggregate-only');+ });});++describe('per-query paths stay inside the repository root', () => {+ test('pathWithinRoot refuses .., outside absolute paths and escaping symlinks', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-eval-root-'));+ const outside = mkdtempSync(join(tmpdir(), 'gbrain-eval-outside-'));+ try {+ mkdirSync(join(root, 'runs'));+ writeFileSync(join(root, 'runs', 'a.jsonl'), '{}\n');+ writeFileSync(join(outside, 'secret.jsonl'), '{}\n');+ symlinkSync(join(outside, 'secret.jsonl'), join(root, 'runs', 'link.jsonl'));+ expect(pathWithinRoot(root, 'runs/a.jsonl')).toEndWith(join('runs', 'a.jsonl'));+ expect(pathWithinRoot(root, join(root, 'runs', 'a.jsonl'))).toEndWith(join('runs', 'a.jsonl'));+ expect(pathWithinRoot(root, 'runs/../runs/missing.jsonl')).toEndWith(join('runs', 'missing.jsonl'));+ expect(pathWithinRoot(root, '../outside.jsonl')).toBeNull();+ expect(pathWithinRoot(root, 'runs/../../x.jsonl')).toBeNull();+ expect(pathWithinRoot(root, join(outside, 'secret.jsonl'))).toBeNull();+ expect(pathWithinRoot(root, 'runs/link.jsonl')).toBeNull();+ expect(pathWithinRoot(root, '.')).toBeNull();+ } finally {+ rmSync(root, { recursive: true, force: true });+ rmSync(outside, { recursive: true, force: true });+ }+ });++ test('a ledger record pointing outside the root is refused with a clear reason and never read', async () => {+ const outside = mkdtempSync(join(tmpdir(), 'gbrain-eval-outside-'));+ const cwd = process.cwd();+ process.chdir(tmp);+ try {+ const escaping = join(outside, 'rows.jsonl');+ writeFileSync(escaping, JSON.stringify({ question_id: 'q1', recall_all_hit: true }) + '\n');+ const path = writeJsonl([+ { ...SAMPLE_RECORDS[0], run_id: 'b', params: { output: escaping } },+ { ...SAMPLE_RECORDS[1], run_id: 'c', params: { output: '../../etc/passwd' } },+ ]);+ const report = JSON.parse(await captureRun(() => runEvalCompare(['--json', '--input', path, '--baseline', 'b', '--candidate', 'c'])));+ expect(report.paired).toEqual([]);+ expect(report.paired_unavailable).toEqual([+ { run_id: 'b', reason: expect.stringContaining('refused per-query file outside the repository root') },+ { run_id: 'c', reason: expect.stringContaining('refused per-query file outside the repository root') },+ ]);+ } finally {+ process.chdir(cwd);+ rmSync(outside, { recursive: true, force: true });+ }+ });+});+diff --git a/test/eval-paired-bootstrap.test.ts b/test/eval-paired-bootstrap.test.tsnew file mode 100644index 0000000000..b720ead696--- /dev/null+++ b/test/eval-paired-bootstrap.test.ts@@ -0,0 +1,56 @@+/**+ * Paired cluster statistics (src/core/eval/paired-bootstrap.ts): the port of+ * the gbrain-evals situation-recall comparator used by `gbrain eval compare`.+ */+import { describe, expect, test } from 'bun:test';+import { holmAdjusted, pairedClusterStatistics } from '../src/core/eval/paired-bootstrap.ts';++const opts = { seed: 42, draws: 10_000 };++describe('pairedClusterStatistics', () => {+ test('exact sign-flip enumeration at 16 or fewer clusters', () => {+ // Five questions, all improved: the two all-same-sign flips out of 2^5+ // are as extreme as observed (two-sided) → p = 2/32.+ const pairs = Array.from({ length: 5 }, (_, i) => ({ cluster: `q${i}`, baseline: 0, candidate: 1 }));+ const st = pairedClusterStatistics(pairs, opts);+ expect(st.p_value).toBe(2 / 32);+ expect(st).toMatchObject({ n: 5, clusters: 5, wins: 5, losses: 0, ties: 0, delta: 1, lower95: 1, upper95: 1 });+ });++ test('no discordant pairs → zero delta, degenerate interval, p = 1', () => {+ const st = pairedClusterStatistics([{ cluster: 'a', baseline: 1, candidate: 1 }, { cluster: 'b', baseline: 0, candidate: 0 }], opts);+ expect(st).toMatchObject({ delta: 0, lower95: 0, upper95: 0, p_value: 1, ties: 2 });+ });++ test('clusters resample whole: rows sharing a cluster move together', () => {+ // One cluster of 10 improvements and 10 singleton ties. Clustered, the+ // 11 clusters give a much wider interval than 20 independent rows would.+ const clustered = [+ ...Array.from({ length: 10 }, () => ({ cluster: 'big', baseline: 0, candidate: 1 })),+ ...Array.from({ length: 10 }, (_, i) => ({ cluster: `t${i}`, baseline: 1, candidate: 1 })),+ ];+ const independent = clustered.map((p, i) => ({ ...p, cluster: `r${i}` }));+ const a = pairedClusterStatistics(clustered, opts);+ const b = pairedClusterStatistics(independent, opts);+ expect(a.clusters).toBe(11);+ expect(a.delta).toBeCloseTo(0.5, 10);+ expect(a.upper95 - a.lower95).toBeGreaterThan(b.upper95 - b.lower95);+ // Exact enumeration over 11 clusters: only the one non-zero cluster+ // matters, so half the flips are as extreme → p = 1.+ expect(a.p_value).toBe(1);+ });++ test('rejects too few draws and non-finite values', () => {+ expect(() => pairedClusterStatistics([{ cluster: 'a', baseline: 0, candidate: 1 }], { seed: 1, draws: 10 })).toThrow();+ expect(() => pairedClusterStatistics([{ cluster: 'a', baseline: Number.NaN, candidate: 1 }], opts)).toThrow();+ expect(() => pairedClusterStatistics([], opts)).toThrow();+ });+});++describe('holmAdjusted', () => {+ test('step-down with monotone enforcement', () => {+ expect(holmAdjusted([0.01, 0.04, 0.03])).toEqual([0.03, 0.06, 0.06]);+ expect(holmAdjusted([0.5])).toEqual([0.5]);+ expect(holmAdjusted([0.2, 0.9])).toEqual([0.4, 0.9]);+ });+});diff --git a/test/helpers/repeated-consolidation.ts b/test/helpers/repeated-consolidation.tsnew file mode 100644index 0000000000..c9147bd9fd--- /dev/null+++ b/test/helpers/repeated-consolidation.ts@@ -0,0 +1,357 @@+/**+ * Hermetic repeated-consolidation experiment (gbrain 10x plan, amendment 7).+ *+ * Runs the real dream cycle (`synthesize` → `extract` → `extract_facts`+ * through `runCycle`) three times on a fixed PGLite brain. Each cycle adds+ * one fixed transcript to the session corpus. The ONLY stub is the gateway+ * chat transport, which serves a scripted triage judge and a scripted+ * synthesis child (agentic mode through the gateway tool loop, the one+ * production mode whose children may write into existing pages) whose pages+ * mix source-supported claims with labelled defects:+ *+ * - fabricated quote a quotation nobody said+ * - speaker swap a real quotation attributed to the other speaker+ * - invented number a figure the transcript never states+ * - unquoted invention a plain-prose claim with no quote or number+ * (not mechanically checkable; measured to show+ * the limit honestly)+ *+ * Cycles 2 and 3 also consolidate into existing pages: the child rewrites the+ * cycle-1 reflection page (keeping it, adding new claims, and re-emitting the+ * cycle-1 fabricated quote) and appends to a human-authored+ * `wiki/people/alice-example` page.+ *+ * "Active memory" is what authoritative recall reads: the compiled_truth and+ * timeline text of live pages (the text that is chunked and searched),+ * timeline_entries rows, and facts rows. Frontmatter is excluded: it is not+ * chunked, embedded, or searched.+ *+ * No network and no paid calls. Placeholder names only.+ */+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { runCycle } from '../../src/core/cycle.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { normForGrounding } from '../../src/core/cycle/synthesize-verify.ts';+import { __setChatTransportForTests, resetGateway, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';+import { withEnv } from './with-env.ts';++export type ClaimKind = 'valid' | 'fabricated_quote' | 'speaker_swap' | 'invented_number' | 'unquoted_invention';++export interface ScriptedClaim {+ id: string;+ kind: ClaimKind;+ /** The exact line the scripted child writes. */+ text: string;+}++const PAD_LINES = [+ 'Alice-example: let me check the build status.',+ 'Bob-example: green on main.',+];+const pad = (n: number) => Array.from({ length: n }, () => PAD_LINES.join('\n')).join('\n');++interface CycleFixture {+ basename: string;+ transcript: string;+ /** Claims written to this cycle's NEW reflection page. */+ newPage: ScriptedClaim[];+ /** Claims appended to the cycle-1 reflection page (cycles 2 and 3). */+ consolidate: ScriptedClaim[];+ /** Claims appended to the human-authored person page. */+ personPage: ScriptedClaim[];+ /** Timeline lines written to this cycle's new page. */+ timeline: ScriptedClaim[];+}++export const CYCLES: CycleFixture[] = [+ {+ basename: '2026-08-28-pricing-sync.txt',+ transcript: [+ 'Alice-example: We will price the product per seat, not per usage.',+ 'Bob-example: The pilot with acme-example costs $40K and starts on September 15.',+ pad(12),+ 'Alice-example: Our churn is 4% this quarter, down from last quarter.',+ 'Bob-example: I will hire two engineers before the launch.',+ pad(12),+ ].join('\n'),+ newPage: [+ { id: 'c1-quote', kind: 'valid', text: 'Alice-example said "We will price the product per seat, not per usage."' },+ { id: 'c1-pilot', kind: 'valid', text: 'The acme-example pilot costs $40,000 and starts on September 15th.' },+ { id: 'c1-churn', kind: 'valid', text: 'Churn is 4% this quarter.' },+ { id: 'c1-hire', kind: 'valid', text: 'Bob-example plans to hire two engineers before the launch.' },+ { id: 'c1-fab', kind: 'fabricated_quote', text: 'Alice-example said "we will shut down the hardware line by December."' },+ { id: 'c1-swap', kind: 'speaker_swap', text: 'Bob-example said "We will price the product per seat, not per usage."' },+ { id: 'c1-num', kind: 'invented_number', text: 'The pilot budget was raised to $95K.' },+ { id: 'c1-unq', kind: 'unquoted_invention', text: 'Bob-example agreed to relocate to the Tokyo office.' },+ ],+ consolidate: [],+ personPage: [],+ timeline: [+ { id: 'c1-tl-valid', kind: 'valid', text: '- **2026-08-28** | Pilot with acme-example priced at $40K' },+ { id: 'c1-tl-num', kind: 'invented_number', text: '- **2026-08-28** | Signed a $3M contract with globex-example' },+ ],+ },+ {+ basename: '2026-08-29-launch-review.txt',+ transcript: [+ 'Bob-example: The launch date moved to October 20 because the security review slipped.',+ pad(12),+ 'Alice-example: Revenue reached $1.2M in August.',+ 'Bob-example: The support queue is under control.',+ pad(12),+ ].join('\n'),+ newPage: [+ { id: 'c2-quote', kind: 'valid', text: 'Bob-example said "The launch date moved to October 20 because the security review slipped."' },+ { id: 'c2-rev', kind: 'valid', text: 'Revenue reached $1.2 million in August.' },+ { id: 'c2-swap', kind: 'speaker_swap', text: 'Alice-example said "The launch date moved to October 20 because the security review slipped."' },+ { id: 'c2-num', kind: 'invented_number', text: 'The security review costs $120K.' },+ ],+ consolidate: [+ { id: 'c2-cons-valid', kind: 'valid', text: 'Update: the launch moved to October 20th.' },+ { id: 'c2-cons-refab', kind: 'fabricated_quote', text: 'Alice-example reiterated "we will shut down the hardware line by December."' },+ { id: 'c2-cons-fab', kind: 'fabricated_quote', text: 'Bob-example said "the security review found no issues at all."' },+ ],+ personPage: [+ { id: 'c2-person-valid', kind: 'valid', text: 'Alice-example said "Revenue reached $1.2M in August."' },+ { id: 'c2-person-fab', kind: 'fabricated_quote', text: 'Alice-example said "we doubled headcount to ninety people this year."' },+ { id: 'c2-person-num', kind: 'invented_number', text: 'Alice-example owns 35% of the company.' },+ ],+ timeline: [+ { id: 'c2-tl-valid', kind: 'valid', text: '- **2026-08-29** | Launch moved to October 20' },+ ],+ },+ {+ basename: '2026-08-30-planning.txt',+ transcript: [+ 'Alice-example: We are opening a second office in Lisbon next year.',+ pad(12),+ 'Bob-example: The acme-example pilot renewed at $55K.',+ 'Alice-example: Good, keep the renewal terms simple.',+ pad(12),+ ].join('\n'),+ newPage: [+ { id: 'c3-quote', kind: 'valid', text: 'Alice-example said "We are opening a second office in Lisbon next year."' },+ { id: 'c3-renew', kind: 'valid', text: 'The acme-example pilot renewed at $55K.' },+ { id: 'c3-swap', kind: 'speaker_swap', text: 'Bob-example said "We are opening a second office in Lisbon next year."' },+ { id: 'c3-fab', kind: 'fabricated_quote', text: 'Bob-example said "we are acquiring initech-example for cash."' },+ { id: 'c3-unq', kind: 'unquoted_invention', text: 'Alice-example decided to step down as chief executive.' },+ ],+ consolidate: [+ { id: 'c3-cons-valid', kind: 'valid', text: 'Later, Bob-example said "The acme-example pilot renewed at $55K."' },+ { id: 'c3-cons-num', kind: 'invented_number', text: 'The renewal adds 1,500 seats.' },+ { id: 'c3-cons-refab', kind: 'fabricated_quote', text: 'Alice-example reiterated "we will shut down the hardware line by December."' },+ ],+ personPage: [],+ timeline: [+ { id: 'c3-tl-num', kind: 'invented_number', text: '- **2026-08-30** | Renewal closed at $80K' },+ ],+ },+];++const PERSON_SLUG = 'wiki/people/alice-example';+const PERSON_HUMAN_LINE = 'Alice Example is a founder. She said "hardware margins are the hardest part of the business" at an offsite.';++export interface CycleSnapshot {+ cycle: number;+ statuses: Record<string, string>;+ active: Record<string, boolean>;+}++export interface ConsolidationMetrics {+ cycles: number;+ claims_by_kind: Record<ClaimKind, number>;+ /** Invented claims (every non-valid kind) active after the final cycle. */+ invented_active: number;+ invented_total: number;+ invented_active_by_kind: Record<Exclude<ClaimKind, 'valid'>, number>;+ /** Invented claims that were active after ANY cycle. */+ invented_ever_active: number;+ /** Speaker-swapped quotes active after the final cycle. */+ wrong_attribution_active: number;+ valid_total: number;+ valid_active: number;+ valid_lost: number;+ valid_lost_ids: string[];+ /** valid_active / valid_total. */+ source_supported_retention: number;+ /** The human-authored line on the person page survived every cycle. */+ human_line_intact: boolean;+ per_cycle: CycleSnapshot[];+ invented_active_ids: string[];+}++function allClaims(): Array<ScriptedClaim & { cycle: number }> {+ return CYCLES.flatMap((c, i) => [...c.newPage, ...c.consolidate, ...c.personPage, ...c.timeline].map(cl => ({ ...cl, cycle: i + 1 })));+}++async function activeMemoryText(engine: PGLiteEngine): Promise<string> {+ const pages = await engine.executeRaw<{ compiled_truth: string; timeline: string }>(+ `SELECT compiled_truth, timeline FROM pages+ WHERE deleted_at IS NULL AND NOT (COALESCE(frontmatter, '{}'::jsonb) ? 'quarantine')`);+ const timeline = await engine.executeRaw<{ summary: string; detail: string }>('SELECT summary, detail FROM timeline_entries');+ const facts = await engine.executeRaw<{ fact: string }>('SELECT fact FROM facts WHERE expired_at IS NULL');+ return comparable([+ ...pages.map(p => `${p.compiled_truth}\n${p.timeline}`),+ ...timeline.map(t => `${t.summary} ${t.detail}`),+ ...facts.map(f => f.fact),+ ].join('\n'));+}++/** Normalized and without quotation marks: a claim whose marks were stripped+ * is still the same claim in active memory. */+function comparable(s: string): string {+ return normForGrounding(s.replace(/["“”]/g, ''));+}++/** A claim is active when its distinctive text survives in active memory,+ * with or without its quotation marks. Timeline claims match on the summary+ * after the `|`; other claims on the whole line, so a speaker swap only+ * counts when its attribution survives. */+function isActive(claim: ScriptedClaim, memory: string): boolean {+ const probe = claim.text.startsWith('- **') ? claim.text.split('|')[1] : claim.text;+ return memory.includes(comparable(probe));+}++function textOf(content: unknown): string {+ if (typeof content === 'string') return content;+ if (Array.isArray(content)) return content.map(b => (b && typeof b === 'object' && 'text' in b ? String((b as { text: unknown }).text) : '')).join('\n');+ return '';+}++function reply(text: string, blocks: unknown[], stopReason: string, model?: string): ChatResult {+ return {+ text,+ blocks: blocks as never,+ stopReason: stopReason as never,+ usage: { input_tokens: 500, output_tokens: 200, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: model ?? 'anthropic:scripted',+ providerId: 'anthropic',+ };+}++/**+ * Scripted gateway transport. Triage is a JSON verdict; the synthesis child+ * runs in agentic mode through the gateway tool loop (the one production+ * mode whose children may write into existing pages): its first turn issues+ * one `brain_put_page` call per page, and its second turn ends.+ */+function scriptedTransport(engine: PGLiteEngine, state: { cycle1Slug?: string }) {+ return async (opts: ChatOpts): Promise<ChatResult> => {+ const system = opts.system ?? '';+ const messages = opts.messages ?? [];+ const firstUser = textOf(messages[0]?.content);+ if (system.startsWith('You triage a conversation transcript')) {+ return reply(JSON.stringify({ score: 0.9, content_type: 'decision', segments: [], entities: [], reasons: ['scripted'] }), [], 'end', opts.model);+ }+ const cycleIdx = CYCLES.findIndex(c => firstUser.includes(c.transcript.slice(0, 50)));+ const hash = /hash suffix \(USE THIS in slugs\): ([a-z0-9-]+)/i.exec(firstUser)?.[1];+ if (cycleIdx < 0 || !hash) return reply('{}', [{ type: 'text', text: '{}' }], 'end', opts.model);+ if (messages.length > 1) return reply('saved', [{ type: 'text', text: 'saved' }], 'end', opts.model);++ const c = CYCLES[cycleIdx];+ const date = c.basename.slice(0, 10);+ const slug = `wiki/personal/reflections/${date}-consolidation-${hash}`;+ if (cycleIdx === 0) state.cycle1Slug = slug;+ const writes: Array<{ slug: string; content: string; expected_revision?: string }> = [{+ slug,+ content: [+ '---', `title: Consolidation ${cycleIdx + 1}`, 'type: note', '---',+ `A working session between Alice-example and Bob-example. See [[${PERSON_SLUG}]].`,+ '',+ ...c.newPage.map(cl => `- ${cl.text}`),+ ...(c.timeline.length ? ['', '## Timeline', '', ...c.timeline.map(cl => cl.text)] : []),+ ].join('\n'),+ }];+ const rewrite = async (target: string, title: string, type: string, added: string[], sep: string) => {+ const snap = await engine.readPageSnapshot(target, { sourceId: 'default' });+ if (!snap) return;+ const tl = snap.page.timeline?.trim() ? `\n\n## Timeline\n\n${snap.page.timeline.trim()}` : '';+ writes.push({+ slug: target,+ expected_revision: snap.revision,+ content: `---\ntitle: ${title}\ntype: ${type}\n---\n${snap.page.compiled_truth.trim()}${sep}${added.join(sep)}${tl}`,+ });+ };+ if (c.consolidate.length && state.cycle1Slug) {+ await rewrite(state.cycle1Slug, 'Consolidation 1', 'note', c.consolidate.map(cl => `- ${cl.text}`), '\n');+ }+ if (c.personPage.length) await rewrite(PERSON_SLUG, 'Alice Example', 'person', c.personPage.map(cl => cl.text), '\n\n');+ return reply('', writes.map((input, i) => ({ type: 'tool-call', toolCallId: `put-${cycleIdx}-${i}`, toolName: 'brain_put_page', input })), 'tool_calls', opts.model);+ };+}++/**+ * Run the experiment and return its measurements. `onCycle` receives each+ * cycle's phase reports (for debugging and the script's verbose mode).+ */+export async function runRepeatedConsolidation(opts: { onCycle?: (cycle: number, phases: unknown) => void } = {}): Promise<ConsolidationMetrics> {+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite' } as never);+ await engine.initSchema();+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-consolidation-brain-'));+ const corpusDir = mkdtempSync(join(tmpdir(), 'gbrain-consolidation-corpus-'));+ const home = mkdtempSync(join(tmpdir(), 'gbrain-consolidation-home-'));+ const state: { cycle1Slug?: string } = {};+ const perCycle: CycleSnapshot[] = [];+ const claims = allClaims();+ try {+ await importFromContent(engine, PERSON_SLUG, `---\ntype: person\ntitle: Alice Example\n---\n${PERSON_HUMAN_LINE}`, { noEmbed: true, remote: false, sourceId: 'default' });+ await engine.setConfig('dream.synthesize.enabled', 'true');+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusDir);+ await engine.setConfig('dream.synthesize.cooldown_hours', '0');+ await engine.setConfig('dream.synthesize.min_chars', '200');+ await engine.setConfig('dream.synthesize.mode', 'agentic');+ await engine.setConfig('agent.use_gateway_loop', 'true');++ for (let i = 0; i < CYCLES.length; i++) {+ writeFileSync(join(corpusDir, CYCLES[i].basename), CYCLES[i].transcript);+ // runCycle resets the gateway at its end; re-install the stub per cycle.+ __setChatTransportForTests(scriptedTransport(engine, state));+ const report = await withEnv({ ANTHROPIC_API_KEY: 'sk-test-consolidation', GBRAIN_HOME: home }, () =>+ runCycle(engine, { brainDir, phases: ['synthesize', 'extract', 'extract_facts'] }));+ const statuses = Object.fromEntries(report.phases.map(p => [p.phase, p.status]));+ opts.onCycle?.(i + 1, report.phases);+ const memory = await activeMemoryText(engine);+ perCycle.push({+ cycle: i + 1,+ statuses,+ active: Object.fromEntries(claims.filter(c => c.cycle <= i + 1).map(c => [c.id, isActive(c, memory)])),+ });+ }++ const final = perCycle[perCycle.length - 1].active;+ const invented = claims.filter(c => c.kind !== 'valid');+ const valid = claims.filter(c => c.kind === 'valid');+ const byKind = { fabricated_quote: 0, speaker_swap: 0, invented_number: 0, unquoted_invention: 0 };+ for (const c of invented) if (final[c.id]) byKind[c.kind as keyof typeof byKind]++;+ const claimsByKind = { valid: 0, fabricated_quote: 0, speaker_swap: 0, invented_number: 0, unquoted_invention: 0 };+ for (const c of claims) claimsByKind[c.kind]++;+ const person = await engine.getPage(PERSON_SLUG, { sourceId: 'default' });+ const validLost = valid.filter(c => !final[c.id]).map(c => c.id);+ return {+ cycles: CYCLES.length,+ claims_by_kind: claimsByKind,+ invented_total: invented.length,+ invented_active: invented.filter(c => final[c.id]).length,+ invented_active_by_kind: byKind,+ invented_ever_active: invented.filter(c => perCycle.some(s => s.active[c.id])).length,+ invented_active_ids: invented.filter(c => final[c.id]).map(c => c.id),+ wrong_attribution_active: byKind.speaker_swap,+ valid_total: valid.length,+ valid_active: valid.length - validLost.length,+ valid_lost: validLost.length,+ valid_lost_ids: validLost,+ source_supported_retention: (valid.length - validLost.length) / valid.length,+ human_line_intact: normForGrounding(person?.compiled_truth ?? '').includes(normForGrounding(PERSON_HUMAN_LINE)),+ per_cycle: perCycle,+ };+ } finally {+ __setChatTransportForTests(null);+ resetGateway();+ try { await engine.disconnect(); } catch { /* best-effort */ }+ for (const d of [brainDir, corpusDir, home]) try { rmSync(d, { recursive: true, force: true }); } catch { /* best-effort */ }+ }+}