Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(facts): per-model supersession threshold calibration

garrytan62a7168e9a2b
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index bbfed08f5c..168ca49c12 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`.
-- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims.
+- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (the model's calibrated threshold from `facts/supersession-threshold.ts`; identical text is a duplicate even when the model is uncalibrated) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims.
- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; `attributeFallback` sets the intent's `attribute_fallback`), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.
- `src/core/interaction.ts` — the one interaction primitive (agent operator wave A5). `isInteractive(probe?)` needs two TTYs and no `GBRAIN_NON_INTERACTIVE`, `CI` or agent-process marker (`agentProcessMarker()`: `CLAUDECODE`, `CLAUDE_CODE_ENTRYPOINT`, `CODEX_SANDBOX`, `CODEX_CI`, `OPENCODE`, `OPENCODE_PID`; never `CODEX_HOME`); `GBRAIN_INTERACTIVE=1` overrides on two TTYs only, and a marker or `CI` forcing prompts off prints one stderr line per process naming it and the override. Neither variable implies consent. `readLine` is the prompt read (stderr prompt; EOF/timeout = decline; `{kind:'eof'}` without reading when non-interactive; bytes after the newline are pushed back for the next prompt). `readStdinBounded` is the payload read: 30 s first-byte deadline (`GBRAIN_STDIN_TIMEOUT_MS` overrides; stderr notice at 5 s), 60 s inactivity reset per chunk, no total cap, 5 MB default byte cap; `data`/`empty`/`timeout{phase}`/`cancelled`/`error` are distinct and partial input is never `data`. Every reader removes its listeners and pauses the stream so the process can exit; a failed read of process stdin also destroys it. Also hosts the legacy `promptLine` (now `''` on EOF), `promptLineStderr` and `promptYesNo`, re-exported by `cli-util.ts` / `confirm-prompt.ts` for one release; `src/cli.ts` keeps a legacy `readStdinBounded(): string | null` shim. Pinned by `test/interaction.test.ts` (decision table, injected streams) and `test/interaction-stdin.serial.test.ts` (real stdin, PTY, natural exit).
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index f08995047b..1bed5d9d09 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -85,10 +85,14 @@ rejection of serve-only flags before a brain opens.
- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text, resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).
-- `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/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 drop at the embedding model's calibrated threshold (`supersession-threshold.ts`; none for an uncalibrated model); 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/supersession-threshold.ts` — the one explicit-lane cosine supersession threshold, per embedding model: `SUPERSESSION_CALIBRATIONS` keyed `provider:model@dims` (only `voyage:voyage-4@1024` = 0.95, measured in `docs/eval/decisions/supersession-threshold-dev/`), overridden per model by `facts.supersession_thresholds` (JSON `{"provider:model@dims": number in (0,1] | "off"}`; malformed entries ignored). `readSupersessionThreshold` feeds `cosineVerdict` in `decideSingleFact` and the facts backstop, `writeSingleFact`'s unmanaged path, and `classifyAgainstCandidates`' fast path and cosine fallback. An uncalibrated model never supersedes or deduplicates by cosine: the fact is inserted (exact-text duplicates still collapse: the fingerprint check in `decideSingleFact`, identical text in `writeSingleFact`) and the `conflict` decide sweep judges the pair where it is on. Doctor `supersession_calibration` (informational) names an uncalibrated model with the embed → sweep → register action. Tests: `test/facts/supersession-threshold.test.ts`, `test/doctor-supersession-calibration.test.ts`.
+
+- `src/commands/doctor/checks/supersession-calibration.ts` — doctor `supersession_calibration`, always status ok: calibrated or operator threshold → plain ok with the key and value; `"off"` → info `disabled_by_choice`; embeddings off → info `not_applicable`; uncalibrated → info `degraded` with a three-step `fix` (`bun <repo>/scripts/eval-c2-candidate-fusion.ts embed` with consent `paid`+`egress` and a user message, then the free `run --taus 0.80:0.97:0.01`, then `gbrain config set facts.supersession_thresholds` merging existing entries with the `THRESHOLD` input from `threshold_pick.guarded`; verify `gbrain doctor --only supersession_calibration --json`). The fix is omitted when the script is not on disk. Test: `test/doctor-supersession-calibration.test.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/eval/decisions/supersession-threshold-dev/README.md b/docs/eval/decisions/supersession-threshold-dev/README.md
index a6e7fce864..486c6fda2f 100644
--- a/docs/eval/decisions/supersession-threshold-dev/README.md
+++ b/docs/eval/decisions/supersession-threshold-dev/README.md
@@ -8,7 +8,7 @@ For the default model, `voyage:voyage-4`, the product's threshold of 0.95 is alr
choice, so this finding proposes no change for it. The threshold does depend on the embedding model, though.
With `openai:text-embedding-3-large`, no threshold meets the guard, and at 0.95 it replaces 54% of new
coexisting claims. Even at its best setting on the default model, a cosine threshold alone leaves 47% of
-corrections inserted beside the old value. The verdict is `dev` and changes no default.
+corrections inserted beside the old value. The verdict is `dev`; the per-model table it led to is applied in this wave (see below).
## Results (rrf_free arm; interleave is the same from 0.90 up and one correction worse below)
@@ -57,9 +57,26 @@ On both models the two distributions overlap. Cosine alone can't tell "same clai
similar claim about a different period". That's why about half of corrections stay unreplaced even at the
best threshold on the default model.
-## Proposed fix (not applied; routed by the wave owner)
+## Applied in this wave
-1. **Calibrate per model.** Replace the single `EXPLICIT_DUPLICATE_THRESHOLD = 0.95` (`facts/capture-dedup.ts`,
+Fix 1 below is in the memory proof wave. Fix 2 is not.
+
+- **Calibration table.** `src/core/facts/supersession-threshold.ts` holds one table keyed `provider:model@dims`.
+ Its only entry is `voyage:voyage-4@1024` at 0.95, so voyage-4 decides exactly as before.
+- **Readers.** The fixed 0.95 constants in `capture-dedup.ts`, `write-single.ts` and the classify fast path now
+ read the table.
+- **Uncalibrated models,** including `openai:text-embedding-3-large`, never supersede or deduplicate by
+ cosine. Each new fact is inserted, and the `conflict` decide sweep judges the pair where it is on.
+ Exact-text duplicates still collapse: the fingerprint check in `decideSingleFact` and identical text in
+ `writeSingleFact`.
+- **Override.** `facts.supersession_thresholds` takes a JSON map `{"provider:model@dims": number | "off"}`, so an
+ operator can register a measured value without a release.
+- **Doctor.** `supersession_calibration` is an informational check. For an uncalibrated model it names the
+ model and returns the embed, sweep and register commands.
+
+## Proposed fix
+
+1. **Calibrate per model (applied, see above).** Replace the single `EXPLICIT_DUPLICATE_THRESHOLD = 0.95` (`facts/capture-dedup.ts`,
also hard-coded in `facts/write-single.ts` and the classify fast path) with a per-embedding-model table.
Keep `voyage:voyage-4` at 0.95. A model with no calibrated entry, such as `openai:text-embedding-3-large`,
should not supersede by cosine. Its writes insert the new fact and leave the pair to the existing
diff --git a/scripts/eval-c2-candidate-fusion.ts b/scripts/eval-c2-candidate-fusion.ts
index 1c9f8f5e0f..dd5c612da7 100644
--- a/scripts/eval-c2-candidate-fusion.ts
+++ b/scripts/eval-c2-candidate-fusion.ts
@@ -28,8 +28,9 @@
* 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.
+ * in TAUS; each threshold is also registered as the model's
+ * `facts.supersession_thresholds` override, so the real decideSingleFact
+ * runs beside every replayed decision and must agree.
*/
import { createHash } from 'node:crypto';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
@@ -38,7 +39,7 @@ import { gunzipSync, gzipSync } 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 { SUPERSESSION_THRESHOLDS_KEY, calibrationKey, resolveSupersessionThreshold } from '../src/core/facts/supersession-threshold.ts';
import {
CANDIDATE_FUSION_KEY, SUPERSESSION_CANDIDATE_K, decideSingleFact, listSupersessionCandidates, type CandidateFusion,
} from '../src/core/facts/single-prepare.ts';
@@ -242,6 +243,8 @@ async function replay(engineDims: number, model: string, emb: (t: string) => Flo
await engine.connect({});
await engine.initSchema();
await engine.setConfig(CANDIDATE_FUSION_KEY, mode);
+ // The product decides at this threshold too, so every replayed decision is checked against decideSingleFact.
+ await engine.setConfig(SUPERSESSION_THRESHOLDS_KEY, JSON.stringify({ [calibrationKey(model, engineDims)]: tau }));
const keyOf = new Map<number, string>();
const established = new Map<string, Set<string>>();
const insert = async (c: Company, row: Row, supersedeId?: number) => {
@@ -275,7 +278,7 @@ async function replay(engineDims: number, model: string, emb: (t: string) => Flo
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++;
}
@@ -417,7 +420,7 @@ async function run(embeddingsPath: string, outDir: string | null, taus: number[]
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,
+ product_decide_mismatches: { rrf_free: A.product_mismatches, interleave: B.product_mismatches },
},
});
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 }]));
@@ -443,7 +446,7 @@ async function run(embeddingsPath: string, outDir: string | null, taus: number[]
rule: 'lowest correction miss rate with false supersession <= 1% of probes and preserved distinct claims >= 99.5% (rrf_free arm); balanced = argmin(correction miss + coexisting false supersession)',
guarded: pickMin(safe, r => num(r, 'correction_miss_rate')),
balanced: pickMin(base, r => num(r, 'correction_miss_rate') + num(r, 'coexisting_false_supersession_rate')),
- product: EXPLICIT_DUPLICATE_THRESHOLD,
+ product: resolveSupersessionThreshold(model, store.dims).threshold,
};
const decidedAt = new Date().toISOString();
const verdictJson = {
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index b383e46408..70a6cb334b 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -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 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/config.ts 1841 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; +1 facts.supersession_thresholds registry row (per-model supersession calibration)
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/commands/doctor/checks/supersession-calibration.ts b/src/commands/doctor/checks/supersession-calibration.ts
new file mode 100644
index 0000000000..bde58b24a9
--- /dev/null
+++ b/src/commands/doctor/checks/supersession-calibration.ts
@@ -0,0 +1,102 @@
+/**
+ * supersession_calibration (informational): whether this brain's embedding
+ * model has a calibrated fact supersession threshold
+ * (src/core/facts/supersession-threshold.ts). Without one, an explicit write
+ * never replaces a similar fact by cosine: the new fact is inserted next to
+ * the old one, and the conflict review sweep judges the pair where it is on.
+ * The fix measures a threshold for the model on the synthetic C2 fixture
+ * (about 23K tokens of test sentences, about a cent; no brain content leaves
+ * the machine) and registers it in `facts.supersession_thresholds`. Always
+ * status ok: the brain is safe either way, it just keeps more duplicates.
+ */
+import { existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { doctorVerify } from '../check-fix.ts';
+import { embeddingsDisabled } from '../../../core/embedding-disabled.ts';
+import type { Action } from '../../../core/agent-output.ts';
+
+const DOCS = 'docs/eval/decisions/supersession-threshold-dev/README.md';
+const SCRIPT = resolve(import.meta.dir, '../../../../scripts/eval-c2-candidate-fusion.ts');
+
+/** embed (paid, ask first) → sweep (free) → register the guarded pick. */
+function calibrationFix(model: string, dims: number, key: string, overrides: Record<string, unknown>): Action {
+ const out = join(tmpdir(), `gbrain-supersession-${key.replace(/[^a-z0-9]+/gi, '-')}.json.gz`);
+ const register = JSON.stringify({ ...overrides, [key]: '<THRESHOLD>' }).replace('"<THRESHOLD>"', 'THRESHOLD');
+ return {
+ argv: ['bun', SCRIPT, 'embed', '--model', model, '--dims', String(dims), '--out', out],
+ consent: ['paid', 'egress'],
+ actor: 'agent',
+ why: `Supersession by similarity is off for ${key} until a threshold is measured for it. This embeds the synthetic C2 fixture (1,506 test sentences, about 23K tokens) with ${model}; no brain content is sent.`,
+ user_message: `Facts saved on this brain never replace a similar older fact automatically, because its embedding model (${key}) has no measured threshold. Measuring one sends about 23K tokens of synthetic test sentences to the embedding provider (about a cent). OK to run it?`,
+ docs: DOCS,
+ requires_exclusive: false,
+ then: {
+ argv: ['bun', SCRIPT, 'run', '--embeddings', out, '--taus', '0.80:0.97:0.01'],
+ consent: [],
+ actor: 'agent',
+ why: 'Replays the fixture at each threshold on a throwaway in-memory brain (no provider calls) and prints threshold_pick.guarded: the threshold that misses the fewest corrections while false supersession stays at or under 1% and 99.5% of distinct claims survive.',
+ requires_exclusive: false,
+ then: {
+ argv: ['gbrain', 'config', 'set', 'facts.supersession_thresholds', register],
+ consent: [],
+ actor: 'agent',
+ why: 'Registers the measured threshold for this model; the next fact write uses it. Remove it with gbrain config unset facts.supersession_thresholds.',
+ inputs: [{ name: 'THRESHOLD', how: 'threshold_pick.guarded from the previous step\'s JSON output. When it is null no threshold is safe for this model: skip this step and leave supersession off.' }],
+ verify: doctorVerify('supersession_calibration'),
+ requires_exclusive: false,
+ },
+ },
+ };
+}
+
+async function runSupersessionCalibration(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ const checks: Check[] = [];
+ ctx.progress.heartbeat('supersession_calibration');
+ try {
+ if (await embeddingsDisabled(engine)) {
+ checks.push({ name: 'supersession_calibration', status: 'ok', severity: 'info', readiness_state: 'not_applicable',
+ message: 'Embeddings are off on this brain, so facts are only deduplicated by exact text; no supersession threshold applies.' });
+ return checks;
+ }
+ const { getEmbeddingModel, getEmbeddingDimensions } = await import('../../../core/ai/gateway.ts');
+ const { SUPERSESSION_THRESHOLDS_KEY, readSupersessionThreshold } = await import('../../../core/facts/supersession-threshold.ts');
+ const model = getEmbeddingModel();
+ const dims = getEmbeddingDimensions();
+ const resolved = await readSupersessionThreshold(engine, model, dims);
+ const details = { model, dims, key: resolved.key, threshold: resolved.threshold, source: resolved.source, config_key: SUPERSESSION_THRESHOLDS_KEY, docs: DOCS };
+ if (resolved.threshold !== null) {
+ checks.push({ name: 'supersession_calibration', status: 'ok', details,
+ message: `Fact supersession replaces a similar fact at cosine ${resolved.threshold} for ${resolved.key} (${resolved.source === 'override' ? `operator value in ${SUPERSESSION_THRESHOLDS_KEY}` : 'calibrated'}).` });
+ return checks;
+ }
+ if (resolved.source === 'override') {
+ checks.push({ name: 'supersession_calibration', status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice', details,
+ message: `Fact supersession by similarity is off for ${resolved.key} (set to "off" in ${SUPERSESSION_THRESHOLDS_KEY}); new facts are inserted and exact-text duplicates still collapse.` });
+ return checks;
+ }
+ let raw: unknown = {};
+ try { raw = JSON.parse((await engine.getConfig(SUPERSESSION_THRESHOLDS_KEY)) ?? '{}'); } catch { raw = {}; }
+ const overrides = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw as Record<string, unknown> : {};
+ checks.push({
+ name: 'supersession_calibration', status: 'ok', severity: 'info', readiness_state: 'degraded', details,
+ message: `Embedding model ${resolved.key} has no calibrated fact supersession threshold, so a saved fact never replaces a similar older one `
+ + 'by similarity: it is inserted beside it (exact-text duplicates still collapse), and the conflict review sweep judges the pair where it is on. '
+ + `Measure one with the C2 fixture (about a cent), then register it in ${SUPERSESSION_THRESHOLDS_KEY}. See ${DOCS}.`,
+ ...(existsSync(SCRIPT) ? { fix: calibrationFix(model, dims, resolved.key, overrides) } : {}),
+ });
+ } catch (error) {
+ checks.push({ name: 'supersession_calibration', status: 'ok', severity: 'info', readiness_state: 'unknown',
+ message: `Could not resolve the fact supersession threshold: ${error instanceof Error ? error.message : String(error)}.` });
+ }
+ return checks;
+}
+
+export const supersessionCalibrationEntry: DoctorEntry = {
+ name: 'supersession_calibration',
+ emits: ['supersession_calibration'],
+ run: runSupersessionCalibration,
+};
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index c20b98d777..0b9160bd97 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -85,6 +85,7 @@ import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';
import { autoChronicleEntry } from './checks/auto-chronicle.ts';
import { factTakeVectorsEntry } from './checks/vector-coverage.ts';
import { decideHealthEntry } from './checks/decide.ts';
+import { supersessionCalibrationEntry } from './checks/supersession-calibration.ts';
import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';
import { plannerStatsEntry } from './checks/planner-stats.ts';
import { harnessWiringDoctorEntry } from './checks/harness-wiring.ts';
@@ -125,6 +126,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
embeddingQueryPrefixEntry,
embeddingColumnRegistryEntry,
embeddingEnvOverrideEntry,
+ supersessionCalibrationEntry,
graphCoverageEntry,
orphanRatioEntry,
staleMentionsEntry,
diff --git a/src/core/config.ts b/src/core/config.ts
index 24ceaecb9e..b4a6dfe891 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1426,6 +1426,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'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)
+ 'facts.supersession_thresholds', // JSON {"provider:model@dims": number | "off"} (facts/supersession-threshold.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/doctor-categories.ts b/src/core/doctor-categories.ts
index 8e3803fcd8..63c314f746 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -143,6 +143,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'source_routing_health',
'stale_mentions',
'stub_guard_24h',
+ // Fact supersession threshold calibrated for the active embedding model (facts/supersession-threshold.ts).
+ 'supersession_calibration',
'sync_failures',
// #5984: unfinished managed sync cursors, their remaining entries and indexing ETA.
'managed_sync_backlog',
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 787e83acba..afc46bcf75 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -48,6 +48,7 @@ import { isAvailable } from '../ai/gateway.ts';
import { withAIInvocationPreflight } from '../ai/invocation-guard.ts';
import { decideSingleFact } from './single-prepare.ts';
import { cosineVerdict, dedupCapturedFacts, withCaptureDrops } from './capture-dedup.ts';
+import { readSupersessionThreshold } from './supersession-threshold.ts';
import { appendContextNote, type InferredVia } from './subject-infer.ts';
import { inferenceNote, inferMissingSubjects } from './subject-infer-write.ts';
@@ -693,7 +694,7 @@ async function runPipelineBodyInner(
// Dedup against DB candidates (correct per Codex Q7: fence rows
// have no embeddings; FS lock + sync invariant means DB == fence
- // at write time). cosineVerdict: 0.95 for explicit lanes; capture lanes never drop by cosine (#5888).
+ // at write time). cosineVerdict: the model's calibrated threshold for explicit lanes; capture lanes never drop by cosine (#5888).
const exact = resolvedSlug ? await decideSingleFact(ctx.engine, ctx.sourceId, { entity_slug: resolvedSlug, fact: f.fact, kind: f.kind ?? 'fact', visibility }, null) : null;
let matchedExistingId: number | null = exact?.candidate?.id ?? null;
if (matchedExistingId === null && resolvedSlug && f.embedding && !f.entity_inferred) {
@@ -709,7 +710,7 @@ async function runPipelineBodyInner(
const s = cosineSimilarity(f.embedding, c.embedding);
if (!top || s > top.score) top = { id: c.id, score: s, fact: c.fact };
}
- if (top && cosineVerdict(ctx.source, top.score, f.fact, top.fact) === 'duplicate') {
+ if (top && cosineVerdict(ctx.source, top.score, f.fact, top.fact, (await readSupersessionThreshold(ctx.engine, f.embedding_model, f.embedding.length)).threshold) === 'duplicate') {
matchedExistingId = top.id;
}
}
diff --git a/src/core/facts/capture-dedup.ts b/src/core/facts/capture-dedup.ts
index 116a36f5a3..62e70936ce 100644
--- a/src/core/facts/capture-dedup.ts
+++ b/src/core/facts/capture-dedup.ts
@@ -35,8 +35,6 @@ export const CAPTURE_LANES = ['hook:writeback', 'sweep:corpus', 'hook:compact']
export const CAPTURE_DEDUP_WINDOW_MS = 15 * 60 * 1000;
/** Shadow-mode near-duplicate threshold (measured, never a drop). */
export const NEAR_DUPLICATE_THRESHOLD = 0.92;
-/** Explicit lanes keep their pre-#5888 cosine rule. */
-export const EXPLICIT_DUPLICATE_THRESHOLD = 0.95;
const CAPTURE_DEDUP_SCAN_LIMIT = 50;
export function isCaptureLane(source: string | null | undefined): boolean {
@@ -75,10 +73,13 @@ export type CosineVerdict = 'duplicate' | 'near_duplicate' | 'distinct';
/**
* The one cosine policy for every fact-write decision point. Capture lanes
- * never return `duplicate`; explicit lanes keep the 0.95 rule unchanged.
+ * never return `duplicate`. Explicit lanes return `duplicate` at or above
+ * `explicitThreshold`, the embedding model's calibrated supersession
+ * threshold (supersession-threshold.ts); null (an uncalibrated model) never
+ * returns `duplicate`.
*/
-export function cosineVerdict(source: string | null | undefined, score: number, claim: string, existing: string): CosineVerdict {
- if (!isCaptureLane(source)) return score >= EXPLICIT_DUPLICATE_THRESHOLD ? 'duplicate' : 'distinct';
+export function cosineVerdict(source: string | null | undefined, score: number, claim: string, existing: string, explicitThreshold: number | null): CosineVerdict {
+ if (!isCaptureLane(source)) return explicitThreshold !== null && score >= explicitThreshold ? 'duplicate' : 'distinct';
return score >= NEAR_DUPLICATE_THRESHOLD && !claimsDiverge(claim, existing) ? 'near_duplicate' : 'distinct';
}
@@ -163,7 +164,7 @@ export async function findNearDuplicate(scope: CaptureScope, candidate: CaptureC
const score = cosineSimilarity(candidate.embedding, row.embedding);
if (!best || score > best.score) best = { id: row.id, score, fact: row.fact };
}
- return best && cosineVerdict(scope.lane, best.score, candidate.fact, best.fact) === 'near_duplicate' ? best.id : null;
+ return best && cosineVerdict(scope.lane, best.score, candidate.fact, best.fact, null) === 'near_duplicate' ? best.id : null;
}
export interface CaptureDedupResult<T> { kept: T[]; duplicateIds: number[]; nearDuplicates: number; }
diff --git a/src/core/facts/classify.ts b/src/core/facts/classify.ts
index cd49305149..840645e53c 100644
--- a/src/core/facts/classify.ts
+++ b/src/core/facts/classify.ts
@@ -5,11 +5,14 @@
*
* 1. Find candidates (entity-prefiltered, k=5 cap) — caller has done this.
* 2. If candidates is empty → INSERT (independent).
- * 3. CHEAP FAST-PATH (D13): if top-candidate cosine ≥ 0.95 → DUPLICATE.
- * Skip the LLM call entirely. Cheapest accurate dedup.
+ * 3. CHEAP FAST-PATH (D13): if top-candidate cosine ≥ the embedding
+ * model's calibrated threshold (supersession-threshold.ts; 0.95 for
+ * voyage-4@1024) → DUPLICATE. Skip the LLM call entirely. An
+ * uncalibrated model has no fast path.
* 4. Run the LLM classifier asking: duplicate | supersede | independent.
* 5. CLASSIFIER FAILURE FALLBACK (D12): on LLM error/timeout/refusal,
* compute cosine; if top-candidate ≥ 0.92 → DUPLICATE; else → INSERT.
+ * An uncalibrated model always falls back to INSERT.
*
* Pure logic — engine writes happen in the orchestrator layer, not here.
*
@@ -20,6 +23,7 @@ import { chat, isAvailable } from '../ai/gateway.ts';
import type { ChatResult } from '../ai/gateway.ts';
import { resolveTierDefault } from '../model-config.ts';
import type { FactRow, FactKind } from '../engine.ts';
+import { resolveSupersessionThreshold } from './supersession-threshold.ts';
/** Classifier output. id is the matching candidate's id when not 'independent'. */
export type ClassifyResult =
@@ -28,10 +32,12 @@ export type ClassifyResult =
| { decision: 'independent'; reason: 'no_candidates' | 'classifier' | 'cosine_fallback' };
export interface ClassifyOpts {
- /** Cosine threshold for the cheap fast-path. Default 0.95. */
+ /** Cosine threshold for the cheap fast-path. Default: the calibrated threshold of `embeddingModel` at the embedding's dims. */
cheapThreshold?: number;
- /** Cosine threshold for the failure fallback. Default 0.92. */
+ /** Cosine threshold for the failure fallback. Default 0.92 for a calibrated model; none (INSERT) otherwise. */
fallbackThreshold?: number;
+ /** The `provider:model` the embeddings came from; selects the calibrated threshold. */
+ embeddingModel?: string | null;
/** Override the chat model; default uses gateway's expansion model (Haiku). */
model?: string;
/** Abort signal for shutdown. */
@@ -75,10 +81,11 @@ export async function classifyAgainstCandidates(
return { decision: 'independent', reason: 'no_candidates' };
}
- const cheap = opts.cheapThreshold ?? 0.95;
- const fallback = opts.fallbackThreshold ?? 0.92;
+ const calibrated = newFact.embedding ? resolveSupersessionThreshold(opts.embeddingModel, newFact.embedding.length).threshold : null;
+ const cheap = opts.cheapThreshold ?? calibrated ?? Number.POSITIVE_INFINITY;
+ const fallback = opts.fallbackThreshold ?? (calibrated === null ? Number.POSITIVE_INFINITY : 0.92);
- // CHEAP FAST-PATH: skip LLM if top-1 cosine >= 0.95 (D13).
+ // CHEAP FAST-PATH: skip LLM if top-1 cosine >= the calibrated threshold (D13).
let topId: number | null = null;
let topScore = -1;
if (newFact.embedding) {
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index 8f8d25bc80..82fa2abc17 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -5,6 +5,7 @@ import { cosineSimilarity } from './classify.ts';
import { isFactWithdrawn } from './withdrawal.ts';
import { cosineVerdict } from './capture-dedup.ts';
import { interleaveFusion } from '../search/fusion-lists.ts';
+import { readSupersessionThreshold } from './supersession-threshold.ts';
export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };
export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }
@@ -85,7 +86,7 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in
const next = cosineSimilarity(embedding, c.embedding);
if (next > score) { score = next; candidate = c; }
}
- if (candidate && cosineVerdict(lane, score, input.fact, candidate.fact) === 'duplicate') return {
+ if (candidate && cosineVerdict(lane, score, input.fact, candidate.fact, (await readSupersessionThreshold(engine, embeddingModel, embedding.length)).threshold) === 'duplicate') return {
status: candidate.kind === input.kind ? 'superseded' : 'duplicate', candidate,
};
}
diff --git a/src/core/facts/supersession-threshold.ts b/src/core/facts/supersession-threshold.ts
new file mode 100644
index 0000000000..9d2dc598a8
--- /dev/null
+++ b/src/core/facts/supersession-threshold.ts
@@ -0,0 +1,72 @@
+/**
+ * The explicit-lane cosine supersession threshold, per embedding model.
+ *
+ * A new fact whose closest eligible candidate scores at or above this cosine
+ * replaces (or deduplicates against) it. The cutoff is a property of the
+ * embedding model: the C2 follow-up eval (docs/eval/decisions/
+ * supersession-threshold-dev) found 0.95 to be the guarded optimum for
+ * voyage-4 at 1024 dimensions, while for openai text-embedding-3-large no
+ * threshold separates corrections from coexisting claims (at 0.95 it
+ * replaced 54% of new coexisting claims). So the threshold is looked up by
+ * `provider:model@dims`, and a model with no calibrated entry does not
+ * supersede by cosine at all: the new fact is inserted, and the conflict
+ * review sweep (decide slot `conflict`, where enabled) judges the pair.
+ * Exact-text duplicates (`gbrain_fact_fingerprint`) are decided before any
+ * cosine and are unaffected.
+ *
+ * Operators register a measured value without a release:
+ * gbrain config set facts.supersession_thresholds '{"openai:text-embedding-3-large@1536": 0.97}'
+ * A value of "off" disables cosine supersession for a calibrated model.
+ */
+export const SUPERSESSION_THRESHOLDS_KEY = 'facts.supersession_thresholds';
+
+/** Measured thresholds, keyed `provider:model@dims`. Add a row only with an eval behind it. */
+export const SUPERSESSION_CALIBRATIONS: Readonly<Record<string, { threshold: number; evidence: string }>> = {
+ 'voyage:voyage-4@1024': { threshold: 0.95, evidence: 'docs/eval/decisions/supersession-threshold-dev' },
+};
+
+export type SupersessionThresholdSource = 'calibrated' | 'override' | 'uncalibrated';
+
+export interface SupersessionThreshold {
+ /** `provider:model@dims`, the table and override key. */
+ key: string;
+ /** Null: this model never supersedes by cosine. */
+ threshold: number | null;
+ source: SupersessionThresholdSource;
+}
+
+export function calibrationKey(model: string | null | undefined, dims: number): string {
+ return `${(model ?? '').trim().toLowerCase()}@${dims}`;
+}
+
+/** `{ "<provider:model@dims>": number in (0, 1] | "off" }`; malformed JSON or values are ignored. */
+export function parseThresholdOverrides(raw: string | null | undefined): Map<string, number | null> {
+ const out = new Map<string, number | null>();
+ if (!raw?.trim()) return out;
+ let parsed: unknown;
+ try { parsed = JSON.parse(raw); } catch { return out; }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return out;
+ for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
+ const key = k.trim().toLowerCase();
+ if (v === 'off') out.set(key, null);
+ else if (typeof v === 'number' && Number.isFinite(v) && v > 0 && v <= 1) out.set(key, v);
+ }
+ return out;
+}
+
+export function resolveSupersessionThreshold(model: string | null | undefined, dims: number, overrides: Map<string, number | null> = new Map()): SupersessionThreshold {
+ const key = calibrationKey(model, dims);
+ if (overrides.has(key)) return { key, threshold: overrides.get(key)!, source: 'override' };
+ const calibrated = SUPERSESSION_CALIBRATIONS[key];
+ return calibrated ? { key, threshold: calibrated.threshold, source: 'calibrated' } : { key, threshold: null, source: 'uncalibrated' };
+}
+
+/** The threshold for this brain's facts embedded with `model` at `dims`; config errors read as no overrides. */
+export async function readSupersessionThreshold(
+ engine: { getConfig(key: string): Promise<string | null> },
+ model: string | null | undefined,
+ dims: number,
+): Promise<SupersessionThreshold> {
+ const raw = await engine.getConfig(SUPERSESSION_THRESHOLDS_KEY).catch(() => null);
+ return resolveSupersessionThreshold(model, dims, parseThresholdOverrides(raw));
+}
diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.ts
index e48e72cdd1..d614b9cdf0 100644
--- a/src/core/facts/write-single.ts
+++ b/src/core/facts/write-single.ts
@@ -4,8 +4,8 @@
*
* `runFactsPipeline` is extraction-first (LLM-gated in extract.ts) and cannot
* back a verb whose fact arrives pre-formed. This module reuses the pipeline's
- * post-extraction stages directly: resolve → dedup (embedding cosine, same
- * 0.95 threshold) → fence-first write (markdown durability) with the same
+ * post-extraction stages directly: resolve → dedup (embedding cosine at the
+ * model's calibrated threshold, supersession-threshold.ts) → fence-first write (markdown durability) with the same
* legacy DB-only fallbacks (thin-client, unparented, stub-guard).
*
* Supersession [X1, frozen as implementation-defined]: minimal deterministic
@@ -25,7 +25,6 @@
import type { BrainEngine, FactInsertStatus, NewFact } from '../engine.ts';
-const DEDUP_THRESHOLD = 0.95;
const DEDUP_CANDIDATE_LIMIT = 5;
/**
@@ -157,8 +156,9 @@ export async function writeSingleFact(
top = c;
}
}
- if (top && topScore >= DEDUP_THRESHOLD) {
- const textDiffers = collapse(top.fact) !== collapse(factText);
+ const { threshold } = await (await import('./supersession-threshold.ts')).readSupersessionThreshold(engine, embeddingModel, embedding.length);
+ const textDiffers = top !== null && collapse(top.fact) !== collapse(factText);
+ if (top && (!textDiffers || threshold !== null && topScore >= threshold)) {
if (top.kind === kind && textDiffers) {
supersedeId = top.id; // X1: near-duplicate with changed content = update
} else {
diff --git a/test/doctor-supersession-calibration.test.ts b/test/doctor-supersession-calibration.test.ts
new file mode 100644
index 0000000000..ea5a5a0332
--- /dev/null
+++ b/test/doctor-supersession-calibration.test.ts
@@ -0,0 +1,81 @@
+/**
+ * supersession_calibration doctor check: informational, names an uncalibrated
+ * embedding model with the calibrate-and-register action, reports a calibrated
+ * or operator threshold as ok, and is not applicable on a keyless brain.
+ * PGLite in-memory ($0).
+ */
+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 { supersessionCalibrationEntry } from '../src/commands/doctor/checks/supersession-calibration.ts';
+import { categorizeCheck } from '../src/core/doctor-categories.ts';
+import type { Action } from '../src/core/agent-output.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+let engine: PGLiteEngine;
+const run = async () => (await supersessionCalibrationEntry.run({ engine, progress: { heartbeat() {} } } as never) as Check[])[0];
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ resetGateway();
+}, 60_000);
+
+describe('supersession_calibration', () => {
+ test('a calibrated default model is ok', async () => {
+ configureGateway({ embedding_model: 'voyage:voyage-4', embedding_dimensions: 1024, env: { VOYAGE_API_KEY: 'k' } });
+ const check = await run();
+ expect(check).toMatchObject({ name: 'supersession_calibration', status: 'ok', details: { key: 'voyage:voyage-4@1024', threshold: 0.95, source: 'calibrated' } });
+ expect(check.fix).toBeUndefined();
+ expect(categorizeCheck('supersession_calibration')).toBe('brain');
+ });
+
+ test('an uncalibrated model is informational, names the model and carries the calibrate → sweep → register action', async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'k' } });
+ await engine.setConfig('facts.supersession_thresholds', JSON.stringify({ 'other:model@8': 0.9 }));
+ try {
+ const check = await run();
+ expect(check).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'degraded', details: { key: 'openai:text-embedding-3-large@1536', threshold: null, source: 'uncalibrated' } });
+ expect(check.message).toContain('openai:text-embedding-3-large@1536 has no calibrated fact supersession threshold');
+ const fix = check.fix as Action;
+ expect(fix.consent).toEqual(['paid', 'egress']);
+ expect(fix.user_message).toContain('about a cent');
+ expect(fix.argv!.slice(2, 7)).toEqual(['embed', '--model', 'openai:text-embedding-3-large', '--dims', '1536']);
+ expect(fix.argv![1]).toMatch(/scripts\/eval-c2-candidate-fusion\.ts$/);
+ expect(fix.then!.argv).toContain('0.80:0.97:0.01');
+ const register = fix.then!.then!;
+ expect(register.argv!.slice(0, 4)).toEqual(['gbrain', 'config', 'set', 'facts.supersession_thresholds']);
+ expect(register.argv![4]).toBe('{"other:model@8":0.9,"openai:text-embedding-3-large@1536":THRESHOLD}');
+ expect(register.inputs![0].name).toBe('THRESHOLD');
+ expect(register.verify!.argv).toEqual(['gbrain', 'doctor', '--only', 'supersession_calibration', '--json']);
+ } finally {
+ await engine.unsetConfig('facts.supersession_thresholds');
+ }
+ });
+
+ test('an operator threshold is ok; "off" is disabled by choice', async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'k' } });
+ await engine.setConfig('facts.supersession_thresholds', JSON.stringify({ 'openai:text-embedding-3-large@1536': 0.97 }));
+ try {
+ expect(await run()).toMatchObject({ status: 'ok', details: { threshold: 0.97, source: 'override' } });
+ await engine.setConfig('facts.supersession_thresholds', JSON.stringify({ 'openai:text-embedding-3-large@1536': 'off' }));
+ expect(await run()).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice' });
+ } finally {
+ await engine.unsetConfig('facts.supersession_thresholds');
+ }
+ });
+
+ test('a brain with embeddings off is not applicable', async () => {
+ await engine.setConfig('embedding_disabled', 'true');
+ try {
+ expect(await run()).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'not_applicable' });
+ } finally {
+ await engine.unsetConfig('embedding_disabled');
+ }
+ });
+});
diff --git a/test/facts-classify.test.ts b/test/facts-classify.test.ts
index ce889b4376..80adf542bb 100644
--- a/test/facts-classify.test.ts
+++ b/test/facts-classify.test.ts
@@ -50,7 +50,9 @@ function makeFact(overrides: Partial<FactRow> & { id: number }): FactRow {
};
}
-const EMBED_LEN = 8;
+/** voyage-4's width: the cosine defaults come from its calibrated threshold (supersession-threshold.ts). */
+const EMBED_LEN = 1024;
+const VOYAGE = { embeddingModel: 'voyage:voyage-4' };
function vec(...values: number[]): Float32Array {
const a = new Float32Array(EMBED_LEN);
for (let i = 0; i < values.length; i++) a[i] = values[i];
@@ -96,6 +98,7 @@ describe('classifyAgainstCandidates', () => {
const result = await classifyAgainstCandidates(
{ fact: 'new', kind: 'fact', embedding: vec(1) },
candidates,
+ VOYAGE,
);
expect(result.decision).toBe('duplicate');
expect((result as { matched_id: number }).matched_id).toBe(42);
@@ -115,6 +118,7 @@ describe('classifyAgainstCandidates', () => {
const result = await classifyAgainstCandidates(
{ fact: 'new', kind: 'fact', embedding: a },
candidates,
+ VOYAGE,
);
// Gateway configured with env:{} above → isAvailable('chat') is false →
// straight to cosine fallback. cos ≈ 0.93 ≥ 0.92 → duplicate.
@@ -122,6 +126,14 @@ describe('classifyAgainstCandidates', () => {
expect((result as { reason: string }).reason).toBe('cosine_fallback');
});
+ test('an uncalibrated embedding model has no cosine fast path or cosine fallback', async () => {
+ const candidates = [makeFact({ id: 42, embedding: vec(1) })];
+ for (const opts of [{}, { embeddingModel: 'openai:text-embedding-3-large' }]) {
+ const result = await classifyAgainstCandidates({ fact: 'new', kind: 'fact', embedding: vec(1) }, candidates, opts);
+ expect(result).toEqual({ decision: 'independent', reason: 'cosine_fallback' });
+ }
+ });
+
test('no embedding on new fact → falls through to classifier path or cosine fallback', async () => {
const candidates = [makeFact({ id: 7, embedding: vec(1) })];
const result = await classifyAgainstCandidates(
@@ -159,6 +171,7 @@ describe('classify gate — key-aware, engine-free (CX10)', () => {
const r = await classifyAgainstCandidates(
{ fact: 'x', kind: 'fact', embedding: vec(0.93, Math.sqrt(1 - 0.93 * 0.93), 0) },
[existing],
+ VOYAGE,
);
expect(r.reason).toBe('cosine_fallback');
expect(r.decision).toBe('duplicate');
diff --git a/test/facts-supersede-not-withdrawal.test.ts b/test/facts-supersede-not-withdrawal.test.ts
index 802af5db05..1fb31e70f1 100644
--- a/test/facts-supersede-not-withdrawal.test.ts
+++ b/test/facts-supersede-not-withdrawal.test.ts
@@ -37,6 +37,8 @@ beforeEach(async () => {
brainDir = mkdtempSync(join(tmpdir(), 'supersede-'));
await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brainDir]);
configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIM, env: { OPENAI_API_KEY: 'sk-test-deterministic' } });
+ // Calibrate the deterministic test embedder: an uncalibrated model never supersedes by cosine (supersession-threshold.ts).
+ await engine.setConfig('facts.supersession_thresholds', JSON.stringify({ [`openai:text-embedding-3-small@${DIM}`]: 0.95 }));
__setEmbedTransportForTests((async (opts: { values: string[] }) => ({
embeddings: opts.values.map(t => {
const v = new Array(DIM).fill(0);
diff --git a/test/facts/candidate-fusion.test.ts b/test/facts/candidate-fusion.test.ts
index 235ff9ca32..538d6a82ac 100644
--- a/test/facts/candidate-fusion.test.ts
+++ b/test/facts/candidate-fusion.test.ts
@@ -20,6 +20,8 @@ beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
+ // Calibrate the synthetic model: an uncalibrated model never supersedes by cosine (supersession-threshold.ts).
+ await engine.setConfig('facts.supersession_thresholds', JSON.stringify({ [`${MODEL}@1536`]: 0.95 }));
});
afterAll(async () => {
diff --git a/test/facts/capture-dedup-policy.test.ts b/test/facts/capture-dedup-policy.test.ts
index 4d04ef4769..3cb1319c8f 100644
--- a/test/facts/capture-dedup-policy.test.ts
+++ b/test/facts/capture-dedup-policy.test.ts
@@ -29,7 +29,13 @@ describe('cosineVerdict', () => {
['changed month is distinct', 'sweep:corpus', 0.97, 'The renewal closes in November', 'The renewal closes in December', 'distinct'],
['changed date is distinct', 'hook:compact', 0.97, 'Launch is on 2026-10-02', 'Launch is on 2026-10-09', 'distinct'],
] as const)('%s', (_label, lane, score, a, b, verdict) => {
- expect(cosineVerdict(lane, score, a, b)).toBe(verdict);
+ // 0.95: voyage-4@1024's calibrated explicit-lane threshold (supersession-threshold.ts).
+ expect(cosineVerdict(lane, score, a, b, 0.95)).toBe(verdict);
+ });
+
+ test('an uncalibrated embedding model (null threshold) never makes an explicit-lane duplicate', () => {
+ expect(cosineVerdict('mcp:extract_facts', 0.999, same, same, null)).toBe('distinct');
+ expect(cosineVerdict('hook:writeback', 0.99, same, 'Alice Example relocates to NYC', null)).toBe('near_duplicate');
});
});
diff --git a/test/facts/supersession-threshold.test.ts b/test/facts/supersession-threshold.test.ts
new file mode 100644
index 0000000000..2b2183375a
--- /dev/null
+++ b/test/facts/supersession-threshold.test.ts
@@ -0,0 +1,132 @@
+/**
+ * Per-model fact supersession threshold (supersession-threshold.ts): table
+ * lookup and operator overrides; voyage-4@1024 decides exactly as the old
+ * fixed 0.95 rule did; an uncalibrated model never supersedes by cosine,
+ * keeps exact-text dedup, and its pair reaches the conflict review sweep.
+ * PGLite in-memory, no provider calls.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { decideSingleFact } from '../../src/core/facts/single-prepare.ts';
+import { writeSingleFact } from '../../src/core/facts/write-single.ts';
+import { conflictNeighbours, factsAfter } from '../../src/core/ai/decide/proposals-store.ts';
+import {
+ SUPERSESSION_CALIBRATIONS, SUPERSESSION_THRESHOLDS_KEY, calibrationKey, parseThresholdOverrides, resolveSupersessionThreshold,
+} from '../../src/core/facts/supersession-threshold.ts';
+
+const DIM = 1024;
+const VOYAGE = 'voyage:voyage-4';
+const OPENAI = 'openai:text-embedding-3-large';
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ resetGateway();
+ configureGateway({ embedding_model: VOYAGE, embedding_dimensions: DIM, env: { VOYAGE_API_KEY: 'test-voyage-key' } });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ await engine.disconnect();
+ resetGateway();
+});
+
+/** Unit vector whose cosine to `vec(1)` is exactly `c`. */
+const vec = (c: number, axis = 1): Float32Array => {
+ const a = new Float32Array(DIM);
+ a[0] = c;
+ a[axis] = Math.sqrt(1 - c * c);
+ return a;
+};
+
+let n = 0;
+async function seedPair(model: string, cosine: number) {
+ const slug = `companies/threshold-${++n}`;
+ const old = await engine.insertFact({ fact: `Threshold Example ${n} has 40 employees.`, kind: 'fact', entity_slug: slug, visibility: 'world', source: 'test',
+ embedding: vec(1), embedding_model: model }, { source_id: 'default' });
+ const decide = (fact = `Threshold Example ${n} has 45 employees.`) =>
+ decideSingleFact(engine, 'default', { fact, kind: 'fact', visibility: 'world', entity_slug: slug }, vec(cosine, 2), model);
+ return { slug, oldId: old.id, decide, oldText: `Threshold Example ${n} has 40 employees.` };
+}
+
+describe('lookup', () => {
+ test('voyage-4 at 1024 dimensions is calibrated at 0.95; other widths and models are not', () => {
+ expect(SUPERSESSION_CALIBRATIONS['voyage:voyage-4@1024'].threshold).toBe(0.95);
+ expect(resolveSupersessionThreshold(VOYAGE, 1024)).toEqual({ key: 'voyage:voyage-4@1024', threshold: 0.95, source: 'calibrated' });
+ expect(resolveSupersessionThreshold('Voyage:Voyage-4', 1024).threshold).toBe(0.95);
+ expect(resolveSupersessionThreshold(VOYAGE, 2048)).toEqual({ key: 'voyage:voyage-4@2048', threshold: null, source: 'uncalibrated' });
+ expect(resolveSupersessionThreshold(OPENAI, 1536)).toEqual({ key: 'openai:text-embedding-3-large@1536', threshold: null, source: 'uncalibrated' });
+ expect(resolveSupersessionThreshold(null, 1024).source).toBe('uncalibrated');
+ expect(calibrationKey(' OpenAI:Text-Embedding-3-Large ', 1536)).toBe('openai:text-embedding-3-large@1536');
+ });
+
+ test('operator overrides win, "off" disables, malformed values are ignored', () => {
+ const o = parseThresholdOverrides(JSON.stringify({ 'OpenAI:text-embedding-3-large@1536': 0.97, 'voyage:voyage-4@1024': 'off', 'x@1': 1.5, 'y@1': 'high', 'z@1': 0 }));
+ expect([...o.entries()]).toEqual([['openai:text-embedding-3-large@1536', 0.97], ['voyage:voyage-4@1024', null]]);
+ expect(resolveSupersessionThreshold(OPENAI, 1536, o)).toEqual({ key: 'openai:text-embedding-3-large@1536', threshold: 0.97, source: 'override' });
+ expect(resolveSupersessionThreshold(VOYAGE, 1024, o)).toEqual({ key: 'voyage:voyage-4@1024', threshold: null, source: 'override' });
+ for (const raw of [null, '', 'not json', '[1]', '"x"']) expect(parseThresholdOverrides(raw).size).toBe(0);
+ });
+});
+
+describe('decideSingleFact', () => {
+ test('voyage-4@1024 keeps the 0.95 boundary exactly', async () => {
+ expect((await (await seedPair(VOYAGE, 0.9505)).decide()).status).toBe('superseded');
+ expect((await (await seedPair(VOYAGE, 0.9495)).decide()).status).toBe('inserted');
+ const near = await seedPair(VOYAGE, 0.99);
+ const d = await near.decide();
+ expect(d.status).toBe('superseded');
+ expect(d.candidate?.id).toBe(near.oldId);
+ });
+
+ test('an uncalibrated model inserts instead of superseding, keeps exact-text dedup, and its pair reaches conflict review', async () => {
+ const before = Number((await engine.executeRaw<{ m: number }>('SELECT COALESCE(MAX(id), 0) AS m FROM facts'))[0].m);
+ const pair = await seedPair(OPENAI + '-uncal', 0.99);
+ expect((await pair.decide()).status).toBe('inserted');
+ expect((await pair.decide(pair.oldText)).status).toBe('duplicate');
+ const added = await engine.insertFact({ fact: `Threshold Example ${n} has 45 employees.`, kind: 'fact', entity_slug: pair.slug, visibility: 'world', source: 'test',
+ embedding: vec(0.99, 2), embedding_model: OPENAI + '-uncal' }, { source_id: 'default' });
+ const swept = await factsAfter(engine, 'default', before, 100);
+ expect(swept.map(f => Number(f.id))).toContain(added.id);
+ const neighbours = await conflictNeighbours(engine, added.id, 'default');
+ expect(neighbours.map(c => c.id)).toContain(pair.oldId);
+ expect(neighbours.find(c => c.id === pair.oldId)!.similarity).toBeGreaterThan(0.98);
+ });
+
+ test('an operator threshold makes an uncalibrated model supersede; "off" stops a calibrated one', async () => {
+ const pair = await seedPair(OPENAI + '-op', 0.97);
+ await engine.setConfig(SUPERSESSION_THRESHOLDS_KEY, JSON.stringify({ [`${OPENAI}-op@${DIM}`]: 0.96, [`${VOYAGE}@${DIM}`]: 'off' }));
+ try {
+ expect((await pair.decide()).status).toBe('superseded');
+ expect((await (await seedPair(VOYAGE, 0.99)).decide()).status).toBe('inserted');
+ } finally {
+ await engine.unsetConfig(SUPERSESSION_THRESHOLDS_KEY);
+ }
+ });
+});
+
+describe('writeSingleFact (unmanaged path)', () => {
+ test('an uncalibrated model never supersedes, and identical text is still a duplicate', async () => {
+ configureGateway({ embedding_model: OPENAI, embedding_dimensions: DIM, env: { OPENAI_API_KEY: 'sk-test-deterministic' } });
+ __setEmbedTransportForTests((async (opts: { values: string[] }) => ({
+ embeddings: opts.values.map(t => Array.from(t.includes('PAIR') ? vec(1) : vec(0.1, 3))),
+ })) as never);
+ try {
+ const remember = (fact: string) => writeSingleFact(engine, 'default', { fact, provenance: 'test', entity: 'people/uncalibrated-example', kind: 'fact' });
+ const a = await remember('PAIR alice works at acme-example');
+ expect(a.status).toBe('inserted');
+ const dup = await remember('PAIR alice works at acme-example');
+ expect(dup.status).toBe('duplicate');
+ expect(dup.id).toBe(a.id);
+ const changed = await remember('PAIR alice left acme-example');
+ expect(changed.status).toBe('inserted');
+ expect(changed.id).not.toBe(a.id);
+ } finally {
+ __setEmbedTransportForTests(null);
+ configureGateway({ embedding_model: VOYAGE, embedding_dimensions: DIM, env: { VOYAGE_API_KEY: 'test-voyage-key' } });
+ }
+ });
+});
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 22c4a12451..43665b5968 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -554,6 +554,98 @@
"name": "embedding_migration_state",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "config_key": "facts.supersession_thresholds",
+ "dims": 3072,
+ "docs": "docs/eval/decisions/supersession-threshold-dev/README.md",
+ "key": "openai:text-embedding-3-large@3072",
+ "model": "openai:text-embedding-3-large",
+ "source": "uncalibrated",
+ "threshold": null
+ },
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "bun",
+ "<repo>/scripts/eval-c2-candidate-fusion.ts",
+ "embed",
+ "--model",
+ "openai:text-embedding-3-large",
+ "--dims",
+ "3072",
+ "--out",
+ "<tmp>/gbrain-supersession-openai-text-embedding-3-large-3072.json.gz"
+ ],
+ "command": "bun <repo>/scripts/eval-c2-candidate-fusion.ts embed --model openai:text-embedding-3-large --dims 3072 --out <tmp>/gbrain-supersession-openai-text-embedding-3-large-3072.json.gz",
+ "consent": [
+ "paid",
+ "egress"
+ ],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/eval/decisions/supersession-threshold-dev/README.md",
+ "next": "ask_user",
+ "requires_exclusive": false,
+ "then": {
+ "actor": "agent",
+ "argv": [
+ "bun",
+ "<repo>/scripts/eval-c2-candidate-fusion.ts",
+ "run",
+ "--embeddings",
+ "<tmp>/gbrain-supersession-openai-text-embedding-3-large-3072.json.gz",
+ "--taus",
+ "0.80:0.97:0.01"
+ ],
+ "command": "bun <repo>/scripts/eval-c2-candidate-fusion.ts run --embeddings <tmp>/gbrain-supersession-openai-text-embedding-3-large-3072.json.gz --taus 0.80:0.97:0.01",
+ "consent": [],
+ "next": "run",
+ "requires_exclusive": false,
+ "then": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "config",
+ "set",
+ "facts.supersession_thresholds",
+ "{\"openai:text-embedding-3-large@3072\":THRESHOLD}",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain config set facts.supersession_thresholds '{\"openai:text-embedding-3-large@3072\":THRESHOLD}' --brain host",
+ "consent": [],
+ "inputs": [
+ {
+ "how": "threshold_pick.guarded from the previous step's JSON output. When it is null no threshold is safe for this model: skip this step and leave supersession off.",
+ "name": "THRESHOLD"
+ }
+ ],
+ "next": "run",
+ "requires_exclusive": false,
+ "verify": {
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "supersession_calibration",
+ "--json",
+ "--brain",
+ "host"
+ ]
+ },
+ "why": "Registers the measured threshold for this model; the next fact write uses it. Remove it with gbrain config unset facts.supersession_thresholds."
+ },
+ "why": "Replays the fixture at each threshold on a throwaway in-memory brain (no provider calls) and prints threshold_pick.guarded: the threshold that misses the fewest corrections while false supersession stays at or under 1% and 99.5% of distinct claims survive."
+ },
+ "user_message": "Facts saved on this brain never replace a similar older fact automatically, because its embedding model (openai:text-embedding-3-large@3072) has no measured threshold. Measuring one sends about 23K tokens of synthetic test sentences to the embedding provider (about a cent). OK to run it?",
+ "why": "Supersession by similarity is off for openai:text-embedding-3-large@3072 until a threshold is measured for it. This embeds the synthetic C2 fixture (1,506 test sentences, about 23K tokens) with openai:text-embedding-3-large; no brain content is sent."
+ },
+ "message": "Embedding model openai:text-embedding-3-large@3072 has no calibrated fact supersession threshold, so a saved fact never replaces a similar older one by similarity: it is inserted beside it (exact-text duplicates still collapse), and the conflict review sweep judges the pair where it is on. Measure one with the C2 fixture (about a cent), then register it in facts.supersession_thresholds. See docs/eval/decisions/supersession-threshold-dev/README.md.",
+ "name": "supersession_calibration",
+ "readiness_state": "degraded",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "No entity pages — graph_coverage not applicable (markdown-only brain)",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 153d996111..1646172a06 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -642,6 +642,14 @@
"name": "embedding_migration_state",
"status": "ok"
},
+ {
+ "category": "brain",
+ "message": "Embeddings are off on this brain, so facts are only deduplicated by exact text; no supersession threshold applies.",
+ "name": "supersession_calibration",
+ "readiness_state": "not_applicable",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "No entity pages — graph_coverage not applicable (markdown-only brain)",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 9ebd3e303b..8f9b16681b 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -631,6 +631,14 @@
"name": "embedding_migration_state",
"status": "ok"
},
+ {
+ "category": "brain",
+ "message": "Embeddings are off on this brain, so facts are only deduplicated by exact text; no supersession threshold applies.",
+ "name": "supersession_calibration",
+ "readiness_state": "not_applicable",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "No entity pages — graph_coverage not applicable (markdown-only brain)",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 4c4c6b7532..37b09d90c7 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -325,6 +325,10 @@
"category": "brain",
"name": "embedding_migration_state"
},
+ {
+ "category": "brain",
+ "name": "supersession_calibration"
+ },
{
"category": "brain",
"name": "graph_coverage"
diff --git a/test/managed-facts-writers.test.ts b/test/managed-facts-writers.test.ts
index fa060ed5de..c73606eeb1 100644
--- a/test/managed-facts-writers.test.ts
+++ b/test/managed-facts-writers.test.ts
@@ -246,6 +246,8 @@ test('managed writeSingleFact supersedes a near-duplicate of the same kind like
await managed(async ({ engine, put }) => {
await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
await engine.setConfig('embedding_dimensions', '1536');
+ // Calibrate the test embedder: an uncalibrated model never supersedes by cosine (supersession-threshold.ts).
+ await engine.setConfig('facts.supersession_thresholds', JSON.stringify({ 'openai:text-embedding-3-large@1536': 0.95 }));
await put('people/alice-example', PERSON('Alice Example'));
}, async ({ engine, sourceId, root }) => {
const remember = (fact: string) => writeSingleFact(engine, sourceId, { fact, provenance: 'fixture', entity: 'people/alice-example', visibility: 'world' });
diff --git a/test/memory-verbs-conformance.test.ts b/test/memory-verbs-conformance.test.ts
index 931862c2dc..ab15e62359 100644
--- a/test/memory-verbs-conformance.test.ts
+++ b/test/memory-verbs-conformance.test.ts
@@ -682,6 +682,8 @@ describe('writeSingleFact — supersession rule [X1] + degraded dedup', () => {
it('near-duplicate with changed text and same kind SUPERSEDES; identical text is a duplicate', async () => {
installDeterministicEmbedder();
+ // Calibrate the deterministic test embedder: an uncalibrated model never supersedes by cosine (supersession-threshold.ts).
+ await engine.setConfig('facts.supersession_thresholds', JSON.stringify({ 'openai:text-embedding-3-small@1536': 0.95 }));
const a = await writeSingleFact(engine, 'default', {
fact: 'SUPERSEDE-PAIR alice works at acme-example',
provenance: 'test', entity: 'people/supersede-test', kind: 'fact',