Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
P2.4 (#6333, shadow only): count would_dedup_same_page, never drop
garrytan432e8e8a1feb
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 35406acad0..ddde1acd0e 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -88,7 +88,7 @@ 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/drain.ts` + `drain-scheduler.ts` + `src/core/cycle/facts-drain.ts` + `src/commands/doctor/checks/facts-drain.ts` — the automatic facts drain on PGLite (no job worker there). `runFactsDrain(engine, { owner, signal, wallClockMs })` runs queued `facts-absorb` jobs one at a time through the real handler (`withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)`), with `authorizeJobExecution`/`withSubmissionAuthority`, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one `BudgetTracker` (`facts:drain`) capped at min(`facts.drain_budget_usd` 1.00, the rest of `facts.drain_daily_budget_usd` 5.00 over a rolling 24 h); `capSource` is `user` once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the `gbrain pricing set` fix under a user cap. Before each claim the job's worst case (8,000-char turn + `facts.extraction_max_tokens`) must fit; `facts.drain_max_jobs` (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (`queue.deferJob`): `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config `facts.drain_state`; `readFactsDrainStatus` feeds doctor `facts_drain` and the readiness capability `facts_drain`. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a `facts_drain_first_run` notice; deferrals raise one `facts_drain_deferred` notice per reason per process (`takeFactsDrainNotice`, taken by stdio `dispatch.ts`). Never writes stdout. `startFactsDrainScheduler` owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (`canRun`), the timer callback returns the tick's promise (a test awaits it), and `stop()` aborts and waits up to 5 s. Owners: stdio `serve` (`installFactsDrain`, stdin-data activity, delegated-sync veto, stopped first in the shutdown chain), `serve --http` (every tick; stopped before engine disconnect) and the cycle phase `facts_drain` (PGLite only; Postgres skips `not_applicable`). Opt-out: `facts.extraction_enabled false`. Tests: `test/facts-drain.test.ts`, `test/facts-drain-scheduler.test.ts`, `test/facts-absorb-keyless-deferral.test.ts`, the `facts_drain` row of `test/managed-phase-matrix.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/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. `wouldDedupSamePage(ctx, existing, score, claim)` (#6333, shadow only, wave 15 [UC2]) is the explicit-lane same-page rewording rule the backstop measures but never acts on: the nearest candidate shares the lane, `source_session` and visibility, sits at or above `SAME_PAGE_REWORDING_THRESHOLD` (0.85) and does not `claimsDiverge`; the backstop counts it as `would_dedup_same_page` on its result, logs the matched id, cosine and session on stderr, and inserts the fact as before. Its measured false positives (Lisbon→Porto, approved→rejected, email→phone are all counted) are pinned in `test/backstop-same-page-shadow-6333.test.ts` and are why no drop path ships. `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/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/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 83f3674f7a..46ff6c0eea 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -441,6 +441,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.176.0', text: '`gbrain extract-conversation-facts` now walks a source\'s pages by slug (a keyset) instead of OFFSET over `updated_at`, so a page is listed, extracted and frozen once per run even while other writers touch pages that share one timestamp; a page the run sees twice is counted as `pages_skipped_duplicate_listing` with no second model call. A batch request the writer refused as malformed (`invalid_params`, the shape a page listed twice produced) is no longer a permanent block: its stored entries are resubmitted on the next run with zero model calls, up to 3 failed requests per page version, and one failed request counts once however many times it listed the page. `list_pages` sorted by `updated_desc` (the default) now breaks timestamp ties by slug, source and id, so ties page deterministically; offset paging is still unstable under writes that change `updated_at`.' },{ since: '0.60.176.0', text: '`gbrain projections drain` (and the migration drain) no longer loops on one queue row whose revision does not match its page: the row is re-keyed to the page\'s current revision and rebuilt in the same pass, or deleted when the page is already projected or belongs to a dead source incarnation, always as a compare-and-set on the exact row listed so a newer queued row survives. A page whose content changes while it is being rebuilt appears once under `failed` with a `revision_conflict:` reason and stays queued for the next run; `--json` may now list such rows where the command used to hang.' },{ since: '0.60.176.0', text: '`gbrain extract-conversation-facts` now sends every eligible turn of a conversation page to the extractor in bounded windows: a window closes at 30 messages or when its rendered text, header included, would exceed 6,500 characters, and the next turn opens a new window instead of being cut off; a turn too long for one window is split at sentence boundaries with its speaker and timestamp repeated; the 31st reply of a 31-turn group is extracted as its own window instead of being dropped. A dense page therefore takes more extractor calls than before, under the same cost cap. Pages already stamped complete from clipped input are not re-extracted automatically; to recompute them run `gbrain extract-conversation-facts --source <id> --force` (narrowed to one page with its slug option, or the whole source after a `--dry-run` preview of the window count), which spends model calls.' },+ { since: '0.60.176.0', text: 'Fact extraction on explicit lanes (sync import, put_page) now measures same-page rewordings: when a page is re-extracted and a new claim sits within cosine 0.85 of a fact the same page produced earlier without changing a number, date, amount or negation, the run counts it as `would_dedup_same_page` and prints one stderr line naming the matched fact id. Nothing is dropped or expired; the counter exists so the rule\'s false-positive rate can be measured before any automatic dedup ships.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 2537772290..faa6de8170 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -49,7 +49,7 @@ import type { GBrainConfig } from '../config.ts';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 { cosineVerdict, dedupCapturedFacts, withCaptureDrops, wouldDedupSamePage } from './capture-dedup.ts';import { readSupersessionThreshold } from './supersession-threshold.ts';import { assertAmbientCaptureAdmissible, type FactsBackstopSource } from './capture-sources.ts';import { appendContextNote, type InferredVia } from './subject-infer.ts';@@ -171,6 +171,8 @@ export type FactsBackstopResult =write_gate?: GateTally;/** Entity groups held because the page's facts fence does not parse cleanly (nothing written). */fence_refused?: number;+ /** #6333 shadow (never a drop): facts the same-page rewording rule would have treated as duplicates. */+ would_dedup_same_page?: number;};/** One pipeline run's input: the turn text plus its page provenance and observation date. */@@ -222,6 +224,11 @@ function warnOnce(key: string, msg: string): void {// eslint-disable-next-line no-consoleconsole.warn(msg);}+/** #6333 [UC2] shadow only: name the pair the same-page rewording rule would have deduplicated; the fact is inserted as today. */+function warnSamePageShadow(sessionId: string | null, matchedId: number, score: number): void {+ // eslint-disable-next-line no-console+ console.warn(`[facts-backstop] #6333 shadow: new fact in session ${sessionId} rewords fact ${matchedId} (cosine ${score.toFixed(3)}); both kept`);+}/** Test-only: reset the once-per-process warning memo. */export function __resetBackstopWarningsForTests(): void {_warnedKeys.clear();@@ -534,6 +541,8 @@ export async function runFactsPipeline(write_gate?: GateTally;/** Entity groups held because the page's facts fence does not parse cleanly (nothing written). */fence_refused?: number;+ /** #6333 shadow (never a drop): facts the same-page rewording rule would have treated as duplicates. */+ would_dedup_same_page?: number;}> {return runPipelineWithBody({turnText,@@ -555,7 +564,7 @@ async function runPipeline(parsedPage: ParsedPageInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number }> {+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number }> {return runPipelineWithBody({turnText: parsedPage.compiled_truth,@@ -602,7 +611,7 @@ async function runPipelineWithBody(input: PipelineInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number }> {+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number }> {// #4210: outside a withBudgetTracker scope (extract_facts op, sweep,// put_page backstop, checkpoint harvest, file/code import) the gateway's// chat/embed calls were budget no-ops — real spend, zero audit rows.@@ -665,7 +674,7 @@ async function runPipelineBodyInner(input: PipelineInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number }> {+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number }> {const { extractFactsFromTurnWithOutcome, FactsExtractionError } = await import('./extract.ts');const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');const { cosineSimilarity } = await import('./classify.ts');@@ -750,6 +759,7 @@ async function runPipelineBodyInner(if (managed) return withCaptureDrops(dropped, facts.length || !dropped.length ? await publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug) : null);const counts = { inserted: 0, duplicate: dropped.length, superseded: 0, fact_ids: [...dropped] };+ let wouldDedupSamePageCount = 0;const writer = await derivedFactWriter(ctx, input, derivation, counts);const { insertDerivedFact, write_gate } = writer;// Cathedral 5: slugs whose fence-write actually inserted a fact this run.@@ -794,14 +804,16 @@ async function runPipelineBodyInner(f.fact,{ embedding: f.embedding, embeddingModel: f.embedding_model, k: DEDUP_CANDIDATE_LIMIT, attributedTo: f.attributed_to ?? null },);- let top: { id: number; score: number; fact: string } | null = null;+ let top: { row: typeof candidates[number]; score: number } | null = null;for (const c of candidates) {if (!c.embedding) continue;const s = cosineSimilarity(f.embedding, c.embedding);- if (!top || s > top.score) top = { id: c.id, score: s, fact: c.fact };+ if (!top || s > top.score) top = { row: c, score: s };}- 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;+ if (top && cosineVerdict(ctx.source, top.score, f.fact, top.row.fact, (await readSupersessionThreshold(ctx.engine, f.embedding_model, f.embedding.length)).threshold) === 'duplicate') {+ matchedExistingId = top.row.id;+ } else if (top && wouldDedupSamePage({ source: ctx.source, sessionId: ctx.sessionId, visibility }, top.row, top.score, f.fact)) {+ wouldDedupSamePageCount++; warnSamePageShadow(ctx.sessionId, top.row.id, top.score);}}@@ -814,8 +826,9 @@ async function runPipelineBodyInner(survived.push({ f, resolvedSlug, resolutionSource });}+ const shadow = wouldDedupSamePageCount ? { would_dedup_same_page: wouldDedupSamePageCount } : {};if (survived.length === 0) {- return { ...counts, entity_slugs: [], write_gate };+ return { ...counts, entity_slugs: [], write_gate, ...shadow };}// Phase 2: group survived facts by resolved entity_slug. Facts with@@ -890,7 +903,7 @@ async function runPipelineBodyInner(if (localPath === null) {// All went through legacy bucket; nothing left to fence — DB-only// inserts have no fence-written page, so entity_slugs stays empty.- return { ...counts, entity_slugs: [], write_gate };+ return { ...counts, entity_slugs: [], write_gate, ...shadow };}// Phase 5: fence-write per entity. writeFactsToFence handles the@@ -1012,5 +1025,5 @@ async function runPipelineBodyInner(if (result.inserted > 0) fencedSlugs.add(slug);}- return { ...counts, entity_slugs: [...fencedSlugs], write_gate, ...(fenceRefused ? { fence_refused: fenceRefused } : {}) };+ return { ...counts, entity_slugs: [...fencedSlugs], write_gate, ...(fenceRefused ? { fence_refused: fenceRefused } : {}), ...shadow };}diff --git a/src/core/facts/capture-dedup.ts b/src/core/facts/capture-dedup.tsindex b69e161799..36e7200592 100644--- a/src/core/facts/capture-dedup.ts+++ b/src/core/facts/capture-dedup.ts@@ -25,7 +25,7 @@* collapse to the newest row, which carries every entity slug of its group.*/-import type { BrainEngine, FactAttribution, FactRow } from '../engine.ts';+import type { BrainEngine, FactAttribution, FactRow, FactVisibility } from '../engine.ts';import { corpusFileSessionId } from '../context/corpus-segments.ts';import { writeHeartbeat } from '../context/hook-heartbeat.ts';import { normalizeAlias } from '../search/alias-normalize.ts';@@ -85,6 +85,29 @@ export function cosineVerdict(source: string | null | undefined, score: number,return score >= NEAR_DUPLICATE_THRESHOLD && !claimsDiverge(claim, existing) ? 'near_duplicate' : 'distinct';}+/** #6333 shadow floor: same-page rewordings sit at cosine 0.86–0.93 (lane C), under every calibrated dedup threshold. */+export const SAME_PAGE_REWORDING_THRESHOLD = 0.85;++/**+ * #6333 [UC2] shadow predicate, never a drop: would the deterministic rule+ * "same source-qualified provenance (lane + session + visibility), cosine at+ * or above SAME_PAGE_REWORDING_THRESHOLD, no diverging guard token" have+ * treated `claim` as a duplicate of `existing`? The backstop counts it as+ * `would_dedup_same_page` on explicit lanes only. Measured false positives+ * (Lisbon→Porto, approved→rejected, email→phone, all invisible to+ * claimsDiverge) are why the rule measures and does not act.+ */+export function wouldDedupSamePage(+ ctx: { source: string | null | undefined; sessionId: string | null | undefined; visibility: FactVisibility },+ existing: { source: string; source_session: string | null; visibility: FactVisibility; fact: string },+ score: number,+ claim: string,+): boolean {+ if (!ctx.source || !ctx.sessionId || isCaptureLane(ctx.source)) return false;+ if (existing.source !== ctx.source || existing.source_session !== ctx.sessionId || existing.visibility !== ctx.visibility) return false;+ return score >= SAME_PAGE_REWORDING_THRESHOLD && !claimsDiverge(claim, existing.fact);+}+function nameKey(text: string): string {return ` ${normalizeAlias(text).replace(/[^\p{L}\p{N}]+/gu, ' ').trim()} `;}diff --git a/test/backstop-same-page-shadow-6333.test.ts b/test/backstop-same-page-shadow-6333.test.tsnew file mode 100644index 0000000000..7490e958ec--- /dev/null+++ b/test/backstop-same-page-shadow-6333.test.ts@@ -0,0 +1,156 @@+/**+ * Wave 15 P2.4 (#6333, [UC2] SHADOW ONLY): re-extracting an edited page+ * inserts reworded copies of one claim (pairwise cosine 0.86–0.93, under the+ * calibrated dedup threshold, and on an uncalibrated embedding model no+ * cosine dedup fires at all). The deterministic "same page, cosine ≥ 0.85,+ * no diverging guard token" rule is NOT allowed to drop anything this wave:+ * the backstop only counts `would_dedup_same_page` so the predicate's+ * false-drop rate is measured on fixtures before any behaviour ships.+ *+ * Positive fixture: four rewordings of one claim → counted 3, four rows kept.+ * Negative fixtures (Lisbon→Porto, approved→rejected, email→phone): the+ * second claim is a correction, both rows are kept, and the counter pins the+ * measured false positive (the guard tokens cannot tell them apart), which+ * is exactly why the drop path does not ship.+ *+ * Zero model calls: the chat and embedding transports are stubs.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runFactsBackstop, type FactsBackstopCtx } from '../src/core/facts/backstop.ts';+import { __setChatTransportForTests, __setEmbedTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';+import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';++let engine: PGLiteEngine;+const DIMS = 1536;+const ENTITY = 'people/alice-example';+const LONG_BODY = 'this is a real meeting note longer than 80 chars '.repeat(3);++/**+ * Unit vectors: sqrt(0.9) on a dim private to the page plus sqrt(0.1) on a+ * dim private to the fact, so two facts of one page sit at cosine exactly+ * 0.9 and facts of different pages are orthogonal (the candidate query is+ * entity-wide and the rule inspects the nearest row, as in production where+ * a page's own rewording is the closest fact about the entity).+ */+let nextDim = 0;+const pageDim = new Map<string, number>();+function vectorFor(slug: string): number[] {+ if (!pageDim.has(slug)) pageDim.set(slug, nextDim++);+ const v = new Array<number>(DIMS).fill(0);+ v[pageDim.get(slug)!] = Math.sqrt(0.9);+ v[nextDim++] = Math.sqrt(0.1);+ return v;+}++function stubExtraction(fact: string, vector: number[]): void {+ __setChatTransportForTests(async (): Promise<ChatResult> => ({+ text: JSON.stringify({ facts: [{ fact, kind: 'fact', entity: ENTITY, confidence: 1.0, notability: 'high' }] }),+ blocks: [],+ stopReason: 'end',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'test:stub',+ providerId: 'test',+ }));+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => vector) })) as never);+}++async function extractOnce(slug: string, fact: string, vector: number[] = vectorFor(slug)) {+ stubExtraction(fact, vector);+ const ctx: FactsBackstopCtx = { engine, sourceId: 'default', sessionId: `sync:${slug}`, source: 'sync:import', mode: 'inline' };+ const r = await runFactsBackstop({ slug, type: 'meeting', compiled_truth: LONG_BODY, frontmatter: {} }, ctx);+ expect(r.mode).toBe('inline');+ if (r.mode !== 'inline') throw new Error('unreachable');+ return r;+}++async function activeRows(slug: string): Promise<Array<{ id: number; fact: string }>> {+ return engine.executeRaw<{ id: number; fact: string }>(+ `SELECT id, fact FROM facts WHERE source_id = 'default' AND source_session = $1 AND expired_at IS NULL ORDER BY id`, [`sync:${slug}`],+ );+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.putPage(ENTITY, { type: 'person', title: 'Alice Example', compiled_truth: 'Alice Example is a person.', timeline: '', frontmatter: {} });+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+});++afterAll(async () => { await engine.disconnect(); });++afterEach(() => {+ __setChatTransportForTests(null);+ __setEmbedTransportForTests(null);+ __resetFactsQueueForTests();+});++describe('#6333 shadow: same-page rewording counter, never a drop', () => {+ test('four rewordings of one claim on one page: counted 3 times, four rows kept, nothing expired', async () => {+ const slug = 'meetings/reworded-example';+ const rewordings = [+ 'Alice Example leads the platform team at the example company',+ 'Alice Example is the lead of the example company platform team',+ 'At the example company, Alice Example heads the platform team',+ 'The example company platform team is led by Alice Example',+ ];+ let counted = 0;+ for (const [i, fact] of rewordings.entries()) {+ const r = await extractOnce(slug, fact);+ expect(r.inserted).toBe(1);+ expect(r.duplicate).toBe(0);+ counted += r.would_dedup_same_page ?? 0;+ expect(r.would_dedup_same_page ?? 0).toBe(i === 0 ? 0 : 1);+ }+ expect(counted).toBe(3);+ const rows = await activeRows(slug);+ expect(rows.map((r) => r.fact)).toEqual(rewordings);+ const expired = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source_session = $1 AND expired_at IS NOT NULL`, [`sync:${slug}`]);+ expect(Number(expired[0].n)).toBe(0);+ });++ test('a rewording from a different page is never counted (provenance must match exactly)', async () => {+ const a = 'meetings/provenance-a-example';+ const b = 'meetings/provenance-b-example';+ await extractOnce(a, 'Alice Example moved the weekly sync to Tuesday mornings');+ const r = await extractOnce(b, 'Alice Example shifted the weekly sync to Tuesday mornings');+ expect(r.inserted).toBe(1);+ expect(r.would_dedup_same_page ?? 0).toBe(0);+ });++ test('a pair under the 0.85 floor is never counted', async () => {+ const slug = 'meetings/far-apart-example';+ await extractOnce(slug, 'Alice Example prefers written updates over meetings');+ // sqrt(0.5) on the page dim → cosine 0.67 against the page's first fact.+ const far = new Array<number>(DIMS).fill(0);+ far[pageDim.get(slug)!] = Math.sqrt(0.5); far[nextDim++] = Math.sqrt(0.5);+ const r = await extractOnce(slug, 'Alice Example likes async written updates more than meetings', far);+ expect(r.inserted).toBe(1);+ expect(r.would_dedup_same_page ?? 0).toBe(0);+ });++ // Measured false positives: `claimsDiverge` guards negation, numbers,+ // dates and amounts only, so each correction below is counted as a+ // would-be duplicate. The rows are still inserted (no drop path); the+ // pinned counts are the published false-drop rate (3/3) that keeps the+ // automatic drop out of this wave.+ const negatives: Array<[string, string, string]> = [+ ['lisbon-porto', 'Alice Example lives in Lisbon', 'Alice Example lives in Porto'],+ ['approved-rejected', 'Alice Example approved the example vendor contract', 'Alice Example rejected the example vendor contract'],+ ['email-phone', 'Alice Example prefers to be reached by email', 'Alice Example prefers to be reached by phone'],+ ];+ for (const [name, before, after] of negatives) {+ test(`negative ${name}: the correction is inserted, never dropped; the counter pins the measured false positive`, async () => {+ const slug = `meetings/negative-${name}-example`;+ await extractOnce(slug, before);+ const r = await extractOnce(slug, after);+ expect(r.inserted).toBe(1);+ expect(r.duplicate).toBe(0);+ expect(r.fact_ids).toHaveLength(1);+ const rows = await activeRows(slug);+ expect(rows.map((x) => x.fact)).toEqual([before, after]);+ expect(r.would_dedup_same_page ?? 0).toBe(1);+ });+ }+});