Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search,facts): C1 dated evidence headers, C2 interleaved supersession candidates

garrytan91081f319b72
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index 347f55c1b6..66bcab4264 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -17,7 +17,7 @@
- `src/core/onboard/writeback-nudge.ts` — the fire-once consent ASK (init epilogue + `runPostUpgrade`): double gate (sentinel `memory.auto_writeback_notice_shown` + setting unset), personal-audience only, suppressed on mounts/thin-clients/env bypass, `[AGENT]`-relayed disclosure + ask (non-TTY IS the relay path — deliberately unlike runInitNudge), sentinel stamped AFTER printing (a decline is permanent; a shared classification does NOT burn the sentinel), whole body try/caught (init/upgrade must survive a crashing nudge). The recurring reminder is `src/core/advisor/collect-writeback-consent.ts` (info, `ask_user`, NO dispatch_id — consent is never `--apply`-able; local-only; fires only AFTER the sentinel so the advisor is never the first ask).
- `src/core/bootstrap/instructions-block.ts` — the managed harness block (`<!-- gbrain:ambient-writeback:begin/end -->`): spliceCompiledBlock discipline verbatim (idempotent replace-interior, THROW on damaged markers, marker-equal body lines neutralized), header names mode + serve endpoint (multi-brain last-wins stays visible), remove/strip helpers never delete a user file. Harness lane (`src/core/bootstrap/harness.ts`): `kind:'instructions'` targets (additive under receipt version 1 — old binaries won't unwire them, documented) for user-scope CLAUDE.md + `$CODEX_HOME/AGENTS.md` (paths + the AGENTS.override.md exclusivity probe are dated PROVISIONAL spec entries in `host-specs.ts`); enabled ⇒ install, disabled ⇒ CONVERGE (strip blocks + receipt targets + advisory line; a strip FAILURE is recorded as a failed `instructions` receipt target so --status/--remove/the next converge keep tracking the orphan); registrar mode (non-loopback --url) NEVER installs blocks — the local mirror speaks for the local brain, and the remote brain's own MCP instructions carry the contract when its operator opts in; a block installs only when the SAME host's MCP target confirmed (both lanes — a foreign-registration refusal or failed write must not leave a block directing saves at a server this run never registered), and a failed final smoke STRIPS the blocks this run installed (targets marked failed) so no block outlives its rolled-back registration; `--remove`/`--status` wired.
- Stop-hook backstop lane: `hookStop` in `src/commands/hook.ts` (own 2s deadline inside Stop's 10s cap, fail-open exit 0, file-plane gate, a gbrain claude-cli scratch session [transcript path or payload cwd fingerprint, the SessionEnd guard's] is the by-design skip `self_capture` before any parse, 128KB-tail transcript parse selecting the newest structurally genuine user turn via `genuineUserTurnIndexes` [a paste-only turn is not genuine], with ONE 2MB-cap retry when the cheap tail contains none — turn OFFSET from EOF ≠ turn size, and Claude's user-role tool-result placeholders neither shadow the prompt nor suppress the retry — then gate → secret-scanned `bankWritebackTurn` [corpus-segments.ts: `<session>.wb-<hash24>[.src-<sourceId>].txt` — the source segment lets the SWEEP fallback file the turn into the session's own source; scanner-unavailable = fail-closed skip] → `requestContextPack(bankOnly, flushCorpusFile, trigger:'writeback-bank', sourceId from GBRAIN_SOURCE)`; every outcome a typed `writeback-bank` heartbeat reason — by-design skips [gate reasons, no_user_turn, flush_skip_*] ride `outcome:'ok'`, 'degraded' is INFRA faults only) → `src/mcp/context-pack-handler.ts` tags `.wb-` basenames `lane:'writeback'` → `checkpoint-harvest.ts`'s writeback lane (a self-capture session [`isClaudeCliSelfSessionId`] is the terminal `.ingested {skipped:'self_capture'}` before any gate or extraction; both lanes extract `corpusTextForExtraction` text; AUTHORITATIVE serve-side `memory.auto_writeback` re-check with `{gate:true}` + loadConfig drift input — off ⇒ terminal `.ingested {skipped:'writeback_off'}`; `plane_drift`/invalid mode/read_error/non-transport extraction skip [`extract_skipped_*`: refusal/content_filter/malformed_output class] ⇒ NO sidecar, file survives for the sweep; salient ⇒ `notabilityFilter:'medium-and-up'`; `source:'hook:writeback'`; NO manifest publish; per-session prompt-harvest cap `WRITEBACK_SESSION_CAP=30` in a true-LRU counter map [delete-before-set on increment], budget burned only on real enqueues, overflow = ACK-only skip the sweep batch-extracts; heartbeats under `event:'writeback'` with PERSISTED inserted/duplicate/superseded). The sweep's corpus pass recognizes `.wb-` files, applies the same gate semantics, routes to the FILENAME-banked source (isValidSourceId-checked, pass source as fallback), and records `skipped_reason` in its terminal sidecar (`src/core/sweep.ts`) — leftover banked turns never bypass the OFF gate and never silently zero out. wb-file state machine: ack-only skips leave the file for the sweep; `writeback_off` is the one terminal skip sidecar.
- - Read-time TTL validity (there is no sweeper): ACTIVE fact reads in BOTH engines (`listFactsByEntity/Since/BySession`, both `findCandidateDuplicates` branches, `countUnconsolidatedFacts`, `getFactsHealth` active buckets) carry `AND (valid_until IS NULL OR valid_until > now())` — `valid_until` is temporal validity, not retention; history paths (`listSupersessions`, `findTrajectory`, `--asof`) deliberately still see lapsed rows; a re-stated expired fact re-inserts fresh. Pinned by `test/facts/ttl-validity.test.ts` + engine-parity additions.
+ - Read-time TTL validity (there is no sweeper): ACTIVE fact reads in BOTH engines (`listFactsByEntity/Since/BySession`, every `findCandidateDuplicates` branch (cosine, keyword, recency), `countUnconsolidatedFacts`, `getFactsHealth` active buckets) carry `AND (valid_until IS NULL OR valid_until > now())` — `valid_until` is temporal validity, not retention; history paths (`listSupersessions`, `findTrajectory`, `--asof`) deliberately still see lapsed rows; a re-stated expired fact re-inserts fresh. Pinned by `test/facts/ttl-validity.test.ts` + engine-parity additions.
- Diagnostics: `src/commands/doctor/checks/memory-writeback.ts` (`memory_writeback`, BRAIN category) — quiet-ok when off, but the OFF branch still probes receipt + canonical instruction paths and WARNS on a lingering block (off-but-still-instructing) with the converge command; plane-compare warns when the file mirror disagrees with the DB row (the Stop hook acting on the wrong truth) naming the re-sync; a read_error reports the state as UNKNOWN, never "off (default)"; resolved bundle + BOTH visibility postures + audience/reasons; on both branches an explicit private `facts.default_visibility` on a non-shared brain with remote readers (a harness receipt, or HTTP MCP clients active in 30d; listed in `private_default_remote_readers`) warns with the shared `PRIVATE_DEFAULT_REMOTE_CONSEQUENCE` text (`writeback-config.ts`), the same text `bootstrap harness` prints before consent; instruction blocks receipt-vs-live-probe-vs-drift compare (drift fix names the `config set` + `bootstrap harness` combo — the config set re-stamps the posture mirror so the re-render converges even after an out-of-band visibility flip) + AGENTS.override.md detection — and a receipt target in state `failed` is a STANDING warn regardless of the live probe (the one physical-survival path — a smoke-rollback strip that itself threw — leaves a current-looking block directing sessions at a rolled-back endpoint, and only the receipt state knows) naming the `bootstrap harness --yes` / `--remove` converge; validity-lapsed count; 7d counters (verbs usage sidecar's additive `remember_status` [stamped in `src/mcp/dispatch.ts`, ALL-MCP-callers semantics labeled honestly] + `writeback`/`writeback-bank` heartbeat events; `turns_banked` counts flush_skip_* — banked, enqueue declined) with the local/lossy disclosure. Null-engine runs report the file mirror honestly. `cross_lane_duplicates_7d` / `near_duplicates_shadow_7d` sum the `writeback_dedup` heartbeat events in both the on and off branches.
- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.serial.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).
- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `GBRAIN_SWEEP=0` kills it. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created.
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 50ddb8753c..e5b7ac49d1 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -28,7 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/explain-formatter.ts` — renders `SearchResult[]` as a multi-line per-result breakdown for `gbrain search --explain`. Reads every boost-stamping field; also prints the raw query↔chunk cosine (`SearchResult.cosine`, the calibrated signal evidence keys off) next to the blended score when present — absent on keyword-only / no-embedding paths. Handles the "no boosts applied" empty path. 4-decimal precision with trailing-zero strip. `formatResultsExplain(results, meta?)` prepends header lines from the captured retrieval meta when present — `formatAutocutSummary` (the autocut decision) and `formatDegradedSummary(meta.degraded)`, which renders the closed `degraded[]` vocabulary as `degraded: reranker_skipped (no_key)` (null when the run was clean); `cli.ts:formatResult` threads `lastRetrievalMeta` into it, so a silently skipped reranker is visible from the CLI. Pinned by `test/search/explain-formatter.test.ts` + `test/cli-explain-degraded-render.test.ts`. `formatDecideSummary` prints one `decide <slot>:` line per slot that ran (all-off: none), including the slot's answer summary (S2 label, S4 probability and verdict).
-- `src/core/search/fusion-lists.ts` — the ONE composition point for `hybridSearch`'s RRF inputs. Every vector recall list is a ROLE-tagged arm (`VectorArm {list, role: 'original'|'variant'|'clause'|'image'}`, appended only via `pushVectorList`) — never a parallel index-aligned array: the `Promise.allSettled` salvage path drops failed arms and the both-mode image branch fails open, so any positional rule ("last list is the image", "index 0 is the original") mis-tags lists under partial failure. `composeFusionLists({arms, keywordFusionList, titleFusionList, relationalList, includeRelational, ks, knobs})` returns the complete weighted list set (`FusionListEntry {list, k, weight?}`) in the fixed order vector arms → keyword (`keywordK`) → title (`keywordK`, only if non-empty) → relational (`baseRrfK`, only if non-empty and not image modality): text arms fuse at `textRrfK` and the image arm at `imageRrfK` only when BOTH kinds are present, otherwise every arm at `vectorK` (text, image-only, unified, and a both-mode whose image branch fell open). `variant`/`clause` arms share `expansionVariantBudget` as total RRF weight — `weight_i = b / n_voting_arms` over the NON-EMPTY expansion arms (an empty list casts no vote), the `original` arm always weight 1; a `null` budget emits no `weight` key, byte-identical to unweighted fusion; when the original is missing (its embed or `searchVector` failed) every surviving text arm is a `variant` sharing the budget. `rrfFusionWeighted` (hybrid.ts) scores `weight / (k + rank)` — the literature weighted-RRF form, a list-level multiplier that holds at every rank (a k-penalty would fade at deep ranks). `textArmsNonEmpty` is the role-based text-arm health gate behind the OR-relaxed keyword demotion (image arms never count, so a fell-open image branch can't veto the lexical rescue). `normalizeExpansionVariantBudget` is the single range contract for the knob: finite `(0, 4]` (or a string parsing to one) → number, `null`/`legacy`/`null`-literal → null, anything else → `undefined` (fall through to config → bundle); shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`, so an invalid per-call value never reaches fusion or the cache key. Pure, no engine/IO. Pinned by `test/search/fusion-lists.test.ts` (knife-edge arithmetic at budget 1.0, legacy deep-equals the pre-role text mapping, role alignment under rejected arms), `test/search/expansion-variant-budget.test.ts` (hermetic directional PGLite test), and the both-mode demotion-gate regression in `test/keyword-relaxed-fusion.serial.test.ts`.
+- `src/core/search/fusion-lists.ts` — the ONE composition point for `hybridSearch`'s RRF inputs. Every vector recall list is a ROLE-tagged arm (`VectorArm {list, role: 'original'|'variant'|'clause'|'image'}`, appended only via `pushVectorList`) — never a parallel index-aligned array, since the `allSettled` salvage path drops failed arms and the both-mode image branch fails open, so positional rules mis-tag lists. `composeFusionLists({arms, keywordFusionList, titleFusionList, relationalList, includeRelational, ks, knobs})` returns the complete weighted list set (`FusionListEntry {list, k, weight?}`) in the fixed order vector arms → keyword (`keywordK`) → title (`keywordK`, only if non-empty) → relational (`baseRrfK`, only if non-empty and not image modality): text arms fuse at `textRrfK` and the image arm at `imageRrfK` only when BOTH kinds are present, otherwise every arm at `vectorK` (text, image-only, unified, and a both-mode whose image branch fell open). `variant`/`clause` arms share `expansionVariantBudget` as total RRF weight — `weight_i = b / n_voting_arms` over the NON-EMPTY expansion arms (an empty list casts no vote), the `original` arm always weight 1; a `null` budget emits no `weight` key, byte-identical to unweighted fusion; when the original is missing every surviving text arm is a `variant` sharing the budget. `rrfFusionWeighted` (hybrid.ts) scores `weight / (k + rank)` (weighted RRF: a list-level multiplier at every rank). `textArmsNonEmpty` is the role-based text-arm health gate behind the OR-relaxed keyword demotion (image arms never count). `normalizeExpansionVariantBudget` is the single range contract for the knob: finite `(0, 4]` (or a string parsing to one) → number, `null`/`legacy`/`null`-literal → null, anything else → `undefined` (fall through to config → bundle); shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`, so an invalid per-call value never reaches fusion or the cache key. `interleaveFusion(arms, key, limit)`: score-free round-robin (each arm's #1, then #2, deduped by key, cut at `limit`) for fact supersession candidates (`facts.candidate_fusion`); hybrid search stays on RRF (`test/search/interleave-fusion.test.ts`). Pure, no engine/IO. Pinned by `test/search/fusion-lists.test.ts` (knife-edge arithmetic at budget 1.0, legacy deep-equals the pre-role text mapping, role alignment under rejected arms), `test/search/expansion-variant-budget.test.ts` (hermetic directional PGLite test), and the both-mode demotion-gate regression in `test/keyword-relaxed-fusion.serial.test.ts`.
- `src/core/search/graph-signals.ts` — per-query graph-signals helper. `applyGraphSignals(results, engine, opts)` runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: `ADJACENCY_BOOST=1.05` (page linked from 2+ OTHER top-K results — local hub for THIS query), `CROSS_SOURCE_BOOST=1.10` (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), `SESSION_DEMOTE=0.95` (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. `computeScoreDistribution(results)` emits min/p25/p50/p75/p95/max + `reorder_band_width`. `sessionPrefix(slug)` extracts the chat-session anchor (`chat/2026-05-15-...`). Pure `pairedBootstrapPValue(deltas, resamples, rng)` exported for eval gates. Test seam via `adjacencyFn` DI. Fail-open: any error logs via `logGraphSignalsFailure` (JSONL audit via `audit-writer`) and returns the input array unchanged. Pinned by `test/search/graph-signals.test.ts` (incl. the IRON-RULE floor-gate guard). The atoms/ namespace is excluded from session diversification even when a later segment resembles a date or chat marker; daily, meeting and transcript siblings retain their existing demotion.
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 06cef30bb4..39a32ad748 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -3,7 +3,9 @@
[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/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list; `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.
+- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list; `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.
+
+- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` (midnight UTC renders as written, other instants in `brain.timezone`; the rule think's page dates use), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.
- `src/core/search/chunk-windows.ts` — request/response shapes and the row mapper for `BrainEngine.getChunkWindows`. The SQL lives once in `src/core/engine-sql/chunks.ts` (`getChunkWindows`): page rows (authorization + seal + max chunk index + raw body columns) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction.
diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.md
index 16e19c7d5e..6798ce7ebb 100644
--- a/docs/architecture/key-files/evaluation.md
+++ b/docs/architecture/key-files/evaluation.md
@@ -5,6 +5,8 @@
[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.
+- `scripts/eval-c2-candidate-fusion.ts` + `scripts/eval-c2-embed.py` — the C2 offline eval: a seeded synthetic fixture (40 companies; single-valued claims with changed numbers/dates, coexisting similar claims, private rows, a dense crowded slice, back-to-back corrections) replayed on PGLite through `listSupersessionCandidates` for `facts.candidate_fusion` `rrf_free` vs `interleave`, embedded once with a free local model. Reports twin recall@5, false supersession, preserved distinct claims and correct decisions per threshold, paired by probe and clustered by company (`pairedClusterStatistics`); at 0.95 the real `decideSingleFact` runs beside the replayed rule and must agree. Output: `docs/eval/decisions/c2-interleave-dev/verdict.json`.
+
- `src/eval/longmemeval/reader.ts` + `gateway-client.ts` — the LongMemEval answer request seam, exported as `gbrain/eval/longmemeval/reader`. `resolveReaderConfig` selects notes-first/1024 by default or the frozen direct-v3/512 baseline; `buildReaderRequest` changes only the system instruction and budget, retaining the same full-session sanitizer, evidence order and dates. `readerConfigHash` pins mode, system-prompt version/sha, requested model and token budget. `generateAnswer` reports the provider finish reason and joins every text block. The command records `reader_partial_output` as a diagnostic, never a completed hypothesis, when the reader stops at the limit or returns empty/unknown completion; those failures count in the judged headline denominator and fail the run without automatic paid retries. Tests: `test/longmemeval-reader.test.ts`, `test/eval-longmemeval-reader-mode.slow.test.ts`, `test/eval-answer-packet.test.ts` (historical explicit direct baseline).
- `evals/brainbench/` — the committed BrainBench corpus: 141 fixtures (135 generated + 6 hand-authored spike) / 241 gold-annotated turns across 7 categories (kta-pos/kta-neg/push/write-back/continuity/multi-source/adversarial), ~15% holdout (excluded from the CI gate, scored in published `--include-holdout` runs). `generator/gen.ts` rebuilds the corpus byte-identically (Mulberry32, seed 42; whole-cloth fictional universe from curated synthetic name pools so scenario privacy is structural; prose is template-synthesized with PRNG-selected variants — deliberately no LLM pass, difficulty stays controlled; several know-to-ask variants intentionally exercise documented v1 reflex limits so the baseline measures the roadmap). `gold/` is sealed; `schema/` is the foreign-runner contract (gbrain-evals drives the suite as a subprocess via `--fixtures DIR --gold DIR --json --out FILE`); `baselines/main.json` is the committed gate baseline; `_ledger.json` records counts/seed/rebuild command. CI: the `.github/workflows/test.yml` `brainbench` job + `scripts/ci-brainbench-gate.sh` (fetches MAIN's baseline via `git show origin/master:…` — a PR cannot rewrite what it's compared against; first-landing path runs ungated) + `scripts/render-brainbench-delta.ts` (compact step-summary/PR-body delta block from the `--out` artifact). Privacy: `scripts/check-synthetic-corpus-privacy.sh` scans `evals/brainbench/{fixtures,gold}` in `bun run verify`.
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index a18f7ec694..f08995047b 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -87,6 +87,8 @@ rejection of serve-only flags before a brain opens.
- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes keep the 0.95 drop; capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).
+- `src/core/facts/single-prepare.ts` — the one supersession decision every managed fact write prepares and re-checks under its publication guard (`decideSingleFact`: exact fingerprint duplicate, else the highest-cosine ELIGIBLE candidate — same visibility, active, same entity page — through `cosineVerdict`). `listSupersessionCandidates` builds the scored set: the cosine arm's top `SUPERSESSION_CANDIDATE_K` (5), or with `facts.candidate_fusion = interleave` the cosine and keyword arms (`findCandidateDuplicates` `arm: 'keyword'`: same bucket and comparability filters, `ts_rank_cd` over an OR of the claim's lexemes) merged by `interleaveFusion` and cut to the same k. Default `rrf_free` (cosine only); unknown values read as the default. The dev verdict is `docs/eval/decisions/c2-interleave-dev/`. Tests: `test/facts/candidate-fusion.test.ts`; eval `scripts/eval-c2-candidate-fusion.ts`.
+
- `src/core/facts/relink.ts` + `relink-publish.ts` + `relink-model.ts` + `relink-reasons.ts` + `relink-schema.ts` — `gbrain facts relink` (`src/commands/facts.ts`, CLI-only, host-only). Candidates are active database-only rows with `entity_slug IS NULL` (fence-owned subjectless rows are only counted), walked by id from `--after-id` over `idx_facts_unlinked_active`. Free tiers via `inferFactSubject`, then the model tier (`facts.extraction_model`, batches of 25, `--max-usd` BudgetTracker cap, private facts only with `--include-private`; an answer must quote the fact and pass the strict resolver). Publication is one coordinator request per entity page (`relink_facts`, dispatched from `persistence/service.ts`, managed or not): each fact's whole row is pinned by hash; prepare and the locked validation must classify identically; linked rows take fresh fence positions (row id, embedding and provenance kept, context gains `entity relinked from <tier>`) ahead of the page projection; exact duplicates retire expired and detached; nothing is superseded; withdrawn claims are skipped; attempt rows and the `decide_sweep_deferred` handoff (`enqueueRelinked`, when the conflict slot is not off) commit in the same transaction. Write target follows `persistence/fact-write-target.ts` (the remember rule): bound write-through publishes the file, write-through off or connector-database publishes the page body only, an unbound write-through source is refused as `unfenceable` (relink never claims an owner). `fact_relink_attempts` (migration v187) holds `linked`/`deduped` records and model verdict memos (`no_subject`, `ambiguous`, `unverified_match`) that stop reruns from paying again unless `--retry-model`. `RELINK_REASONS` is the one reason list (code, memoized flag, fix text) used by output, memo and the guide. Pinned by `test/facts-relink.test.ts` and `test/facts-relink-routing.test.ts` (+ `test/e2e/facts-relink-routing.test.ts`).
- `src/core/entity-identity.ts` + `src/core/ops/entity-identity.ts` — cross-source entity identity (cross-source federation). THE IDENTITY KEY IS `(source_id, slug)`: the same real-world entity routinely exists as a different page per mounted source, and nothing else in gbrain asserts "these pages are the same entity". The `entity_identities` table (migration v137) records that assertion explicitly — member pages grouped under an opaque `entity_id` handle (`validateEntityId`: slug-flavored, lowercase, max 128 chars), one optional canonical member per group, a page belongs to at most one identity (`UNIQUE (source_id, page_id)`; re-linking MOVES it). A link's canonical demotion and upsert run in one transaction, and re-linking with `canonical` omitted keeps the member's canonical flag within the same group (`canonical: false` demotes explicitly). Posture is MANUAL-ONLY by design: rows come exclusively from the `entity_identity_link` op — no auto-matching or name-similarity heuristics, because a wrong identity merge silently corrupts retrieval. Three ops: `entity_identity_link` / `entity_identity_unlink` (write, localOnly — merges change what retrieval unions across sources, too sharp for a remote surface) + `entity_identity_list` (read; restricts MEMBER visibility to a federated grant or remote scalar scope, while a trusted local caller sees the full cross-source group — cross-source IS the feature). Retrieval union is OFF by default behind the `entity_identity.union` config key; when on, get_links/get_backlinks merge edges from identity co-members (dedup'd), never widening past the caller's source grant. Same SQL text on both engines (parity by construction); pinned by the entity-identity test + the DATABASE_URL-gated engine-parity suite. Topology context: `docs/architecture/brains-and-sources.md`.
diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.md
index 04d6bc82df..5c923bd24b 100644
--- a/docs/evidence-delivery.md
+++ b/docs/evidence-delivery.md
@@ -77,7 +77,12 @@ Per-call params on `search`, `query`, `recall`:
long sessions were still trimmed) and the other units use
`search.return_budget_default` (default 6,000). Remote callers are clamped to
`search.return_budget_max_remote` (default 32,000); the clamp is reported in
- `delivery.budget_clamped` and `delivery.fallbacks`, never raised.
+ `delivery.budget_clamped` and `delivery.fallbacks`, never raised per call.
+ A trusted brain that needs more over stdio MCP (an eval cell's hermetic
+ brain, for example) raises the ceiling once with
+ `gbrain config set search.return_budget_max_remote 200000` and asserts that
+ `delivery.budget_clamped` is absent; trusted local CLI calls are never
+ clamped.
- Legacy budget knobs keep their meaning: with `return_unit` omitted,
`query`'s `token_budget` still prunes chunks (chunk mode), and `recall`'s
`budget_tokens` / `budget_policy` still pack chunks (facts first), so any of
@@ -88,9 +93,33 @@ Think reads `think.return_unit` (default `auto`) and never
Under `auto`, think renders conversation pages whole and keeps its usual
excerpts for every other page.
+### Date headers
+
+With `search.evidence_date_header` on (default off), every delivered block,
+including `auto`'s unchanged chunks, starts with one fixed line, and
+`delivery.date_header` is `true`:
+
+```text
+[observed 2026-03-05]
+```
+
+`observed` is when the page's text was written or said: its filename or slug
+date, frontmatter `date`, `published` or a created key, in effective-date
+precedence with `event_date` removed. An event date (when something happened)
+and the row's own timestamps are never shown as observed; a page without an
+observation date reads `[observed unknown]`. A date stored at midnight UTC
+renders as written, any other instant in `brain.timezone`. The header line
+and its newline are part of `chunk_text`: they count in `delivered.tokens`,
+`tokens_delivered` and the budget, `match_spans` offsets include them, and
+`evidenceFingerprint` hashes them. `recall` facts gain
+`date_header: "[observed unknown; valid 2026-03-01 to unknown]"` (facts carry
+no observation date; an open validity end reads `unknown`). The setting
+applies to `search`, `query`, `recall`, `think` and `assemble_evidence`.
+
Config keys: `search.return_unit`, `search.return_window`,
`search.return_budget_default`, `search.return_budget_conversation`,
-`search.return_budget_max_remote`, `think.return_unit`. Kill switch:
+`search.return_budget_max_remote`, `search.evidence_date_header`,
+`think.return_unit`. Kill switch:
`gbrain config set search.return_unit chunk` and
`gbrain config set think.return_unit chunk` (or pass `return_unit: "chunk"`
per call).
@@ -191,7 +220,8 @@ Response meta (`_meta.retrieval.delivery` over MCP; top-level `delivery` on
"dropped": 1, // hits/pages not delivered
"dropped_reasons": { "budget_floor": 1 },
"fallbacks": ["budget_clamped"], // distinct non-fatal problem codes, never silent
- "budget_clamped": { "requested": 50000, "max": 32000 }
+ "budget_clamped": { "requested": 50000, "max": 32000 },
+ "date_header": true // only when search.evidence_date_header is on
}
```
@@ -214,6 +244,7 @@ delivered text and each result gains `delivered`.
| `snippet_cap` | An explicit `snippet_chars` cut a block. | Capped block, `truncated: true`. |
| `budget_clamped` | A remote budget above the max was clamped. | Clamped budget. |
| `tokenizer_heuristic` | cl100k unavailable; char/4 heuristic used. | Counts from the heuristic. |
+| `date_header_unavailable` | Date headers are on but the page dates could not be read. | Every header reads `[observed unknown]`. |
| drop `not_readable` | The page is no longer readable by this caller (deleted, private, grant revoked, quarantined, archived source, source outside scope). | Result removed. Never falls back to cached text. |
| drop `budget_floor` | Not even the block's matching span fits the remaining budget. | Result removed (rank one is instead cut to fit). Under `auto` nothing is dropped for budget: the conversation keeps its ranked chunks. |
diff --git a/scripts/eval-c2-candidate-fusion.ts b/scripts/eval-c2-candidate-fusion.ts
new file mode 100644
index 0000000000..c02d43e315
--- /dev/null
+++ b/scripts/eval-c2-candidate-fusion.ts
@@ -0,0 +1,406 @@
+/**
+ * C2 offline eval: fact supersession candidates, `facts.candidate_fusion`
+ * `rrf_free` (one cosine arm, the current behavior) against `interleave`
+ * (cosine + keyword arms, round-robin, cut to k = 5), on PGLite. No model or
+ * network calls in the replay: the fixture is generated from a fixed seed and
+ * embedded once with a free local model (scripts/eval-c2-embed.py); the
+ * verdict records the sha256 of the texts and of the embeddings file.
+ *
+ * bun scripts/eval-c2-candidate-fusion.ts texts > /tmp/c2-texts.json
+ * python3 scripts/eval-c2-embed.py /tmp/c2-texts.json /tmp/c2-embeddings.json.gz
+ * bun scripts/eval-c2-candidate-fusion.ts run --embeddings /tmp/c2-embeddings.json.gz [--out docs/eval/decisions/c2-interleave-dev]
+ *
+ * Fixture: 40 synthetic companies. Each has single-valued claims (revenue,
+ * headcount, runway, …) as world facts, similar-but-different coexisting
+ * claims (funding rounds, quarterly revenue, offices, board dates), and
+ * private rows (a private copy and a private note of world claims, plus one
+ * private-only claim). Probes, replayed in order through the product's
+ * candidate listing: corrections with changed numbers or dates, restatements,
+ * back-to-back corrections of one claim (the state a concurrent pair reaches
+ * after the publication guard's retry), a private correction, new members of
+ * coexisting claims and new claims. Every row carries its claim key, so the
+ * expected twin of each probe is known by construction.
+ *
+ * Metrics per probe, paired by probe and clustered by company: twin
+ * recall@5 (an active row of the probe's claim is in the scored candidate
+ * set), false supersession (the decision replaced or deduplicated a row of a
+ * different claim), correct decision. Per company at the end of the replay:
+ * preserved distinct claims (every claim ever established still has an
+ * active row). The decision is decideSingleFact's rule (max cosine among
+ * eligible candidates at or above the threshold) replayed at each threshold
+ * in TAUS; at 0.95 (the product's explicit-lane threshold) the real
+ * decideSingleFact runs beside it and must agree.
+ */
+import { createHash } from 'node:crypto';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { gunzipSync } from 'node:zlib';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { cosineSimilarity } from '../src/core/facts/classify.ts';
+import { EXPLICIT_DUPLICATE_THRESHOLD } from '../src/core/facts/capture-dedup.ts';
+import {
+ CANDIDATE_FUSION_KEY, SUPERSESSION_CANDIDATE_K, decideSingleFact, listSupersessionCandidates, type CandidateFusion,
+} from '../src/core/facts/single-prepare.ts';
+import { mulberry32 } from '../src/eval/shared/bootstrap.ts';
+import { holmAdjusted, pairedClusterStatistics } from '../src/core/eval/paired-bootstrap.ts';
+
+export const FIXTURE_SEED = 20261005;
+export const TAUS = [0.85, 0.9, 0.95] as const;
+const MODES: CandidateFusion[] = ['rrf_free', 'interleave'];
+const SOURCE = 'eval:c2-explicit';
+const DRAWS = 10_000;
+
+type Visibility = 'world' | 'private';
+interface Row { key: string; fact: string; visibility: Visibility }
+interface Probe extends Row { kind: 'correction' | 'restatement' | 'concurrent' | 'private_correction' | 'coexisting' | 'new_claim' }
+interface Company { slug: string; dense: boolean; seeds: Row[]; probes: Probe[] }
+
+// ---------------------------------------------------------------------------
+// Fixture (deterministic from FIXTURE_SEED)
+// ---------------------------------------------------------------------------
+
+const STEMS = ['Alder', 'Birch', 'Cedar', 'Dogwood', 'Elm', 'Fir', 'Ginkgo', 'Hazel', 'Ironwood', 'Juniper',
+ 'Kauri', 'Larch', 'Maple', 'Nutmeg', 'Oak', 'Pine', 'Quince', 'Rowan', 'Spruce', 'Teak'];
+const PEOPLE = ['Alice Example', 'Bob Example', 'Carol Example', 'Dan Example', 'Erin Example', 'Frank Example', 'Grace Example', 'Hank Example'];
+const CITIES = ['Austin', 'Denver', 'Boston', 'Seattle', 'Toronto', 'Lisbon', 'Berlin', 'Dublin', 'Singapore', 'Sydney', 'Chicago', 'Madrid'];
+const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
+
+type Rand = () => number;
+const int = (r: Rand, lo: number, hi: number) => lo + Math.floor(r() * (hi - lo + 1));
+const pick = <T>(r: Rand, xs: readonly T[]): T => xs[Math.floor(r() * xs.length)];
+const shuffle = <T>(r: Rand, xs: readonly T[]): T[] => {
+ const out = [...xs];
+ for (let i = out.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [out[i], out[j]] = [out[j], out[i]]; }
+ return out;
+};
+const day = (r: Rand) => `${pick(r, MONTHS)} ${int(r, 1, 28)}, ${int(r, 2025, 2027)}`;
+
+/** Single-valued claims: a new value corrects the old one. Two phrasings each. */
+const SINGLE: Record<string, { value: (r: Rand) => string; say: Array<(e: string, v: string) => string> }> = {
+ arr: { value: r => `$${int(r, 2, 60)}M`, say: [(e, v) => `${e}'s annual recurring revenue is ${v}.`, (e, v) => `${e} now has ${v} in annual recurring revenue.`] },
+ headcount: { value: r => String(int(r, 20, 400)), say: [(e, v) => `${e} has ${v} full-time employees.`, (e, v) => `${e}'s headcount is ${v} people.`] },
+ runway: { value: r => String(int(r, 6, 36)), say: [(e, v) => `${e} has ${v} months of cash runway.`, (e, v) => `${e}'s cash runway is ${v} months.`] },
+ hq: { value: r => pick(r, CITIES), say: [(e, v) => `${e} is headquartered in ${v}.`, (e, v) => `${e}'s headquarters are in ${v}.`] },
+ ceo: { value: r => pick(r, PEOPLE), say: [(e, v) => `The CEO of ${e} is ${v}.`, (e, v) => `${v} is the chief executive of ${e}.`] },
+ price: { value: r => `$${int(r, 8, 120)}`, say: [(e, v) => `${e}'s Pro plan costs ${v} per seat per month.`, (e, v) => `The Pro plan at ${e} is priced at ${v} per seat monthly.`] },
+ customers: { value: r => String(int(r, 15, 5000)), say: [(e, v) => `${e} serves ${v} paying customers.`, (e, v) => `${e} has ${v} paying customers.`] },
+ launch: { value: r => day(r), say: [(e, v) => `${e} plans to launch its mobile app on ${v}.`, (e, v) => `${e}'s mobile app launch is scheduled for ${v}.`] },
+ churn: { value: r => `${int(r, 1, 9)}.${int(r, 0, 9)}%`, say: [(e, v) => `${e}'s monthly logo churn is ${v}.`, (e, v) => `Monthly customer churn at ${e} is ${v}.`] },
+ nps: { value: r => String(int(r, 10, 80)), say: [(e, v) => `${e}'s net promoter score is ${v}.`, (e, v) => `${e} reports a net promoter score of ${v}.`] },
+};
+
+/** Coexisting claims: same template, different numbers or dates, all true at once. */
+const STAGES = ['pre-seed', 'seed', 'Series A', 'Series B', 'Series C', 'Series D'];
+const MULTI: Record<string, (r: Rand, e: string, i: number) => { member: string; fact: string }> = {
+ round: (r, e, i) => ({ member: STAGES[i], fact: `${e} raised a $${int(r, 1, 9) * (i + 1)}M ${STAGES[i]} round in ${2019 + i}.` }),
+ quarter: (r, e, i) => ({ member: `Q${(i % 4) + 1}-${2025 + Math.floor(i / 4)}`, fact: `${e}'s revenue in Q${(i % 4) + 1} ${2025 + Math.floor(i / 4)} was $${int(r, 1, 30)}.${int(r, 0, 9)}M.` }),
+ office: (r, e, i) => ({ member: CITIES[i], fact: `${e} opened an office in ${CITIES[i]} in ${2020 + i}.` }),
+ board: (r, e, i) => ({ member: `m${i}`, fact: `${e}'s board met on ${MONTHS[(i * 3) % 12]} ${int(r, 1, 28)}, ${2025 + Math.floor(i / 4)} to review the budget.` }),
+};
+
+export function buildFixture(seed = FIXTURE_SEED): Company[] {
+ const r = mulberry32(seed);
+ const companies: Company[] = [];
+ for (const [si, stem] of STEMS.entries()) {
+ for (const suffix of ['Labs', 'Works']) {
+ // Every fourth company is dense: all four coexisting families with many
+ // members and three private notes per claim, so the cosine top 5 is crowded.
+ const dense = (si * 2 + (suffix === 'Labs' ? 0 : 1)) % 4 === 0;
+ const name = `${stem} Example ${suffix}`;
+ const slug = `companies/${stem.toLowerCase()}-example-${suffix.toLowerCase()}`;
+ const seeds: Row[] = [];
+ const probes: Probe[] = [];
+ const families = shuffle(r, Object.keys(SINGLE));
+ const seeded = families.slice(0, 7);
+ const values = new Map<string, string>();
+ for (const f of seeded) {
+ const v = SINGLE[f].value(r);
+ values.set(f, v);
+ seeds.push({ key: `${slug}|${f}`, fact: SINGLE[f].say[0](name, v), visibility: 'world' });
+ }
+ // Private rows over world claims: a private copy and a private note.
+ for (const f of seeded.slice(0, 4)) {
+ const v = values.get(f)!;
+ seeds.push({ key: `${slug}|${f}|private-copy`, fact: SINGLE[f].say[1](name, v), visibility: 'private' });
+ seeds.push({ key: `${slug}|${f}|private-note`, fact: `Private note: ${SINGLE[f].say[0](name, v)}`, visibility: 'private' });
+ if (dense) {
+ seeds.push({ key: `${slug}|${f}|private-board-deck`, fact: `From the board deck (private): ${SINGLE[f].say[1](name, v)}`, visibility: 'private' });
+ seeds.push({ key: `${slug}|${f}|private-call`, fact: `Heard on a private call: ${SINGLE[f].say[0](name, SINGLE[f].value(r))}`, visibility: 'private' });
+ seeds.push({ key: `${slug}|${f}|private-draft`, fact: `Draft, do not share: ${SINGLE[f].say[0](name, SINGLE[f].value(r))}`, visibility: 'private' });
+ }
+ }
+ // One private-only claim.
+ const privFamily = seeded[6];
+ const privValue = SINGLE[privFamily].value(r);
+ seeds.push({ key: `${slug}|${privFamily}|private-only`, fact: `Internal estimate: ${SINGLE[privFamily].say[1](name, privValue)}`, visibility: 'private' });
+ // Coexisting claims: two families, members 0..n-1 seeded, the next one is a probe.
+ const multis = shuffle(r, Object.keys(MULTI)).slice(0, dense ? 4 : 2);
+ const multiNext: Array<{ family: string; i: number }> = [];
+ for (const m of multis) {
+ const n = dense ? int(r, 4, m === 'round' ? 5 : 8) : int(r, 2, 3);
+ for (let i = 0; i < n; i++) {
+ const c = MULTI[m](r, name, i);
+ seeds.push({ key: `${slug}|${m}|${c.member}`, fact: c.fact, visibility: 'world' });
+ }
+ multiNext.push({ family: m, i: n });
+ }
+ const newValue = (f: string) => { let v = SINGLE[f].value(r); while (v === values.get(f)) v = SINGLE[f].value(r); values.set(f, v); return v; };
+ for (const f of seeded.slice(0, 3)) probes.push({ kind: 'correction', key: `${slug}|${f}`, fact: SINGLE[f].say[int(r, 0, 1)](name, newValue(f)), visibility: 'world' });
+ probes.push({ kind: 'restatement', key: `${slug}|${seeded[3]}`, fact: SINGLE[seeded[3]].say[1](name, values.get(seeded[3])!), visibility: 'world' });
+ for (const _ of [0, 1]) probes.push({ kind: 'concurrent', key: `${slug}|${seeded[4]}`, fact: SINGLE[seeded[4]].say[int(r, 0, 1)](name, newValue(seeded[4])), visibility: 'world' });
+ let pv = SINGLE[privFamily].value(r);
+ while (pv === privValue) pv = SINGLE[privFamily].value(r);
+ probes.push({ kind: 'private_correction', key: `${slug}|${privFamily}|private-only`, fact: `Internal estimate: ${SINGLE[privFamily].say[0](name, pv)}`, visibility: 'private' });
+ for (const { family, i } of multiNext.slice(0, 2)) {
+ const c = MULTI[family](r, name, i);
+ probes.push({ kind: 'coexisting', key: `${slug}|${family}|${c.member}`, fact: c.fact, visibility: 'world' });
+ }
+ const fresh = families[7];
+ probes.push({ kind: 'new_claim', key: `${slug}|${fresh}`, fact: SINGLE[fresh].say[int(r, 0, 1)](name, SINGLE[fresh].value(r)), visibility: 'world' });
+ companies.push({ slug, dense, seeds, probes: shuffle(r, probes).sort((a, b) => Number(a.kind === 'concurrent') - Number(b.kind === 'concurrent')) });
+ }
+ }
+ return companies;
+}
+
+export function fixtureTexts(companies: Company[]): string[] {
+ return [...new Set(companies.flatMap(c => [...c.seeds, ...c.probes].map(x => x.fact)))].sort();
+}
+
+const sha256 = (s: string | Buffer) => createHash('sha256').update(s).digest('hex');
+
+// ---------------------------------------------------------------------------
+// Embeddings (int8 + per-vector scale, gzip JSON)
+// ---------------------------------------------------------------------------
+
+interface EmbeddingFile { model: string; dims: number; texts_sha256: string; vectors: Record<string, { s: number; q: string }> }
+
+function loadEmbeddings(path: string, texts: string[]): { model: string; dims: number; sha256: string; get(t: string): Float32Array } {
+ const raw = readFileSync(path);
+ const file = JSON.parse(gunzipSync(raw).toString('utf8')) as EmbeddingFile;
+ const expected = sha256(JSON.stringify(texts));
+ if (file.texts_sha256 !== expected) throw new Error(`Embeddings were made for another fixture (texts sha ${file.texts_sha256}, fixture ${expected}); re-run scripts/eval-c2-embed.py.`);
+ const cache = new Map<string, Float32Array>();
+ return {
+ model: file.model, dims: file.dims, sha256: sha256(raw),
+ get(t: string) {
+ const hit = cache.get(t);
+ if (hit) return hit;
+ const v = file.vectors[sha256(t)];
+ if (!v) throw new Error(`No embedding for fixture text: ${t}`);
+ const q = new Int8Array(Buffer.from(v.q, 'base64').buffer.slice(0));
+ const out = Float32Array.from(q, x => x * v.s);
+ cache.set(t, out);
+ return out;
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Replay
+// ---------------------------------------------------------------------------
+
+interface ProbeOutcome {
+ company: string; dense: boolean; kind: Probe['kind']; has_twin: boolean; twin_in_candidates: boolean;
+ status: 'inserted' | 'superseded' | 'duplicate'; outcome: 'correct' | 'missed' | 'false_supersession';
+ hit_key?: string; best_eligible_cosine: number | null; keyword_only_candidates: number;
+}
+interface ArmResult { probes: ProbeOutcome[]; preserved: Record<string, { claims: number; preserved: number }>; stale_claims: number; product_mismatches: number }
+
+async function replay(engineDims: number, model: string, emb: (t: string) => Float32Array, companies: Company[], mode: CandidateFusion, tau: number): Promise<ArmResult> {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.setConfig(CANDIDATE_FUSION_KEY, mode);
+ const keyOf = new Map<number, string>();
+ const established = new Map<string, Set<string>>();
+ const insert = async (c: Company, row: Row, supersedeId?: number) => {
+ const res = await engine.insertFact({ fact: row.fact, kind: 'fact', entity_slug: c.slug, visibility: row.visibility, source: SOURCE, embedding: emb(row.fact), embedding_model: model }, // gbrain-allow-direct-insert: offline eval seeds a throwaway in-memory PGLite brain
+ { source_id: 'default', ...(supersedeId ? { supersedeId } : {}) });
+ keyOf.set(res.id, row.key);
+ if (!established.has(c.slug)) established.set(c.slug, new Set());
+ established.get(c.slug)!.add(row.key);
+ };
+ for (const c of companies) for (const s of c.seeds) await insert(c, s);
+ const probes: ProbeOutcome[] = [];
+ let productMismatches = 0;
+ for (const c of companies) {
+ for (const p of c.probes) {
+ const e = emb(p.fact);
+ const active = await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM facts WHERE source_id='default' AND entity_slug=$1 AND visibility=$2 AND expired_at IS NULL`, [c.slug, p.visibility]);
+ const twins = new Set(active.map(a => Number(a.id)).filter(id => keyOf.get(id) === p.key));
+ const [exact] = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id='default' AND entity_slug=$1 AND visibility=$2
+ AND expired_at IS NULL AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3) ORDER BY id LIMIT 1`, [c.slug, p.visibility, p.fact]);
+ const candidates = await listSupersessionCandidates(engine, 'default', c.slug, p.fact, e, model, mode);
+ const cosineIds = new Set((await listSupersessionCandidates(engine, 'default', c.slug, p.fact, e, model, 'rrf_free')).map(x => x.id));
+ let bestId: number | null = null;
+ let score = -1;
+ for (const cand of candidates) {
+ if (!cand.embedding || cand.visibility !== p.visibility || cand.expired_at) continue;
+ const s = cosineSimilarity(e, cand.embedding);
+ if (s > score) { score = s; bestId = cand.id; }
+ }
+ const eligibleCosine = bestId === null ? null : score;
+ if (exact) bestId = Number(exact.id);
+ const status: ProbeOutcome['status'] = exact ? 'duplicate' : bestId !== null && score >= tau ? 'superseded' : 'inserted';
+ const hitId = status === 'inserted' ? null : bestId;
+ if (tau === EXPLICIT_DUPLICATE_THRESHOLD) {
+ const product = await decideSingleFact(engine, 'default', { fact: p.fact, kind: 'fact', visibility: p.visibility, entity_slug: c.slug }, e, model, SOURCE);
+ if (product.status !== status || (product.candidate?.id ?? null) !== hitId) productMismatches++;
+ }
+ const hitKey = hitId === null ? undefined : keyOf.get(hitId);
+ const outcome: ProbeOutcome['outcome'] = hitId === null
+ ? (twins.size > 0 ? 'missed' : 'correct')
+ : (twins.has(hitId) ? 'correct' : 'false_supersession');
+ probes.push({
+ company: c.slug, dense: c.dense, kind: p.kind, has_twin: twins.size > 0, twin_in_candidates: candidates.some(x => twins.has(x.id)), status, outcome,
+ ...(hitKey && outcome === 'false_supersession' ? { hit_key: hitKey.split('|').slice(1).join('|') } : {}),
+ best_eligible_cosine: eligibleCosine === null ? null : Math.round(eligibleCosine * 10_000) / 10_000,
+ keyword_only_candidates: candidates.filter(x => !cosineIds.has(x.id)).length,
+ });
+ if (status !== 'duplicate') await insert(c, p, status === 'superseded' ? hitId! : undefined);
+ }
+ }
+ const activeRows = await engine.executeRaw<{ id: number; entity_slug: string }>(`SELECT id, entity_slug FROM facts WHERE source_id='default' AND expired_at IS NULL`);
+ const activeKeys = new Map<string, number>();
+ for (const a of activeRows) { const k = keyOf.get(Number(a.id))!; activeKeys.set(k, (activeKeys.get(k) ?? 0) + 1); }
+ const preserved: ArmResult['preserved'] = {};
+ for (const [slug, keys] of established) preserved[slug] = { claims: keys.size, preserved: [...keys].filter(k => activeKeys.has(k)).length };
+ const staleClaims = [...activeKeys].filter(([k, n]) => n > 1 && Object.keys(SINGLE).includes(k.split('|')[1]) && k.split('|').length === 2).length;
+ await engine.disconnect();
+ return { probes, preserved, stale_claims: staleClaims, product_mismatches: productMismatches };
+}
+
+// ---------------------------------------------------------------------------
+// Statistics: paired by probe (or company), bootstrap over companies
+// ---------------------------------------------------------------------------
+
+interface Paired { cluster: string; a: number; b: number }
+
+function pairedStats(pairs: Paired[]) {
+ const st = pairedClusterStatistics(pairs.map(p => ({ cluster: p.cluster, baseline: p.a, candidate: p.b })), { seed: 42, draws: DRAWS });
+ return {
+ n_pairs: st.n, n_clusters: st.clusters, mean_a: st.baseline_mean, mean_b: st.candidate_mean, delta: st.delta,
+ ci95: [st.lower95, st.upper95] as [number, number], wins: st.wins, losses: st.losses, ties: st.ties,
+ p_two_sided: st.p_value, p_method: 'cluster-sign-flip',
+ };
+}
+
+type Gate = { id: string; metric: string; gate: 'superiority' | 'noninferiority' | 'exploratory'; direction: 'higher' | 'lower'; tolerance?: number; description: string };
+export const COMPARISONS: Gate[] = [
+ { id: 'twin-recall-at-5', metric: 'twin_recall_at_5', gate: 'superiority', direction: 'higher', description: 'probes whose claim has an active row: that row is in the scored candidate set (k = 5)' },
+ { id: 'false-supersession', metric: 'false_supersession_rate', gate: 'noninferiority', direction: 'lower', tolerance: 0.005, description: 'probes whose decision replaced or deduplicated a row of a different claim' },
+ { id: 'preserved-distinct-claims', metric: 'preserved_distinct_share', gate: 'noninferiority', direction: 'higher', tolerance: 0.005, description: 'per company: share of every claim ever established that still has an active row after the replay' },
+ { id: 'correct-decision', metric: 'correct_decision_rate', gate: 'exploratory', direction: 'higher', description: 'probes decided as the fixture expects (twin replaced, distinct claim inserted)' },
+];
+
+function judge(g: Gate, stats: ReturnType<typeof pairedStats>): 'pass' | 'fail' | 'inconclusive' | 'exploratory' {
+ if (g.gate === 'exploratory') return 'exploratory';
+ const [lo, hi] = stats.ci95;
+ if (g.gate === 'superiority') {
+ const better = g.direction === 'higher' ? lo > 0 : hi < 0;
+ const worse = g.direction === 'higher' ? hi < 0 : lo > 0;
+ return better ? 'pass' : worse ? 'fail' : 'inconclusive';
+ }
+ const tol = g.tolerance ?? 0;
+ const ok = g.direction === 'higher' ? lo >= -tol : hi <= tol;
+ const bad = g.direction === 'higher' ? hi < -tol : lo > tol;
+ return ok ? 'pass' : bad ? 'fail' : 'inconclusive';
+}
+
+async function run(embeddingsPath: string, outDir: string | null): Promise<void> {
+ const companies = buildFixture();
+ const texts = fixtureTexts(companies);
+ const store = loadEmbeddings(embeddingsPath, texts);
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: store.dims, env: { OPENAI_API_KEY: 'sk-offline-c2-eval-no-network' } });
+ const model = `local:${store.model}`;
+ const sources: unknown[] = [];
+ const summary: Record<string, unknown> = {};
+ const allVerdicts: string[] = [];
+ for (const tau of TAUS) {
+ const arms = {} as Record<CandidateFusion, ArmResult>;
+ for (const mode of MODES) arms[mode] = await replay(store.dims, model, t => store.get(t), companies, mode, tau);
+ const A = arms.rrf_free;
+ const B = arms.interleave;
+ const pairsFor = (pick: (o: ProbeOutcome) => number | null): Paired[] => A.probes.flatMap((a, i) => {
+ const xa = pick(a); const xb = pick(B.probes[i]);
+ return xa === null || xb === null ? [] : [{ cluster: a.company, a: xa, b: xb }];
+ });
+ const metricPairs: Record<string, Paired[]> = {
+ // Only probes where both arms had an active twin when the probe arrived.
+ twin_recall_at_5: A.probes.flatMap((a, i) => a.has_twin && B.probes[i].has_twin ? [{ cluster: a.company, a: Number(a.twin_in_candidates), b: Number(B.probes[i].twin_in_candidates) }] : []),
+ false_supersession_rate: pairsFor(o => Number(o.outcome === 'false_supersession')),
+ correct_decision_rate: pairsFor(o => Number(o.outcome === 'correct')),
+ preserved_distinct_share: Object.keys(A.preserved).map(slug => ({ cluster: slug, a: A.preserved[slug].preserved / A.preserved[slug].claims, b: B.preserved[slug].preserved / B.preserved[slug].claims })),
+ };
+ const stats = COMPARISONS.map(g => pairedStats(metricPairs[g.metric]));
+ const holm = holmAdjusted(stats.map(st => st.p_two_sided));
+ const comparisons = COMPARISONS.map((g, i) => ({ ...g, status: judge(g, stats[i]), stats: stats[i], p_holm: holm[i] }));
+ const gated = comparisons.filter(c => c.gate !== 'exploratory');
+ const verdict = gated.some(c => c.status === 'fail') ? 'fail' : gated.every(c => c.status === 'pass') ? 'pass' : 'inconclusive';
+ allVerdicts.push(verdict);
+ const byKind = (arm: ArmResult) => Object.fromEntries([...new Set(arm.probes.map(p => p.kind))].map(k => {
+ const ps = arm.probes.filter(p => p.kind === k);
+ return [k, { n: ps.length, correct: ps.filter(p => p.outcome === 'correct').length, missed: ps.filter(p => p.outcome === 'missed').length,
+ false_supersession: ps.filter(p => p.outcome === 'false_supersession').length, twin_in_candidates: ps.filter(p => p.has_twin && p.twin_in_candidates).length,
+ with_twin: ps.filter(p => p.has_twin).length }];
+ }));
+ const falseHits = (arm: ArmResult) => arm.probes.filter(p => p.outcome === 'false_supersession').map(p => `${p.kind}->${p.hit_key}`);
+ sources.push({
+ source: `c2-twin-fixture-tau-${tau}`, verdict, threshold: tau,
+ arms: { baseline: { config: { [CANDIDATE_FUSION_KEY]: 'rrf_free' } }, candidate: { config: { [CANDIDATE_FUSION_KEY]: 'interleave' } } },
+ family: { family_id: `c2-interleave-dev:tau-${tau}`, verdict, alpha: 0.05, comparisons },
+ diagnostics: {
+ by_kind: { rrf_free: byKind(A), interleave: byKind(B) },
+ false_supersession_hits: { rrf_free: falseHits(A), interleave: falseHits(B) },
+ stale_single_value_claims_at_end: { rrf_free: A.stale_claims, interleave: B.stale_claims },
+ probes_with_keyword_only_candidates: B.probes.filter(p => p.keyword_only_candidates > 0).length,
+ twin_recall_by_slice: Object.fromEntries((['dense', 'standard'] as const).map(slice => [slice, Object.fromEntries((['rrf_free', 'interleave'] as const).map(m => {
+ const ps = arms[m].probes.filter(p => p.has_twin && p.dense === (slice === 'dense'));
+ return [m, { with_twin: ps.length, twin_in_candidates: ps.filter(p => p.twin_in_candidates).length }];
+ }))])),
+ product_decide_mismatches: tau === EXPLICIT_DUPLICATE_THRESHOLD ? { rrf_free: A.product_mismatches, interleave: B.product_mismatches } : null,
+ },
+ });
+ summary[String(tau)] = Object.fromEntries(comparisons.map(c => [c.id, { a: round(c.stats.mean_a), b: round(c.stats.mean_b), delta: round(c.stats.delta), ci95: c.stats.ci95.map(round), status: c.status }]));
+ }
+ const overall = allVerdicts.includes('fail') ? 'fail' : allVerdicts.every(v => v === 'pass') ? 'pass' : 'inconclusive';
+ const fixture = {
+ seed: FIXTURE_SEED, companies: companies.length, seeded_rows: companies.reduce((n, c) => n + c.seeds.length, 0),
+ probes: companies.reduce((n, c) => n + c.probes.length, 0), texts: texts.length, texts_sha256: sha256(JSON.stringify(texts)),
+ embedding_model: store.model, embedding_dims: store.dims, embeddings_sha256: store.sha256, candidate_k: SUPERSESSION_CANDIDATE_K,
+ gbrain_git_head: Bun.spawnSync(['git', 'rev-parse', 'HEAD']).stdout.toString().trim() || null,
+ gbrain_tree_dirty: Bun.spawnSync(['git', 'status', '--porcelain', '--', 'src']).stdout.toString().trim() !== '',
+ };
+ const decidedAt = new Date().toISOString();
+ const verdictJson = {
+ decision_id: 'c2-interleave-dev', plan: 'MEMORY_PROOF_WAVE C2', stage: 'dev', eligible_for_default: false,
+ eligibility_note: 'Dev verdict on a synthetic, offline fixture with a local embedding model; it cannot set a default. The parent wave decides facts.candidate_fusion.',
+ verdict_type: 'quality', overall, decided_at: decidedAt, fixture, sources,
+ };
+ console.log(JSON.stringify({ overall, fixture, summary }, null, 2));
+ if (!outDir) return;
+ mkdirSync(outDir, { recursive: true });
+ writeFileSync(join(outDir, 'verdict.json'), JSON.stringify(verdictJson, null, 2) + '\n');
+}
+
+const round = (x: number) => Math.round(x * 10_000) / 10_000;
+
+if (import.meta.main) {
+ const [cmd, ...rest] = process.argv.slice(2);
+ if (cmd === 'texts') {
+ const texts = fixtureTexts(buildFixture());
+ console.log(JSON.stringify({ texts_sha256: sha256(JSON.stringify(texts)), texts }));
+ } else if (cmd === 'run') {
+ const arg = (flag: string) => { const i = rest.indexOf(flag); return i >= 0 ? rest[i + 1] : null; };
+ const embeddings = arg('--embeddings');
+ if (!embeddings) { console.error('run needs --embeddings <file> (make it with scripts/eval-c2-embed.py)'); process.exit(2); }
+ await run(embeddings, arg('--out'));
+ } else {
+ console.error('usage: bun scripts/eval-c2-candidate-fusion.ts texts | run --embeddings <file> [--out <dir>]');
+ process.exit(2);
+ }
+}
diff --git a/scripts/eval-c2-embed.py b/scripts/eval-c2-embed.py
new file mode 100644
index 0000000000..39dde3af21
--- /dev/null
+++ b/scripts/eval-c2-embed.py
@@ -0,0 +1,31 @@
+"""Embed the C2 candidate-fusion fixture texts with a free local model (no API key, no spend).
+
+usage: python3 scripts/eval-c2-embed.py <texts.json> <out.json.gz>
+
+<texts.json> is the output of `bun scripts/eval-c2-candidate-fusion.ts texts`. Vectors are
+L2-normalized, then stored as int8 with a per-vector scale, keyed by sha256(text). Requires
+`pip install fastembed==0.8.1` (ONNX runtime; downloads the model once).
+"""
+import base64, gzip, hashlib, json, sys
+
+import numpy as np
+from fastembed import TextEmbedding
+
+MODEL = "BAAI/bge-small-en-v1.5"
+
+def main(src: str, dst: str) -> None:
+ spec = json.load(open(src))
+ texts = spec["texts"]
+ vecs = np.array(list(TextEmbedding(MODEL).embed(texts)), dtype=np.float32)
+ vecs /= np.linalg.norm(vecs, axis=1, keepdims=True)
+ out = {}
+ for text, v in zip(texts, vecs):
+ scale = float(np.abs(v).max()) / 127.0
+ q = np.clip(np.round(v / scale), -127, 127).astype(np.int8)
+ out[hashlib.sha256(text.encode()).hexdigest()] = {"s": scale, "q": base64.b64encode(q.tobytes()).decode()}
+ payload = {"model": MODEL, "dims": int(vecs.shape[1]), "texts_sha256": spec["texts_sha256"], "vectors": out}
+ with gzip.GzipFile(dst, "wb", mtime=0) as f:
+ f.write(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode())
+
+if __name__ == "__main__":
+ main(sys.argv[1], sys.argv[2])
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 42088aa42c..b383e46408 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,7 +16,7 @@ src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3224 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); 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; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224)
src/core/cycle/synthesize.ts 3311 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); 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 wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict)
src/core/cycle/extract-atoms.ts 1808 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 integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
-src/core/engine.ts 2678 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 contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
+src/core/engine.ts 2679 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 contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion)
src/core/import-file.ts 2178 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 anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1838 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured)
+src/core/config.ts 1840 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)
diff --git a/src/core/config.ts b/src/core/config.ts
index e41834bb88..24ceaecb9e 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1362,6 +1362,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.return_budget_default',
'search.return_budget_conversation',
'search.return_budget_max_remote',
+ 'search.evidence_date_header', // C1: one-line date header per delivered block (default off; search/evidence-date.ts)
'think.return_unit',
// Models tier system (v0.31.12)
'models.default',
@@ -1424,6 +1425,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// src/core/facts/visibility.ts; explicit caller values always win.
'facts.default_visibility',
'facts.entity_inference', // #5836: write-time subject inference kill switch (subject-infer.ts)
+ 'facts.candidate_fusion', // C2: 'rrf_free' (default, cosine arm) | 'interleave' (cosine + keyword; facts/single-prepare.ts)
// Ambient memory writeback (opt-in, default OFF): 'off' | 'salient' | 'all'.
// DUAL-PLANE: `gbrain config set` writes the DB plane (authoritative — the
// serve-side harvest gate re-checks it) AND mirrors into the file plane's
diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.ts
index 21d7426ed6..af6824a7bb 100644
--- a/src/core/engine-sql/facts.ts
+++ b/src/core/engine-sql/facts.ts
@@ -22,6 +22,7 @@ import { tryParseEmbedding } from '../utils.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
import { resolveSupersededByRow, isInt4RowRef, supersessionChainOf, type SupersedeTarget } from '../facts/supersede-resolve.ts';
import { escapeLikePattern } from '../cjk.ts';
+import { getFtsLanguage } from '../fts-language.ts';
import type { SqlExecutor } from './executor.ts';
import type { LegacyUnscopedRead } from './brands.ts';
import { sqlFragment, trustedSql } from './fragment.ts';
@@ -480,11 +481,12 @@ export async function findCandidateDuplicates(
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; arm?: 'keyword' },
): Promise<FactRow[]> {
const k = Math.min(Math.max(opts?.k ?? 5, 1), 20);
// Validity-lapsed rows are not dedup candidates: a re-stated fact after
// its valid_until lapses re-inserts fresh (WP5 read-time TTL honesty).
+ if (opts?.arm === 'keyword') return findKeywordCandidates(exec, source_id, entitySlug, factText, k, opts);
if (opts?.embedding) {
if (!opts.embeddingModel) return [];
const lit = toPgVectorLiteral(opts.embedding);
@@ -515,6 +517,42 @@ export async function findCandidateDuplicates(
return rows.map(rowToFact);
}
+/**
+ * The keyword arm of fact supersession candidates (C2, `facts.candidate_fusion
+ * = interleave`): the same entity bucket and active-row filters as the cosine
+ * arm, ranked by `ts_rank_cd` against an OR of the new claim's lexemes, so a
+ * twin whose wording changed only in a number or date still ranks by its
+ * shared terms. With an embedding it keeps the cosine arm's comparability
+ * filters (same model, current text hash, same dimensions), so every row it
+ * returns can be scored by the caller's cosine decision. Per-row tsvector over
+ * one entity's facts: no index is needed at k <= 20.
+ */
+async function findKeywordCandidates(
+ exec: LegacyUnscopedRead, source_id: string, entitySlug: string, factText: string, k: number,
+ opts: { embedding?: Float32Array; embeddingModel?: string | null },
+): Promise<FactRow[]> {
+ if (opts.embedding && !opts.embeddingModel) return [];
+ const lang = getFtsLanguage();
+ const comparable = opts.embedding
+ ? sqlFragment`AND embedding IS NOT NULL AND embedding_model=${opts.embeddingModel} AND embedded_text_hash=md5(fact)
+ AND vector_dims(embedding)=${opts.embedding.length}`
+ : sqlFragment``;
+ const rows = (await exec.run<FactRowSqlShape>(sqlFragment`
+ WITH q AS (SELECT NULLIF(replace(plainto_tsquery(${lang}::regconfig, ${factText})::text, ' & ', ' | '), '')::tsquery AS q)
+ SELECT f.* FROM facts f, q
+ WHERE f.source_id = ${source_id}
+ AND f.entity_slug = ${entitySlug}
+ AND f.expired_at IS NULL
+ AND (f.valid_until IS NULL OR f.valid_until > now())
+ AND f.source != ALL(${AUDIT_ROW_SOURCES}::text[])
+ ${comparable}
+ AND q.q IS NOT NULL AND to_tsvector(${lang}::regconfig, f.fact) @@ q.q
+ ORDER BY ts_rank_cd(to_tsvector(${lang}::regconfig, f.fact), q.q) DESC, f.created_at DESC, f.id DESC
+ LIMIT ${k}
+ `)).rows;
+ return rows.map(rowToFact);
+}
+
export async function consolidateFact(exec: SqlExecutor, id: number, takeId: number): Promise<void> {
(await exec.run(sqlFragment`UPDATE facts SET consolidated_at = now(), consolidated_into = ${takeId} WHERE id = ${id}`)).rows;
}
diff --git a/src/core/engine.ts b/src/core/engine.ts
index f946f3a2dd..484b96bb9a 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -2230,13 +2230,14 @@ export interface BrainEngine {
* Find candidate duplicates for a new fact within a source+entity bucket.
* Entity-prefilter is mandatory (bounds the contradiction-classifier blast
* radius). Hard cap k=5 by default. Embedding-cosine when both sides have
- * embeddings; recency fallback otherwise.
+ * embeddings; recency fallback otherwise. `arm: 'keyword'` ranks the same
+ * bucket by full-text rank instead (C2 `facts.candidate_fusion`).
*/
findCandidateDuplicates(
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; arm?: 'keyword' },
): Promise<FactRow[]>;
/**
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index 2fd0d3a5b9..8f8d25bc80 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -4,6 +4,7 @@ import { isAvailable, embedOne, getEmbeddingModel } from '../ai/gateway.ts';
import { cosineSimilarity } from './classify.ts';
import { isFactWithdrawn } from './withdrawal.ts';
import { cosineVerdict } from './capture-dedup.ts';
+import { interleaveFusion } from '../search/fusion-lists.ts';
export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };
export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }
@@ -27,6 +28,34 @@ export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: stri
'Remember a corrected claim. Repeating the old claim does not restore withdrawn memory.');
}
}
+export const CANDIDATE_FUSION_KEY = 'facts.candidate_fusion';
+export type CandidateFusion = 'rrf_free' | 'interleave';
+/** Candidates the supersession decision scores; the cap bounds the blast radius. */
+export const SUPERSESSION_CANDIDATE_K = 5;
+
+/** `facts.candidate_fusion`: `rrf_free` (default) is the single cosine arm; unknown values read as the default. */
+export async function readCandidateFusion(engine: BrainEngine): Promise<CandidateFusion> {
+ try {
+ const raw = (await engine.getConfig(CANDIDATE_FUSION_KEY))?.trim();
+ return raw === 'interleave' ? 'interleave' : 'rrf_free';
+ } catch {
+ return 'rrf_free';
+ }
+}
+
+/**
+ * The supersession candidate set for one claim: the cosine arm's top k, or
+ * under `interleave` the cosine and keyword arms merged round-robin by fact id
+ * and cut to the same k, so the decision still scores at most k rows.
+ */
+export async function listSupersessionCandidates(engine: BrainEngine, sourceId: string, entitySlug: string, fact: string, embedding: Float32Array, embeddingModel?: string | null, fusion?: CandidateFusion): Promise<FactRow[]> {
+ const k = SUPERSESSION_CANDIDATE_K;
+ const cosine = await engine.findCandidateDuplicates(sourceId, entitySlug, fact, { embedding, embeddingModel, k });
+ if ((fusion ?? await readCandidateFusion(engine)) !== 'interleave') return cosine;
+ const keyword = await engine.findCandidateDuplicates(sourceId, entitySlug, fact, { embedding, embeddingModel, k, arm: 'keyword' });
+ return interleaveFusion([cosine, keyword], row => row.id, k);
+}
+
/**
* SQL-only, so publication can verify the semantic decision under its guard.
* `lane` is the writer's `facts.source`: capture lanes never drop by cosine (#5888).
@@ -38,7 +67,7 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in
ORDER BY id LIMIT 1`, [sourceId, input.entity_slug, input.visibility, input.fact]);
if (exact) return { status: 'duplicate', candidate: { ...exact, id: Number(exact.id) } };
if (embedding && input.entity_slug) {
- const candidates = await engine.findCandidateDuplicates(sourceId, input.entity_slug, input.fact, { embedding, embeddingModel, k: 5 });
+ const candidates = await listSupersessionCandidates(engine, sourceId, input.entity_slug, input.fact, embedding, embeddingModel);
const metadata = await engine.executeRaw<{ id: number; source_markdown_slug: string | null; row_num: number | null }>(
'SELECT id,source_markdown_slug,row_num FROM facts WHERE source_id=$1 AND id=ANY($2::int[])',
[sourceId, candidates.map(c => c.id)]);
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index e44dab633b..1eab49e337 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -1,5 +1,6 @@
import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';
import { deliverEvidence, effectivePlan, resolveEvidencePlan, type DeliveryMeta, type EvidencePlan } from '../search/evidence-delivery.ts';
+import { withFactDateHeaders } from '../search/evidence-date.ts';
import { randomUUID } from 'node:crypto';
import { readHolders } from './context.ts';
/**
@@ -515,7 +516,7 @@ const recall: Operation = {
: undefined;
return {
- facts: packedFacts.map(r => ({
+ facts: await withFactDateHeaders(ctx.engine, packedFacts.map(r => ({
id: r.id,
fact: r.fact,
kind: r.kind,
@@ -545,7 +546,7 @@ const recall: Operation = {
// is the protocol name for the stored source attribution.
fact_id: String(r.id),
provenance: r.source,
- })),
+ }))),
total: packedFacts.length,
...(ambiguousEntity ? { ambiguous_entity: { candidates: ambiguousEntity, suggestion: AMBIGUOUS_ENTITY_SUGGESTION } } : {}),
...(pending_consolidation_count !== undefined ? { pending_consolidation_count } : {}),
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 138e0e292e..dee815ca8e 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2376,7 +2376,7 @@ export class PGLiteEngine implements BrainEngine {
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; arm?: 'keyword' },
): Promise<FactRow[]> {
return factsImpl.findCandidateDuplicates(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, entitySlug, factText, opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index dcf4cff626..ef92c83c69 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2155,7 +2155,7 @@ export class PostgresEngine implements BrainEngine {
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; arm?: 'keyword' },
): Promise<FactRow[]> {
return factsImpl.findCandidateDuplicates(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, entitySlug, factText, opts);
}
diff --git a/src/core/search/evidence-date.ts b/src/core/search/evidence-date.ts
new file mode 100644
index 0000000000..9c9ece9dd1
--- /dev/null
+++ b/src/core/search/evidence-date.ts
@@ -0,0 +1,123 @@
+/**
+ * Dated evidence blocks (C1, `search.evidence_date_header`): the one-line
+ * date header evidence delivery puts at the top of every delivered block, and
+ * the day formatter it shares with think's page dates.
+ *
+ * Header grammar (fixed, one line, parsed by agents and eval harnesses):
+ *
+ * page block: [observed 2026-03-05]
+ * fact: [observed unknown; valid 2026-03-01 to unknown]
+ *
+ * Each date is YYYY-MM-DD or the literal `unknown`. `observed` is when the
+ * source text was written or said (date grounding's observation time,
+ * #6020): the page's filename/slug date,
+ * frontmatter `date`, `published` or a created key, in effective-date
+ * precedence with `event_date` removed. An event date is when something
+ * happened, not when the note was written, and row timestamps are when GBrain
+ * stored it, so neither is ever shown as observed. Facts carry no observation
+ * date on master, so a fact's `observed` is `unknown` and its validity window
+ * (`valid_from` to `valid_until`, an open end shown as `unknown`) follows.
+ *
+ * Seam: `pageObservationDate` mirrors `resolveObservationDate` from
+ * src/core/ai/date-grounding.ts (#6020); once that lands, call it here
+ * instead. `formatBrainDay` is the rendering rule think's `<page date>`
+ * attribute uses, so both surfaces print the same day.
+ */
+import { computeEffectiveDate, isValidTimeZone } from '../effective-date.ts';
+
+export const EVIDENCE_DATE_HEADER_KEY = 'search.evidence_date_header';
+export const UNKNOWN_DATE = 'unknown';
+
+const OBSERVATION_SOURCES = new Set(['filename', 'date', 'published', 'created']);
+
+/**
+ * YYYY-MM-DD for a stored instant: exactly midnight UTC is a day-only date
+ * and renders as written; any other instant renders in `timeZone`
+ * (`brain.timezone`; UTC when unset or invalid). Null for a missing or
+ * invalid value.
+ */
+export function formatBrainDay(value: Date | string | null | undefined, timeZone?: string | null): string | null {
+ if (value === null || value === undefined || value === '') return null;
+ const d = value instanceof Date ? value : new Date(value);
+ if (!Number.isFinite(d.getTime())) return null;
+ const iso = d.toISOString();
+ if (iso.endsWith('T00:00:00.000Z')) return iso.slice(0, 10);
+ const zone = timeZone && isValidTimeZone(timeZone) ? timeZone : 'UTC';
+ return new Intl.DateTimeFormat('en-CA', { timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(d);
+}
+
+/** When the page's text was written or said; null when it states no such date. Never a row timestamp. */
+export function pageObservationDate(page: {
+ slug: string;
+ frontmatter?: Record<string, unknown> | null;
+ filename?: string | null;
+ timeZone?: string | null;
+}): Date | null {
+ const { event_date: _eventDate, ...frontmatter } = page.frontmatter ?? {};
+ const invalid = new Date(Number.NaN);
+ const result = computeEffectiveDate({
+ slug: page.slug,
+ frontmatter,
+ filename: page.filename ?? page.slug.split('/').pop() ?? null,
+ timeZone: page.timeZone ?? undefined,
+ createdAt: invalid,
+ updatedAt: invalid,
+ });
+ return result.date && result.source && OBSERVATION_SOURCES.has(result.source) ? result.date : null;
+}
+
+export function pageDateHeader(observed: string | null): string {
+ return `[observed ${observed ?? UNKNOWN_DATE}]`;
+}
+
+export function factDateHeader(
+ fact: { valid_from?: Date | string | null; valid_until?: Date | string | null },
+ timeZone?: string | null,
+): string {
+ const from = formatBrainDay(fact.valid_from, timeZone) ?? UNKNOWN_DATE;
+ const until = formatBrainDay(fact.valid_until, timeZone) ?? UNKNOWN_DATE;
+ return `[observed ${UNKNOWN_DATE}; valid ${from} to ${until}]`;
+}
+
+/**
+ * The page header for each page id: one read of the stored frontmatter and
+ * import filename (only the derived day leaves this function) plus
+ * `brain.timezone`. Ids missing from the result render `unknown`.
+ */
+export async function loadPageDateHeaders(
+ engine: { executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]>; getConfig(key: string): Promise<string | null> },
+ pageIds: number[],
+): Promise<Map<number, string>> {
+ const out = new Map<number, string>();
+ const ids = [...new Set(pageIds.filter(id => Number.isInteger(id) && id > 0))];
+ if (ids.length === 0) return out;
+ const timeZone = (await engine.getConfig('brain.timezone').catch(() => null))?.trim() || null;
+ const rows = await engine.executeRaw<{ id: number; slug: string; frontmatter: unknown; import_filename: string | null }>(
+ 'SELECT id, slug, frontmatter, import_filename FROM pages WHERE id = ANY($1::int[])', [ids]);
+ for (const r of rows) {
+ const fm = typeof r.frontmatter === 'string' ? JSON.parse(r.frontmatter) : r.frontmatter;
+ const observed = pageObservationDate({ slug: String(r.slug), frontmatter: fm && typeof fm === 'object' ? fm as Record<string, unknown> : null, filename: r.import_filename, timeZone });
+ out.set(Number(r.id), pageDateHeader(formatBrainDay(observed, timeZone)));
+ }
+ return out;
+}
+
+/** `recall` fact rows plus `date_header` when `search.evidence_date_header` is on; unchanged otherwise. */
+export async function withFactDateHeaders<T extends { valid_from: string | null; valid_until: string | null }>(
+ engine: { getConfig(key: string): Promise<string | null> },
+ facts: T[],
+): Promise<Array<T & { date_header?: string }>> {
+ if (!await evidenceDateHeaderEnabled(engine)) return facts;
+ const timeZone = (await engine.getConfig('brain.timezone').catch(() => null))?.trim() || null;
+ return facts.map(f => ({ ...f, date_header: factDateHeader(f, timeZone) }));
+}
+
+/** `search.evidence_date_header` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */
+export async function evidenceDateHeaderEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
+ try {
+ const raw = (await engine.getConfig(EVIDENCE_DATE_HEADER_KEY))?.trim().toLowerCase();
+ return raw === 'true' || raw === 'on' || raw === '1' || raw === 'yes';
+ } catch {
+ return false;
+ }
+}
diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.ts
index 8cfd4cbdcb..7bd44f5f55 100644
--- a/src/core/search/evidence-delivery.ts
+++ b/src/core/search/evidence-delivery.ts
@@ -34,6 +34,7 @@ import { sanitizeRemoteBody } from '../remote-body.ts';
import { credentialSafeProjection } from '../credential-projection.ts';
import { stripChunkHeader } from '../chunkers/code.ts';
import { OperationError } from '../ops/contract.ts';
+import { evidenceDateHeaderEnabled, loadPageDateHeaders, pageDateHeader } from './evidence-date.ts';
export const RETURN_UNITS = ['chunk', 'window', 'section', 'page', 'auto'] as const;
export type ReturnUnit = typeof RETURN_UNITS[number];
@@ -96,6 +97,8 @@ export interface DeliveryMeta {
dropped_reasons: Record<string, number>;
fallbacks: string[];
budget_clamped?: { requested: number; max: number };
+ /** Present (true) when every block starts with its one-line date header (`search.evidence_date_header`). */
+ date_header?: true;
}
export type DeliveredSearchResult = SearchResult & { delivered: DeliveredEvidence };
@@ -108,6 +111,8 @@ export interface EvidencePlan {
/** return_unit came from the call, not config (snippet precedence). */
explicitUnit: boolean;
budgetClamped?: { requested: number; max: number };
+ /** `search.evidence_date_header` is on: each block starts with its date header line. */
+ dateHeader?: true;
}
export interface DeliveryScope extends PageReadScope {
@@ -226,6 +231,7 @@ export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePla
budgetTokens: budget,
explicitUnit: explicit !== undefined,
...(budgetClamped ? { budgetClamped } : {}),
+ ...(await evidenceDateHeaderEnabled(engine) ? { dateHeader: true as const } : {}),
};
}
@@ -479,6 +485,9 @@ interface Block {
revision?: string;
fallbackReason?: string;
titleTok: number;
+ /** The date header line plus its newline ('' when off), counted in the block's floor. */
+ header: string;
+ headerTok: number;
selected: Set<number>;
cut: boolean;
title: string;
@@ -487,7 +496,7 @@ interface Block {
reason?: AutoReason;
}
-type PlannedBlock = Omit<Block, 'titleTok' | 'title' | 'rank' | 'reason'>;
+type PlannedBlock = Omit<Block, 'titleTok' | 'title' | 'rank' | 'reason' | 'header' | 'headerTok'>;
/**
* The hit's text as it appears in the page: a fenced_code chunk carries the
@@ -684,7 +693,7 @@ function allocate(blocks: Block[], budget: number, tokenizer: 'cl100k' | 'heuris
let droppedAny = false;
for (const b of blocks) {
const core = b.anchors[0]?.pieces ?? [];
- const floor = b.titleTok + core.reduce((n, i) => n + tok(b, i, tokenizer), 0);
+ const floor = b.titleTok + b.headerTok + core.reduce((n, i) => n + tok(b, i, tokenizer), 0);
const floorChars = core.reduce((n, i) => n + b.doc.pieces[i].text.length, 0);
if (floor <= remaining && floorChars <= EVIDENCE_BLOCK_CHAR_CAP) {
for (const i of core) b.selected.add(i);
@@ -695,6 +704,7 @@ function allocate(blocks: Block[], budget: number, tokenizer: 'cl100k' | 'heuris
if (spill) { spill(b); continue; }
if (kept.length === 0 && !droppedAny) {
// Rank one alone exceeds the budget: cut it to fit (minKeep).
+ remaining = Math.max(0, remaining - b.headerTok);
if (b.titleTok > remaining) {
b.title = sliceToTokenCount(b.title, remaining, tokenizer);
b.titleTok = countEvidenceTokens(b.title, tokenizer);
@@ -873,6 +883,19 @@ export async function deliverEvidence(
}
}
+ // C1 date headers: one line per block, read for every hit page (passthrough
+ // rows included) and paid for inside the budget like the title.
+ let dateHeaders: Map<number, string> | null = null;
+ if (plan.dateHeader) {
+ try {
+ dateHeaders = await loadPageDateHeaders(engine, hits.map(h => h.page_id));
+ } catch {
+ dateHeaders = new Map();
+ fallbacks.add('date_header_unavailable');
+ }
+ }
+ const headerFor = (hit: SearchResult): string => dateHeaders ? `${dateHeaders.get(hit.page_id) ?? pageDateHeader(null)}\n` : '';
+
const planned: Block[] = [];
for (const g of groups) {
let b: PlannedBlock;
@@ -888,12 +911,13 @@ export async function deliverEvidence(
}
if (b.fallbackReason) fallbacks.add(b.fallbackReason);
const title = b.hit.title ?? '';
- planned.push({ ...b, title, titleTok: countEvidenceTokens(title, tokenizer), rank: g.rank, ...(g.reason ? { reason: g.reason } : {}) });
+ const header = headerFor(b.hit);
+ planned.push({ ...b, title, titleTok: countEvidenceTokens(title, tokenizer), header, headerTok: countEvidenceTokens(header, tokenizer), rank: g.rank, ...(g.reason ? { reason: g.reason } : {}) });
}
// Unchanged chunks are paid for first; conversations share the rest, and one
// whose matching span no longer fits keeps its ranked chunks instead.
- const reserved = passthrough.reduce((n, p) => n + countEvidenceTokens(p.hit.chunk_text ?? '', tokenizer) + countEvidenceTokens(p.hit.title ?? '', tokenizer), 0);
+ const reserved = passthrough.reduce((n, p) => n + countEvidenceTokens(headerFor(p.hit) + (p.hit.chunk_text ?? ''), tokenizer) + countEvidenceTokens(p.hit.title ?? '', tokenizer), 0);
const kept = allocate(planned, Math.max(0, plan.budgetTokens - reserved), tokenizer, dropped, auto
? b => { for (const h of b.hits) passthrough.push({ rank: hits.indexOf(h), hit: h, reason: 'conversation_over_budget' }); }
: undefined);
@@ -903,15 +927,15 @@ export async function deliverEvidence(
const delivered: DeliveredEvidence = {
unit: b.unit,
chunk_ids: b.hits.map(h => h.chunk_id),
- match_spans: out.spans,
- tokens: out.tokens,
+ match_spans: out.spans.map(sp => ({ ...sp, start: sp.start + b.header.length, end: sp.end + b.header.length })),
+ tokens: out.tokens + b.headerTok,
truncated,
...(b.revision ? { revision: b.revision } : {}),
...(out.unmapped.length > 0 ? { unmapped_chunk_ids: out.unmapped } : {}),
...(b.fallbackReason && b.unit === 'chunk' ? { fallback_reason: b.fallbackReason } : {}),
...(b.reason ? { reason: b.reason } : {}),
};
- return { ...b.hit, title: b.title, chunk_text: out.text, delivered };
+ return { ...b.hit, title: b.title, chunk_text: b.header + out.text, delivered };
});
// Budget after redaction: blocks pass through the same secret redaction as
@@ -944,11 +968,12 @@ export async function deliverEvidence(
if (passthrough.length > 0) {
const ranked = results.map((r, i) => ({ rank: kept[i].rank, r }));
for (const p of passthrough) {
- const text = p.hit.chunk_text ?? '';
- ranked.push({ rank: p.rank, r: { ...p.hit, delivered: {
+ const header = headerFor(p.hit);
+ const text = header + (p.hit.chunk_text ?? '');
+ ranked.push({ rank: p.rank, r: { ...p.hit, chunk_text: text, delivered: {
unit: 'chunk',
chunk_ids: [p.hit.chunk_id],
- match_spans: text.length > 0 ? [{ chunk_id: p.hit.chunk_id, start: 0, end: text.length }] : [],
+ match_spans: text.length > header.length ? [{ chunk_id: p.hit.chunk_id, start: header.length, end: text.length }] : [],
tokens: countEvidenceTokens(text, tokenizer),
truncated: false,
reason: p.reason,
@@ -976,6 +1001,7 @@ export async function deliverEvidence(
dropped_reasons: dropped,
fallbacks: [...fallbacks].sort(),
...(plan.budgetClamped ? { budget_clamped: plan.budgetClamped } : {}),
+ ...(plan.dateHeader ? { date_header: true as const } : {}),
},
};
}
diff --git a/src/core/search/fusion-lists.ts b/src/core/search/fusion-lists.ts
index d3936ded9c..b46f79d53a 100644
--- a/src/core/search/fusion-lists.ts
+++ b/src/core/search/fusion-lists.ts
@@ -213,3 +213,27 @@ export function composeFusionLists(input: ComposeFusionListsInput): FusionListEn
}
return out;
}
+
+/**
+ * Round-robin interleave for find-the-twin candidate lists (C2): each arm's
+ * #1 in arm order, then each arm's #2, and so on, keeping the first
+ * occurrence of a key and stopping at `limit`. Rank-only and score-free, so
+ * arms whose scores live on different scales (cosine distance, ts_rank)
+ * merge without calibration; an empty arm casts no vote. Hybrid search
+ * keeps RRF (`composeFusionLists`); this is for small fixed-k candidate sets.
+ */
+export function interleaveFusion<T>(arms: ReadonlyArray<ReadonlyArray<T>>, key: (item: T) => string | number, limit = Number.POSITIVE_INFINITY): T[] {
+ const out: T[] = [];
+ const seen = new Set<string | number>();
+ const depth = Math.max(0, ...arms.map(arm => arm.length));
+ for (let rank = 0; rank < depth && out.length < limit; rank++) {
+ for (const arm of arms) {
+ if (rank >= arm.length || out.length >= limit) continue;
+ const id = key(arm[rank]);
+ if (seen.has(id)) continue;
+ seen.add(id);
+ out.push(arm[rank]);
+ }
+ }
+ return out;
+}
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index d523f5382d..2a36753941 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -40,6 +40,7 @@ const DIRECTLY_READ_SINGLETONS = [
'search.return_budget_default',
'search.return_budget_conversation',
'search.return_budget_max_remote',
+ 'search.evidence_date_header', // search/evidence-delivery.ts (C1)
];
describe('KNOWN_CONFIG_KEYS search.* rows mirror what the code reads (#4605)', () => {
diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.ts
index b207c5baa6..0a7784e4c9 100644
--- a/test/e2e/engine-parity.test.ts
+++ b/test/e2e/engine-parity.test.ts
@@ -2548,6 +2548,8 @@ describeBoth('Engine parity — facts TTL read-time validity (WP5)', () => {
bySession: texts(await eng.listFactsBySession(SRC, SESSION)),
dupRecency: texts(await eng.findCandidateDuplicates(SRC, ENTITY, 'ttl lapsed fact')),
dupEmbedding: texts(await eng.findCandidateDuplicates(SRC, EMB_ENTITY, 'ttl embed lapsed', { embedding: emb, embeddingModel })),
+ dupKeyword: (await eng.findCandidateDuplicates(SRC, ENTITY, 'ttl lapsed future fact', { k: 5, arm: 'keyword' })).map(r => r.fact),
+ dupKeywordEmbedding: texts(await eng.findCandidateDuplicates(SRC, EMB_ENTITY, 'ttl embed lapsed', { embedding: emb, embeddingModel, arm: 'keyword' })),
history: texts(await eng.listFactsByEntity(SRC, ENTITY, { activeOnly: false })),
supersessions: texts(await eng.listSupersessions(SRC)),
health: {
@@ -2572,6 +2574,10 @@ describeBoth('Engine parity — facts TTL read-time validity (WP5)', () => {
expect(pg.dupRecency).toEqual(activeEntity);
// Lapsed row is not a dedup candidate → a re-stated fact re-inserts fresh.
expect(pg.dupEmbedding).toEqual(['ttl embed live']);
+ // C2 keyword arm: same active-row filters, ranked by shared terms (most shared first).
+ expect(pg.dupKeyword[0]).toBe('ttl future fact');
+ expect([...pg.dupKeyword].sort()).toEqual(activeEntity);
+ expect(pg.dupKeywordEmbedding).toEqual(['ttl embed live']);
// History (activeOnly:false) still shows every row.
expect(pg.history).toEqual([
'ttl durable fact', 'ttl future fact', 'ttl lapsed fact',
diff --git a/test/evidence-date-header.test.ts b/test/evidence-date-header.test.ts
new file mode 100644
index 0000000000..93f60148fd
--- /dev/null
+++ b/test/evidence-date-header.test.ts
@@ -0,0 +1,171 @@
+/**
+ * C1 — dated evidence blocks (`search.evidence_date_header`): the fixed
+ * one-line header grammar, the observation-date rule (never an event date or
+ * a row timestamp), budget accounting for the header, span offsets, the
+ * default-off byte identity, recall fact validity windows, and the
+ * configurable remote budget clamp the eval relies on.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import { countEvidenceTokens, deliverEvidence, type EvidencePlan } from '../src/core/search/evidence-delivery.ts';
+import {
+ EVIDENCE_DATE_HEADER_KEY, factDateHeader, formatBrainDay, pageDateHeader, pageObservationDate,
+} from '../src/core/search/evidence-date.ts';
+
+const HEADER_LINE = /^\[observed (\d{4}-\d{2}-\d{2}|unknown)\]\n/;
+
+describe('header grammar and dates', () => {
+ test('page and fact headers are fixed one-line strings; unknown dates read "unknown"', () => {
+ expect(pageDateHeader('2026-03-05')).toBe('[observed 2026-03-05]');
+ expect(pageDateHeader(null)).toBe('[observed unknown]');
+ expect(factDateHeader({ valid_from: new Date('2026-03-01T00:00:00Z'), valid_until: null })).toBe('[observed unknown; valid 2026-03-01 to unknown]');
+ expect(factDateHeader({ valid_from: null, valid_until: '2026-04-01T00:00:00.000Z' })).toBe('[observed unknown; valid unknown to 2026-04-01]');
+ for (const h of [pageDateHeader(null), factDateHeader({})]) expect(h).not.toContain('\n');
+ });
+
+ test('formatBrainDay: midnight UTC renders as written, other instants in brain.timezone', () => {
+ expect(formatBrainDay(new Date('2026-03-05T00:00:00Z'), 'America/Los_Angeles')).toBe('2026-03-05');
+ expect(formatBrainDay(new Date('2026-03-05T03:00:00Z'), 'America/Los_Angeles')).toBe('2026-03-04');
+ expect(formatBrainDay(new Date('2026-03-05T03:00:00Z'), null)).toBe('2026-03-05');
+ expect(formatBrainDay(new Date('2026-03-05T03:00:00Z'), 'Not/AZone')).toBe('2026-03-05');
+ expect(formatBrainDay(null)).toBeNull();
+ expect(formatBrainDay('garbage')).toBeNull();
+ });
+
+ test('observation date: filename, date, published, created keys; never event_date or row times', () => {
+ const day = (d: Date | null) => d?.toISOString().slice(0, 10) ?? null;
+ expect(day(pageObservationDate({ slug: 'notes/x', frontmatter: { date: '2026-03-05' } }))).toBe('2026-03-05');
+ expect(day(pageObservationDate({ slug: 'notes/x', frontmatter: { event_date: '2024-01-01', date: '2026-03-05' } }))).toBe('2026-03-05');
+ expect(pageObservationDate({ slug: 'notes/x', frontmatter: { event_date: '2024-01-01' } })).toBeNull();
+ expect(day(pageObservationDate({ slug: 'chat/2026-02-10-session', frontmatter: {} }))).toBe('2026-02-10');
+ expect(day(pageObservationDate({ slug: 'notes/x', frontmatter: { created: '2025-12-31' } }))).toBe('2025-12-31');
+ expect(pageObservationDate({ slug: 'notes/undated', frontmatter: {} })).toBeNull();
+ });
+});
+
+describe('deliverEvidence with the header on', () => {
+ const body = Array.from({ length: 30 }, (_, i) => `**${i % 2 ? 'assistant' : 'user'}:** turn ${i} about the renewal and the roadmap.`).join('\n\n');
+ const chunks = [body.slice(0, body.length / 2).trim(), body.slice(body.length / 2).trim()];
+ function stub(frontmatter: Record<string, unknown>) {
+ return {
+ async getConfig(key: string) { return key === 'brain.timezone' ? 'UTC' : null; },
+ async executeRaw() { return [{ id: 1, slug: 'chat/s', frontmatter, import_filename: null }]; },
+ async getChunkWindows() {
+ return [{ page_id: 1, slug: 'chat/s', source_id: 'default', type: 'note', revision: 'r1', sealed: true, max_chunk_index: 1, row_limited: false,
+ compiled_truth: body, timeline: '', chunks: chunks.map((t, i) => ({ id: 1000 + i, chunk_index: i, chunk_text: t, chunk_source: 'compiled_truth' })) }];
+ },
+ } as never;
+ }
+ const hit: SearchResult = { slug: 'chat/s', page_id: 1, title: 'S', type: 'note', chunk_text: chunks[1], chunk_source: 'compiled_truth', chunk_id: 1001, chunk_index: 1, score: 1, stale: false, source_id: 'default' };
+ const plan = (budget: number, dateHeader: boolean): EvidencePlan => ({ requestedUnit: 'page', unit: 'page', window: 1, budgetTokens: budget, explicitUnit: true, ...(dateHeader ? { dateHeader: true as const } : {}) });
+
+ test('every block starts with its header; tokens and spans account for it', async () => {
+ const off = await deliverEvidence(stub({ date: '2026-03-05' }), [hit], plan(32000, false), {});
+ const on = await deliverEvidence(stub({ date: '2026-03-05' }), [hit], plan(32000, true), {});
+ const header = '[observed 2026-03-05]\n';
+ expect(on.results[0].chunk_text).toBe(header + off.results[0].chunk_text);
+ expect(on.results[0].delivered.tokens).toBe(off.results[0].delivered.tokens + countEvidenceTokens(header));
+ expect(on.delivery.tokens_delivered).toBe(countEvidenceTokens(on.results[0].chunk_text));
+ expect(on.delivery.date_header).toBe(true);
+ expect(off.delivery.date_header).toBeUndefined();
+ const spanOn = on.results[0].delivered.match_spans[0];
+ const spanOff = off.results[0].delivered.match_spans[0];
+ expect(on.results[0].chunk_text.slice(spanOn.start, spanOn.end)).toBe(off.results[0].chunk_text.slice(spanOff.start, spanOff.end));
+ });
+
+ test('the budget is honoured with the header counted', async () => {
+ for (const budget of [12, 40, 120, 400]) {
+ const on = await deliverEvidence(stub({}), [hit], plan(budget, true), {});
+ expect(on.results[0].chunk_text).toMatch(HEADER_LINE);
+ expect(on.results[0].chunk_text.startsWith('[observed unknown]\n')).toBe(true);
+ expect(on.delivery.budget_used).toBeLessThanOrEqual(budget);
+ }
+ });
+
+ test('a failed date read renders unknown and says so', async () => {
+ const engine = Object.assign(stub({}) as object, { async executeRaw() { throw new Error('boom'); } }) as never;
+ const on = await deliverEvidence(engine, [hit], plan(32000, true), {});
+ expect(on.results[0].chunk_text.startsWith('[observed unknown]\n')).toBe(true);
+ expect(on.delivery.fallbacks).toContain('date_header_unavailable');
+ });
+});
+
+describe('ops on PGLite', () => {
+ let engine: PGLiteEngine;
+ let lastMeta: Record<string, any> | null = null;
+ const op = (name: string) => operations.find(o => o.name === name)!;
+ const ctxOf = (overrides: Partial<OperationContext> = {}): OperationContext => ({
+ engine: engine as never, config: {} as never, logger: console as never, dryRun: false, remote: false, sourceId: 'default',
+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') lastMeta = value as Record<string, any>; },
+ ...overrides,
+ }) as OperationContext;
+ const SESSION = Array.from({ length: 12 }, (_, i) => `**user:** question ${i} about the walrus launch\n\n**assistant:** reply ${i} on walrus timelines`).join('\n\n');
+ const NOTE = '## Walrus\n\nThe walrus pricing note describes the plan.';
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const pages: Array<[string, string, Record<string, unknown>]> = [
+ ['chat/2026-02-10-walrus', SESSION, {}],
+ ['notes/walrus-dated', NOTE, { date: '2026-03-05', event_date: '2020-01-01' }],
+ ['notes/walrus-undated', NOTE.replace('pricing', 'support'), {}],
+ ];
+ for (const [slug, body, frontmatter] of pages) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: '', frontmatter });
+ await installFixtureChunks(engine, slug, await prepareMarkdownChunks({ compiled_truth: body, timeline: '' }));
+ }
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+ await engine.insertFact({ fact: 'Walrus launch is in March', kind: 'fact', entity_slug: 'notes/walrus-dated', source: 'test', visibility: 'world',
+ valid_from: new Date('2026-03-01T00:00:00Z') }, { source_id: 'default' });
+ }, 240_000);
+
+ afterAll(async () => { await engine.disconnect(); }, 240_000);
+
+ test('default off: no header, no meta key, recall facts unchanged', async () => {
+ const rows = await op('search').handler(ctxOf(), { query: 'walrus', return_unit: 'page' }) as SearchResult[];
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.some(r => HEADER_LINE.test(r.chunk_text))).toBe(false);
+ expect(lastMeta!.delivery.date_header).toBeUndefined();
+ const recall = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-dated' }) as Record<string, any>;
+ expect(recall.facts[0].date_header).toBeUndefined();
+ });
+
+ test('on: query/search blocks carry observed dates; recall facts carry their validity window', async () => {
+ await engine.setConfig(EVIDENCE_DATE_HEADER_KEY, 'true');
+ try {
+ const rows = await op('query').handler(ctxOf(), { query: 'walrus', return_unit: 'page', expand: false }) as SearchResult[];
+ const by = (slug: string) => rows.find(r => r.slug === slug)!;
+ expect(by('chat/2026-02-10-walrus').chunk_text.split('\n')[0]).toBe('[observed 2026-02-10]');
+ expect(by('notes/walrus-dated').chunk_text.split('\n')[0]).toBe('[observed 2026-03-05]');
+ expect(by('notes/walrus-undated').chunk_text.split('\n')[0]).toBe('[observed unknown]');
+ expect(lastMeta!.delivery.date_header).toBe(true);
+ expect(lastMeta!.delivery.budget_used).toBeLessThanOrEqual(lastMeta!.delivery.budget_tokens);
+ const auto = await op('search').handler(ctxOf(), { query: 'walrus' }) as SearchResult[];
+ expect(auto.every(r => HEADER_LINE.test(r.chunk_text))).toBe(true);
+ const recall = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-dated' }) as Record<string, any>;
+ expect(recall.facts[0].date_header).toBe('[observed unknown; valid 2026-03-01 to unknown]');
+ } finally {
+ await engine.unsetConfig(EVIDENCE_DATE_HEADER_KEY);
+ }
+ });
+
+ test('remote clamp: 32k by default and reported; a trusted eval brain raises it with search.return_budget_max_remote', async () => {
+ await op('search').handler(ctxOf({ remote: true }), { query: 'walrus', return_unit: 'page', token_budget: 90000 });
+ expect(lastMeta!.delivery.budget_clamped).toEqual({ requested: 90000, max: 32000 });
+ expect(lastMeta!.delivery.fallbacks).toContain('budget_clamped');
+ await engine.setConfig('search.return_budget_max_remote', '200000');
+ try {
+ await op('search').handler(ctxOf({ remote: true }), { query: 'walrus', return_unit: 'page', token_budget: 90000 });
+ expect(lastMeta!.delivery.budget_tokens).toBe(90000);
+ expect(lastMeta!.delivery.budget_clamped).toBeUndefined();
+ expect(lastMeta!.delivery.fallbacks).not.toContain('budget_clamped');
+ } finally {
+ await engine.unsetConfig('search.return_budget_max_remote');
+ }
+ });
+});
diff --git a/test/facts/candidate-fusion.test.ts b/test/facts/candidate-fusion.test.ts
new file mode 100644
index 0000000000..235ff9ca32
--- /dev/null
+++ b/test/facts/candidate-fusion.test.ts
@@ -0,0 +1,133 @@
+/**
+ * C2 — fact supersession candidates: the keyword arm of
+ * `findCandidateDuplicates` and `facts.candidate_fusion` in
+ * `listSupersessionCandidates` / `decideSingleFact` (PGLite, in-memory).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import {
+ CANDIDATE_FUSION_KEY, SUPERSESSION_CANDIDATE_K, decideSingleFact, listSupersessionCandidates, readCandidateFusion,
+} from '../../src/core/facts/single-prepare.ts';
+
+const MODEL = 'synthetic:fusion';
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ // Pin 1536 dims before initSchema (see facts-engine.test.ts for why).
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test-candidate-fusion' } });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ resetGateway();
+});
+
+/** Unit vector at angle theta from axis 0 toward `axis`; cos(vec(t,a), vec(0,_)) = cos(t). */
+const vec = (theta: number, axis = 1): Float32Array => {
+ const a = new Float32Array(1536);
+ a[0] = Math.cos(theta);
+ a[axis] = Math.sin(theta);
+ return a;
+};
+const cosTo = (c: number, axis = 1) => vec(Math.acos(c), axis);
+
+let n = 0;
+const entity = () => `companies/fusion-${++n}-${Math.random().toString(36).slice(2, 8)}`;
+
+async function seed(slug: string, fact: string, embedding: Float32Array, extra: Record<string, unknown> = {}): Promise<number> {
+ const r = await engine.insertFact({ fact, kind: 'fact', entity_slug: slug, source: 'test', visibility: 'world', embedding, embedding_model: MODEL, ...extra }, { source_id: 'default' });
+ return r.id;
+}
+
+async function withFusion<T>(mode: string | null, fn: () => Promise<T>): Promise<T> {
+ if (mode === null) await engine.unsetConfig(CANDIDATE_FUSION_KEY);
+ else await engine.setConfig(CANDIDATE_FUSION_KEY, mode);
+ try { return await fn(); } finally { await engine.setConfig(CANDIDATE_FUSION_KEY, 'rrf_free'); }
+}
+
+describe('findCandidateDuplicates arm=keyword', () => {
+ test('ranks the entity bucket by shared terms, active rows only', async () => {
+ const slug = entity();
+ const twin = await seed(slug, 'Annual recurring revenue reached $5M in March 2026', cosTo(0.5, 2));
+ const partial = await seed(slug, 'Revenue growth slowed in the second quarter', cosTo(0.9, 3));
+ const unrelated = await seed(slug, 'Headquarters moved to a new office downtown', cosTo(0.99, 4));
+ const expired = await seed(slug, 'Annual recurring revenue reached $3M', cosTo(0.5, 5));
+ await engine.expireFact(expired);
+ await seed(entity(), 'Annual recurring revenue reached $9M in March 2026', cosTo(0.5, 6));
+ const rows = await engine.findCandidateDuplicates('default', slug, 'Annual recurring revenue reached $7M in March 2026',
+ { embedding: vec(0), embeddingModel: MODEL, k: 5, arm: 'keyword' });
+ const ids = rows.map(r => r.id);
+ expect(ids[0]).toBe(twin);
+ expect(ids).toContain(partial);
+ expect(ids).not.toContain(unrelated);
+ expect(ids).not.toContain(expired);
+ expect(rows.every(r => r.entity_slug === slug)).toBe(true);
+ });
+
+ test('keeps the cosine arm comparability filters and returns nothing for a claim with no terms', async () => {
+ const slug = entity();
+ await seed(slug, 'Seat count is 40 engineers', cosTo(0.9), { embedding_model: 'other:model' });
+ const same = await seed(slug, 'Seat count is 45 engineers', cosTo(0.9));
+ const opts = { embedding: vec(0), embeddingModel: MODEL, k: 5, arm: 'keyword' as const };
+ expect((await engine.findCandidateDuplicates('default', slug, 'Seat count is 50 engineers', opts)).map(r => r.id)).toEqual([same]);
+ expect(await engine.findCandidateDuplicates('default', slug, 'the of and', opts)).toEqual([]);
+ expect(await engine.findCandidateDuplicates('default', slug, 'Seat count', { ...opts, embeddingModel: null })).toEqual([]);
+ });
+});
+
+describe('facts.candidate_fusion', () => {
+ test('defaults to rrf_free; unknown values read as the default', async () => {
+ expect(await withFusion(null, () => readCandidateFusion(engine))).toBe('rrf_free');
+ expect(await withFusion('bogus', () => readCandidateFusion(engine))).toBe('rrf_free');
+ expect(await withFusion('interleave', () => readCandidateFusion(engine))).toBe('interleave');
+ });
+
+ test('rrf_free is the cosine arm unchanged; interleave carries both arms, capped at k', async () => {
+ const slug = entity();
+ const lexical: number[] = [];
+ const semantic: number[] = [];
+ for (let i = 0; i < 6; i++) semantic.push(await seed(slug, `Board meeting notes batch ${i}`, cosTo(0.99 - i * 0.001, 2 + i)));
+ for (let i = 0; i < 3; i++) lexical.push(await seed(slug, `Customer churn rate was ${i + 2}% last quarter`, cosTo(0.2, 20 + i)));
+ const claim = 'Customer churn rate was 7% last quarter';
+ const cosineOnly = await engine.findCandidateDuplicates('default', slug, claim, { embedding: vec(0), embeddingModel: MODEL, k: SUPERSESSION_CANDIDATE_K });
+ const current = await listSupersessionCandidates(engine, 'default', slug, claim, vec(0), MODEL, 'rrf_free');
+ expect(current.map(r => r.id)).toEqual(cosineOnly.map(r => r.id));
+ expect(current.some(r => lexical.includes(r.id))).toBe(false);
+ const fused = await listSupersessionCandidates(engine, 'default', slug, claim, vec(0), MODEL, 'interleave');
+ expect(fused.length).toBe(SUPERSESSION_CANDIDATE_K);
+ expect(fused[0].id).toBe(semantic[0]);
+ expect(lexical).toContain(fused[1].id);
+ expect(fused.filter(r => lexical.includes(r.id)).length).toBeGreaterThanOrEqual(2);
+ expect(new Set(fused.map(r => r.id)).size).toBe(fused.length);
+ });
+
+ test('interleave finds a world twin crowded out of the cosine top 5 by private copies; never supersedes a private row', async () => {
+ const slug = entity();
+ for (let i = 0; i < 5; i++) {
+ await seed(slug, `Private note ${i}: funding runway estimate from the board deck`, cosTo(0.995 - i * 0.0005, 2 + i), { visibility: 'private' });
+ }
+ const twin = await seed(slug, 'Funding runway is 18 months', cosTo(0.97, 10));
+ const claim = { fact: 'Funding runway is 24 months', kind: 'fact' as const, visibility: 'world' as const, entity_slug: slug };
+ const before = await withFusion('rrf_free', () => decideSingleFact(engine, 'default', claim, vec(0), MODEL));
+ expect(before.status).toBe('inserted');
+ const after = await withFusion('interleave', () => decideSingleFact(engine, 'default', claim, vec(0), MODEL));
+ expect(after.status).toBe('superseded');
+ expect(after.candidate?.id).toBe(twin);
+ const privateClaim = { ...claim, visibility: 'private' as const, fact: 'Funding runway is 30 months' };
+ const priv = await withFusion('interleave', () => decideSingleFact(engine, 'default', privateClaim, vec(0), MODEL));
+ expect(priv.candidate?.visibility ?? 'private').toBe('private');
+ });
+
+ test('a similar-but-distinct claim below the cosine threshold stays distinct under interleave', async () => {
+ const slug = entity();
+ await seed(slug, 'Raised a $5M seed round in 2021', cosTo(0.9, 2));
+ const claim = { fact: 'Raised a $20M Series A round in 2023', kind: 'fact' as const, visibility: 'world' as const, entity_slug: slug };
+ const d = await withFusion('interleave', () => decideSingleFact(engine, 'default', claim, vec(0), MODEL));
+ expect(d.status).toBe('inserted');
+ });
+});
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index fc488e7a6a..ae892ff2a8 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -82,7 +82,7 @@
"expireFact: (id: number, opts?: { supersededBy?: number; at?: Date; }) => Promise<boolean>",
"findAnomalies: (opts: AnomaliesOpts) => Promise<AnomalyResult[]>",
"findByTitleFuzzy: (name: string, dirPrefix?: string, minSimilarity?: number, sourceId?: string) => Promise<{ slug: string; similarity: number; } | null>",
- "findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; }) => Promise<FactRow[]>",
+ "findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; arm?: \"keyword\"; }) => Promise<FactRow[]>",
"findDuplicatePage?: ((sourceId: string, opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string; }) => Promise<{ slug: string; id: number; } | null>) | undefined",
"findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",
"findOrphanPages: (opts?: PageReadScope & { sourceId?: string; sourceIds?: string[]; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>",
@@ -986,7 +986,7 @@
"explainVectorSearch: (embedding: Float32Array, opts?: SearchOpts) => Promise<Record<string, unknown>>",
"findAnomalies: (opts: AnomaliesOpts) => Promise<AnomalyResult[]>",
"findByTitleFuzzy: (name: string, dirPrefix?: string, minSimilarity?: number, sourceId?: string) => Promise<{ slug: string; similarity: number; } | null>",
- "findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; }) => Promise<FactRow[]>",
+ "findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; arm?: \"keyword\"; }) => Promise<FactRow[]>",
"findDuplicatePage: (sourceId: string, opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string; }) => Promise<{ slug: string; id: number; } | null>",
"findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",
"findOrphanPages: (opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>",
@@ -3070,7 +3070,7 @@
"expireFact: (id: number, opts?: { supersededBy?: number; at?: Date; }) => Promise<boolean>",
"findAnomalies: (opts: AnomaliesOpts) => Promise<AnomalyResult[]>",
"findByTitleFuzzy: (name: string, dirPrefix?: string, minSimilarity?: number, sourceId?: string) => Promise<{ slug: string; similarity: number; } | null>",
- "findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; }) => Promise<FactRow[]>",
+ "findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; arm?: \"keyword\"; }) => Promise<FactRow[]>",
"findDuplicatePage?: ((sourceId: string, opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string; }) => Promise<{ slug: string; id: number; } | null>) | undefined",
"findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",
"findOrphanPages: (opts?: PageReadScope & { sourceId?: string; sourceIds?: string[]; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>",
@@ -5858,7 +5858,7 @@
"expireFact: (id: number, opts?: { supersededBy?: number; at?: Date; }) => Promise<boolean>",
"findAnomalies: (opts: AnomaliesOpts) => Promise<AnomalyResult[]>",
"findByTitleFuzzy: (name: string, dirPrefix?: string, minSimilarity?: number, sourceId?: string) => Promise<{ slug: string; similarity: number; } | null>",
- "findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; }) => Promise<FactRow[]>",
+ "findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; arm?: \"keyword\"; }) => Promise<FactRow[]>",
"findDuplicatePage: (sourceId: string, opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string; }) => Promise<{ slug: string; id: number; } | null>",
"findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",
"findOrphanPages: (opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>",
@@ -6386,6 +6386,7 @@
"budget_tokens: number",
"budget_used: number",
"coordinates: \"utf16\"",
+ "date_header?: true | undefined",
"dropped: number",
"dropped_reasons: Record<string, number>",
"fallbacks: string[]",
@@ -6440,6 +6441,7 @@
"members": [
"budgetClamped?: { requested: number; max: number; } | undefined",
"budgetTokens: number",
+ "dateHeader?: true | undefined",
"explicitUnit: boolean",
"requestedUnit: \"auto\" | \"chunk\" | \"window\" | \"section\" | \"page\"",
"unit: \"auto\" | \"window\" | \"section\" | \"page\"",
diff --git a/test/search/interleave-fusion.test.ts b/test/search/interleave-fusion.test.ts
new file mode 100644
index 0000000000..b9844f6506
--- /dev/null
+++ b/test/search/interleave-fusion.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, test } from 'bun:test';
+import { interleaveFusion } from '../../src/core/search/fusion-lists.ts';
+
+const id = (x: { id: number }) => x.id;
+const rows = (...ids: number[]) => ids.map(n => ({ id: n }));
+
+describe('interleaveFusion', () => {
+ test('takes each arm\'s #1, then each arm\'s #2, in arm order', () => {
+ expect(interleaveFusion([rows(1, 2, 3), rows(10, 20, 30)], id).map(id)).toEqual([1, 10, 2, 20, 3, 30]);
+ });
+
+ test('de-duplicates by key, keeping the first occurrence', () => {
+ const cos = [{ id: 1, arm: 'cos' }, { id: 2, arm: 'cos' }];
+ const kw = [{ id: 2, arm: 'kw' }, { id: 1, arm: 'kw' }, { id: 3, arm: 'kw' }];
+ expect(interleaveFusion([cos, kw], id)).toEqual([{ id: 1, arm: 'cos' }, { id: 2, arm: 'kw' }, { id: 3, arm: 'kw' }]);
+ });
+
+ test('empty arms cast no vote; no arms yields nothing', () => {
+ expect(interleaveFusion([[], rows(4, 5)], id).map(id)).toEqual([4, 5]);
+ expect(interleaveFusion([rows(4, 5), []], id).map(id)).toEqual([4, 5]);
+ expect(interleaveFusion<{ id: number }>([], id)).toEqual([]);
+ expect(interleaveFusion([[], []], id)).toEqual([]);
+ });
+
+ test('unequal lengths continue with the longer arm', () => {
+ expect(interleaveFusion([rows(1), rows(10, 20, 30)], id).map(id)).toEqual([1, 10, 20, 30]);
+ });
+
+ test('limit truncates the fused order (k-bounded candidate set)', () => {
+ expect(interleaveFusion([rows(1, 2, 3, 4, 5), rows(10, 20, 30, 40, 50)], id, 5).map(id)).toEqual([1, 10, 2, 20, 3]);
+ expect(interleaveFusion([rows(1, 2), rows(1, 2)], id, 5).map(id)).toEqual([1, 2]);
+ expect(interleaveFusion([rows(1, 2)], id, 0)).toEqual([]);
+ });
+
+ test('is deterministic and does not mutate its inputs', () => {
+ const a = rows(3, 1, 2);
+ const b = rows(2, 9);
+ const first = interleaveFusion([a, b], id);
+ expect(interleaveFusion([a, b], id)).toEqual(first);
+ expect(a.map(id)).toEqual([3, 1, 2]);
+ expect(b.map(id)).toEqual([2, 9]);
+ });
+
+ test('three arms rotate in arm order', () => {
+ expect(interleaveFusion([rows(1, 2), rows(10), rows(100, 200)], id).map(id)).toEqual([1, 10, 100, 2, 200]);
+ });
+});