Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): one-shot calibrate for the doctor fix; calibrate test embedders
garrytan38bf1d97f5d3
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 1bed5d9d09..7f574754b8 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -89,9 +89,9 @@ rejection of serve-only flags before a brain opens.- `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/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 calibrate → 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/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 two-step `fix` (`bun <repo>/scripts/eval-c2-candidate-fusion.ts calibrate <model> <dims> <out>` with consent `paid`+`egress` and a user message: embeds the fixture, sweeps 0.80–0.97 on the default arm and prints `threshold_pick.guarded`; then `gbrain config set facts.supersession_thresholds` merging existing entries with the `THRESHOLD` input; verify `gbrain doctor --only supersession_calibration --json`). No flag literals appear in the check, so the CLI flag registry is unchanged. 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`).diff --git a/docs/eval/decisions/supersession-threshold-dev/README.md b/docs/eval/decisions/supersession-threshold-dev/README.mdindex 486c6fda2f..64a4aee045 100644--- a/docs/eval/decisions/supersession-threshold-dev/README.md+++ b/docs/eval/decisions/supersession-threshold-dev/README.md@@ -72,7 +72,10 @@ Fix 1 below is in the memory proof wave. Fix 2 is not.- **Override.** `facts.supersession_thresholds` takes a JSON map `{"provider:model@dims": number | "off"}`, so anoperator 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.+ model and returns two commands, which need consent because the first one costs money:+ `bun scripts/eval-c2-candidate-fusion.ts calibrate <provider:model> <dims> <out>` embeds the fixture (about a+ cent), sweeps 0.80 to 0.97 and prints `threshold_pick.guarded`; then+ `gbrain config set facts.supersession_thresholds` registers the result.## Proposed fix@@ -81,9 +84,9 @@ Fix 1 below is in the memory proof wave. Fix 2 is not.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 existingconflict review where that is enabled. At 0.95 on 3-large, that gives up the 37% of corrections it- catches today and removes the 54% of wrong replacements. `gbrain doctor` could flag a brain whose embedding model has- no calibrated threshold. This fixture calibrates a new model for about a cent:- `bun scripts/eval-c2-candidate-fusion.ts embed …` then `run … --taus 0.80:0.97:0.01`.+ catches today and removes the 54% of wrong replacements. `gbrain doctor` flags a brain whose embedding model has+ no calibrated threshold. This fixture calibrates a new model for about a cent with+ `bun scripts/eval-c2-candidate-fusion.ts calibrate <provider:model> <dims> <out>`.2. **Make supersession slot-aware.** The remaining misses need more than a threshold. Supersession can usethe claim slot: the typed `claim_metric` and `claim_period` columns when both rows carry them, or thecaller-named target from `remember.replaces` (#6027). Then cosine only nominates candidates, and the slotdiff --git a/scripts/eval-c2-candidate-fusion.ts b/scripts/eval-c2-candidate-fusion.tsindex dd5c612da7..fdf44a4427 100644--- a/scripts/eval-c2-candidate-fusion.ts+++ b/scripts/eval-c2-candidate-fusion.ts@@ -207,7 +207,7 @@ function loadEmbeddings(path: string, texts: string[]): { model: string; dims: n* 24K tokens. Vectors are stored as float32 so cosines near the threshold* are exact.*/-async function embedWithGateway(model: string, dims: number, outPath: string): Promise<void> {+async function embedWithGateway(model: string, dims: number, outPath: string): Promise<Record<string, unknown>> {const { embed } = await import('../src/core/ai/gateway.ts');const { estimateTokens } = await import('../src/core/chunkers/token-estimate.ts');const texts = fixtureTexts(buildFixture());@@ -224,7 +224,7 @@ async function embedWithGateway(model: string, dims: number, outPath: string): P}const tokens = texts.reduce((n, t) => n + estimateTokens(t), 0);writeFileSync(outPath, gzipSync(JSON.stringify({ model, dims, texts_sha256: sha256(JSON.stringify(texts)), vectors })));- console.log(JSON.stringify({ model, dims, texts: texts.length, approx_cl100k_tokens: tokens, out: outPath }));+ return { model, dims, texts: texts.length, approx_cl100k_tokens: tokens, out: outPath };}// ---------------------------------------------------------------------------@@ -389,24 +389,7 @@ async function run(embeddingsPath: string, outDir: string | null, taus: number[]}return counts;};- for (const mode of MODES) {- const ps = arms[mode].probes;- const rate = (num: number, den: number) => den === 0 ? null : round(num / den);- const corr = ps.filter(p => p.has_twin && (p.kind === 'correction' || p.kind === 'concurrent' || p.kind === 'private_correction'));- const rest = ps.filter(p => p.has_twin && p.kind === 'restatement');- const coex = ps.filter(p => p.kind === 'coexisting');- const kept = Object.values(arms[mode].preserved);- sweep.push({- threshold: tau, arm: mode,- correction_miss_rate: rate(corr.filter(p => p.outcome === 'missed').length, corr.length),- restatement_miss_rate: rate(rest.filter(p => p.outcome === 'missed').length, rest.length),- coexisting_false_supersession_rate: rate(coex.filter(p => p.outcome === 'false_supersession').length, coex.length),- false_supersession_rate: rate(ps.filter(p => p.outcome === 'false_supersession').length, ps.length),- preserved_distinct_share: rate(kept.reduce((n, k) => n + k.preserved, 0), kept.reduce((n, k) => n + k.claims, 0)),- correct_decision_rate: rate(ps.filter(p => p.outcome === 'correct').length, ps.length),- stale_single_value_claims_at_end: arms[mode].stale_claims,- });- }+ for (const mode of MODES) sweep.push(sweepRow(arms[mode], tau, mode));sources.push({source: `c2-twin-fixture-tau-${tau}`, verdict, threshold: tau,arms: { baseline: { config: { [CANDIDATE_FUSION_KEY]: 'rrf_free' } }, candidate: { config: { [CANDIDATE_FUSION_KEY]: 'interleave' } } },@@ -437,17 +420,7 @@ async function run(embeddingsPath: string, outDir: string | null, taus: number[]// rate whose false supersession stays at or under 1% of probes and whose// preserved distinct claims stay at or over 99.5%; plus the equal-weight// balance (correction miss + coexisting false supersession).- const base = sweep.filter(r => r.arm === 'rrf_free');- const num = (r: Record<string, unknown>, k: string) => Number(r[k] ?? 0);- const safe = base.filter(r => num(r, 'false_supersession_rate') <= 0.01 && num(r, 'preserved_distinct_share') >= 0.995);- const pickMin = (rows: Array<Record<string, unknown>>, f: (r: Record<string, unknown>) => number) =>- rows.length === 0 ? null : rows.reduce((a, b) => f(b) < f(a) ? b : a).threshold;- const thresholdPick = {- 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: resolveSupersessionThreshold(model, store.dims).threshold,- };+ const thresholdPick = { ...pickThreshold(sweep.filter(r => r.arm === 'rrf_free')), product: resolveSupersessionThreshold(model, store.dims).threshold };const decidedAt = new Date().toISOString();const verdictJson = {decision_id: decisionId, plan: 'MEMORY_PROOF_WAVE C2', stage: 'dev', eligible_for_default: false,@@ -462,6 +435,62 @@ async function run(embeddingsPath: string, outDir: string | null, taus: number[]const round = (x: number) => Math.round(x * 10_000) / 10_000;+type SweepRow = Record<string, unknown> & { threshold: number };++function sweepRow(arm: ArmResult, tau: number, mode: CandidateFusion): SweepRow {+ const ps = arm.probes;+ const rate = (num: number, den: number) => den === 0 ? null : round(num / den);+ const corr = ps.filter(p => p.has_twin && (p.kind === 'correction' || p.kind === 'concurrent' || p.kind === 'private_correction'));+ const rest = ps.filter(p => p.has_twin && p.kind === 'restatement');+ const coex = ps.filter(p => p.kind === 'coexisting');+ const kept = Object.values(arm.preserved);+ return {+ threshold: tau, arm: mode,+ correction_miss_rate: rate(corr.filter(p => p.outcome === 'missed').length, corr.length),+ restatement_miss_rate: rate(rest.filter(p => p.outcome === 'missed').length, rest.length),+ coexisting_false_supersession_rate: rate(coex.filter(p => p.outcome === 'false_supersession').length, coex.length),+ false_supersession_rate: rate(ps.filter(p => p.outcome === 'false_supersession').length, ps.length),+ preserved_distinct_share: rate(kept.reduce((n, k) => n + k.preserved, 0), kept.reduce((n, k) => n + k.claims, 0)),+ correct_decision_rate: rate(ps.filter(p => p.outcome === 'correct').length, ps.length),+ stale_single_value_claims_at_end: arm.stale_claims,+ };+}++/**+ * Preregistered pick over the rrf_free (default) rows: the lowest correction+ * miss rate whose false supersession stays at or under 1% of probes and whose+ * preserved distinct claims stay at or over 99.5%; plus the equal-weight+ * balance (correction miss + coexisting false supersession).+ */+function pickThreshold(rows: SweepRow[]) {+ const num = (r: SweepRow, k: string) => Number(r[k] ?? 0);+ const safe = rows.filter(r => num(r, 'false_supersession_rate') <= 0.01 && num(r, 'preserved_distinct_share') >= 0.995);+ const pickMin = (xs: SweepRow[], f: (r: SweepRow) => number) => xs.length === 0 ? null : xs.reduce((a, b) => f(b) < f(a) ? b : a).threshold;+ return {+ 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(rows, r => num(r, 'correction_miss_rate') + num(r, 'coexisting_false_supersession_rate')),+ };+}++/**+ * One-shot calibration for `gbrain doctor`'s supersession_calibration fix:+ * embed the fixture with the brain's model (paid, about a cent), sweep the+ * default arm over 0.80-0.97, print the key, the rows and the guarded pick.+ */+async function calibrate(model: string, dims: number, outPath: string): Promise<void> {+ await embedWithGateway(model, dims, outPath);+ const companies = buildFixture();+ const store = loadEmbeddings(outPath, fixtureTexts(companies));+ resetGateway();+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-offline-c2-eval-no-network' } });+ const rows: SweepRow[] = [];+ for (const tau of thresholdRange('0.80:0.97:0.01')) rows.push(sweepRow(await replay(dims, model, t => store.get(t), companies, 'rrf_free', tau), tau, 'rrf_free'));+ const pick = pickThreshold(rows);+ console.log(JSON.stringify({ key: calibrationKey(model, dims), threshold_pick: pick, threshold_sweep: rows,+ register: pick.guarded === null ? null : `gbrain config set ${SUPERSESSION_THRESHOLDS_KEY} '{"${calibrationKey(model, dims)}": ${pick.guarded}}'` }, null, 2));+}+/** `0.80:0.97:0.01` (inclusive range) or `0.85,0.9,0.95`. */function thresholdRange(spec: string): number[] {if (!spec.includes(':')) return spec.split(',').map(Number);@@ -483,13 +512,17 @@ if (import.meta.main) {const range = arg('--taus');const taus = range ? thresholdRange(range) : TAUS;await run(embeddings, arg('--out'), taus, arg('--decision-id') ?? 'c2-interleave-dev');+ } else if (cmd === 'calibrate') {+ const [model, dims, out] = rest;+ if (!model || !Number.isInteger(Number(dims)) || !out) { console.error('calibrate needs <provider:model> <dims> <out-file> (paid provider calls, about a cent)'); process.exit(2); }+ await calibrate(model, Number(dims), out);} else if (cmd === 'embed') {const arg = (flag: string) => { const i = rest.indexOf(flag); return i >= 0 ? rest[i + 1] : null; };const model = arg('--model'); const dims = Number(arg('--dims')); const out = arg('--out');if (!model || !Number.isInteger(dims) || !out) { console.error('embed needs --model <provider:model> --dims <n> --out <file> (paid provider calls)'); process.exit(2); }- await embedWithGateway(model, dims, out);+ console.log(JSON.stringify(await embedWithGateway(model, dims, out)));} else {- console.error('usage: bun scripts/eval-c2-candidate-fusion.ts texts | embed --model m --dims n --out f | run --embeddings <file> [--taus 0.80:0.97:0.01] [--decision-id id] [--out <dir>]');+ console.error('usage: bun scripts/eval-c2-candidate-fusion.ts texts | calibrate <model> <dims> <out> | embed --model m --dims n --out f | run --embeddings <file> [--taus 0.80:0.97:0.01] [--decision-id id] [--out <dir>]');process.exit(2);}}diff --git a/src/commands/doctor/checks/supersession-calibration.ts b/src/commands/doctor/checks/supersession-calibration.tsindex bde58b24a9..6b6ee28a99 100644--- a/src/commands/doctor/checks/supersession-calibration.ts+++ b/src/commands/doctor/checks/supersession-calibration.ts@@ -21,33 +21,26 @@ 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. */+/** Calibrate (paid, ask first: embeds the fixture, then sweeps for 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],+ argv: ['bun', SCRIPT, 'calibrate', model, String(dims), 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.`,+ 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}, then replays it at thresholds 0.80 to 0.97 on a throwaway in-memory brain (several minutes, no further provider calls) and prints threshold_pick.guarded. 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'],+ argv: ['gbrain', 'config', 'set', 'facts.supersession_thresholds', register],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.',+ 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 calibrate 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,- 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,- },},};}diff --git a/test/doctor-supersession-calibration.test.ts b/test/doctor-supersession-calibration.test.tsindex ea5a5a0332..03e06b14d8 100644--- a/test/doctor-supersession-calibration.test.ts+++ b/test/doctor-supersession-calibration.test.ts@@ -35,7 +35,7 @@ describe('supersession_calibration', () => {expect(categorizeCheck('supersession_calibration')).toBe('brain');});- test('an uncalibrated model is informational, names the model and carries the calibrate → sweep → register action', async () => {+ test('an uncalibrated model is informational, names the model and carries the calibrate → 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 {@@ -45,10 +45,10 @@ describe('supersession_calibration', () => {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!.slice(2, 5)).toEqual(['calibrate', 'openai:text-embedding-3-large', '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(fix.argv!.some(a => a.startsWith('--'))).toBe(false);+ const register = fix.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');diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 43665b5968..3357aceed9 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -570,15 +570,12 @@"argv": ["bun","<repo>/scripts/eval-c2-candidate-fusion.ts",- "embed",- "--model",+ "calibrate","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",+ "command": "bun <repo>/scripts/eval-c2-candidate-fusion.ts calibrate openai:text-embedding-3-large 3072 <tmp>/gbrain-supersession-openai-text-embedding-3-large-3072.json.gz","consent": ["paid","egress"@@ -589,56 +586,39 @@"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"+ "gbrain",+ "config",+ "set",+ "facts.supersession_thresholds",+ "{\"openai:text-embedding-3-large@3072\":THRESHOLD}",+ "--brain",+ "host"],- "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",+ "command": "gbrain config set facts.supersession_thresholds '{\"openai:text-embedding-3-large@3072\":THRESHOLD}' --brain host","consent": [],+ "inputs": [+ {+ "how": "threshold_pick.guarded from the calibrate 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,- "then": {- "actor": "agent",+ "verify": {"argv": ["gbrain",- "config",- "set",- "facts.supersession_thresholds",- "{\"openai:text-embedding-3-large@3072\":THRESHOLD}",+ "doctor",+ "--only",+ "supersession_calibration",+ "--json","--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."+ "why": "Registers the measured threshold for this model; the next fact write uses it. Remove it with gbrain config unset facts.supersession_thresholds."},"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."+ "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, then replays it at thresholds 0.80 to 0.97 on a throwaway in-memory brain (several minutes, no further provider calls) and prints threshold_pick.guarded. 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",diff --git a/test/persistence-memory-mutations.test.ts b/test/persistence-memory-mutations.test.tsindex a0676a6189..d86451160e 100644--- a/test/persistence-memory-mutations.test.ts+++ b/test/persistence-memory-mutations.test.ts@@ -199,6 +199,8 @@ describe('journaled memory publication, both engines', () => {try {for (const engine of engines) {const slug = 'people/supersede-example';+ // Calibrate the fixed 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 }));await setupPage(engine, slug);const privateMemory = await submitRememberMutation(context(engine), { fact: 'Confidential unrelated claim',provenance: 'test', entity: slug, visibility: 'private' }, 30_000);diff --git a/test/write-attribution.test.ts b/test/write-attribution.test.tsindex 678c9ebc36..556ca45c07 100644--- a/test/write-attribution.test.ts+++ b/test/write-attribution.test.ts@@ -192,6 +192,8 @@ describe('write attribution on a managed brain', () => {await withFixedEmbeddings(async () => {for (const engine of engines) {const brain = await managedBrain(engine);+ // Calibrate the fixed test embedder: an uncalibrated model never supersedes by cosine (supersession-threshold.ts).+ await brain.engine.setConfig('facts.supersession_thresholds', JSON.stringify({ 'openai:text-embedding-3-small@1536': 0.95 }));await run(brain.local, 'put_page', { slug: 'people/alice-example', content: page('Alice', 'Profile') });await run(brain.local, 'put_page', { slug: 'people/charlie-example', content: page('Charlie', 'Profile') });const byOauth = await submitRememberMutation(brain.oauth, { fact: 'Prefers written updates', provenance: 'test', entity: 'people/alice-example', request_id: randomUUID() }, 30_000);