Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): writeSingleFact dedups exact repeats and never mints a fallback entity; backstop dedups NULL-entity facts (#5152, #5504, #5275)
garrytanf0492de93a64
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 464ef8e42a..ca3f52118d 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -377,6 +377,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Wave 14 PR3 (GBRA-79); `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.157.0', text: 'The dream `consolidate` phase no longer merges two facts that differ in a negation, number, date or amount ("Invoice A due Monday" and "Invoice B due Tuesday" stay two facts), and facts without a typed metric now need a 0.95 embedding match (the explicit-duplicate bar) instead of the 0.85 `cycle.consolidate.cluster_threshold`, which keeps governing typed metric facts. Expect fewer takes from untyped event facts. `gbrain dream --phase consolidate --dry-run` lists the clusters it would write under `details.clusters`. Facts an earlier run wrongly merged keep the `valid_until` that run stamped: previous intervals were not retained, so there is no exact undo; `gbrain recall` still returns the facts, and `remember … replaces` records a correction.' },{ since: '0.60.157.0', text: 'A write tool call (`add_timeline_entry`, `put_page`, `remember`, every tool marked mutating) that names a parameter the tool does not declare is now refused `invalid_params` with nothing written, in every `mcp.strict_params` mode; the suggestion names the submitted key and the declared one (`content` → `detail` on `add_timeline_entry`). Before, the default warn mode committed the row with the misnamed field dropped. Reads keep the warn grace period.' },+ { since: '0.60.157.0', text: 'A `remember` (or any single-fact write) that repeats a fact already stored word for word for the same entity, or with no resolved entity at all, now returns the existing fact (`status: duplicate`) instead of inserting a second row, including on brains without an embedding key; a remote or unattributed caller never dedups against a fact that came from a private source. A write whose entity could not be resolved and fell back to slugifying the name now stores the fact with no entity instead of minting a placeholder entity slug, so the stub guard no longer refuses later writes about that name; search and `recall` still find the fact by its text.' },];/** 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 37f05b9b75..a6a31c06e5 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -779,7 +779,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).- const exact = resolvedSlug ? await decideSingleFact(ctx.engine, ctx.sourceId, { entity_slug: resolvedSlug, fact: f.fact, kind: f.kind ?? 'fact', visibility, attributed_to: f.attributed_to ?? null }, null) : null;+ const exact = await decideSingleFact(ctx.engine, ctx.sourceId, { entity_slug: resolvedSlug, fact: f.fact, kind: f.kind ?? 'fact', visibility, attributed_to: f.attributed_to ?? null }, null);let matchedExistingId: number | null = exact?.candidate?.id ?? null;if (matchedExistingId === null && resolvedSlug && f.embedding && !f.entity_inferred) {const candidates = await ctx.engine.findCandidateDuplicates(diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.tsindex c7969b1279..c471122288 100644--- a/src/core/facts/write-single.ts+++ b/src/core/facts/write-single.ts@@ -4,9 +4,12 @@** `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- * legacy DB-only fallbacks (thin-client, unparented, stub-guard).+ * post-extraction stages directly: resolve → dedup (`decideSingleFact`: exact+ * fingerprint, then embedding cosine at the 0.95 explicit bar) → fence-first+ * write (markdown durability) with the same legacy DB-only fallbacks+ * (thin-client, unparented, stub-guard). The `remember` verb itself routes+ * through the coordinated write (`submitRememberMutation`); the production+ * caller of this helper is loops extraction.** Supersession [X1, frozen as implementation-defined]: minimal deterministic* rule, zero LLM — when the top dedup candidate scores >= threshold with the@@ -15,8 +18,18 @@* → plain duplicate (existing id returned, nothing written).** Degradation (documented in the protocol doc): with no embedding provider,- * dedup/supersession are skipped on the fence path and near-duplicates may- * insert — `degraded_dedup: true` tells the caller.+ * the semantic half of dedup/supersession is skipped and near-duplicates may+ * insert — `degraded_dedup: true` tells the caller; the exact-fingerprint+ * check always runs (#5152). The check runs before, not inside, the insert+ * transaction, so dedup is sequential: two identical submissions racing each+ * other may both insert.+ *+ * Entity (#5504): an unmanaged write never mints an unprefixed slug. When the+ * resolver can only slugify the reference (`fallback_slugify`) the fact is+ * stored with `entity_slug = NULL`, the convention the facts backstop and+ * resolve-on-save follow, so the stub guard has nothing to refuse. The managed+ * path keeps the fallback slug database-only (`attribute_fallback`), where the+ * coordinated fact intent owns dedup per entity.** Provenance (c6): callers pass free-text provenance which lands on* `NewFact.source` verbatim — this seam deliberately does NOT take a@@ -29,9 +42,6 @@ import { recordTaintEdges } from '../trust/taint.ts';import type { TaintInput, WriteTrust } from '../trust/tier.ts';import { recordFlaggedRow, type GatedRowDecision } from '../write-gate-store.ts';-const DEDUP_THRESHOLD = 0.95;-const DEDUP_CANDIDATE_LIMIT = 5;-/*** #4755: null-like entity tokens LLM extractors emit for subjectless* statements. A caller passing the STRING "null" means what JSON `null`@@ -68,6 +78,13 @@ export interface SingleFactInput {derivation?: { trust: WriteTrust; inputs: readonly TaintInput[] };/** #5575 B3: the caller's write-gate decision (an `insert`); a flag records its receipt on the new row. */gate?: GatedRowDecision;+ /**+ * Caller trust for the dedup lookup. Fail-closed: only `false` (the local+ * CLI, a local maintenance job) may dedup against a fact whose provenance+ * page is private; anything else, including an unset value, treats such a+ * fact as unseen and inserts.+ */+ remote?: boolean;}export interface SingleFactResult {@@ -75,7 +92,7 @@ export interface SingleFactResult {status: FactInsertStatus;entity_slug: string | null;valid_until: Date | null;- /** True when no embedding provider — dedup/supersession skipped. */+ /** True when no embedding was available: semantic dedup/supersession skipped; the exact-fingerprint check still ran. */degraded_dedup: boolean;}@@ -88,7 +105,8 @@ export async function writeSingleFact(const managed = await managedPersistenceEnabled(engine);const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');- const { cosineSimilarity } = await import('./classify.ts');+ const { decideSingleFact } = await import('./single-prepare.ts');+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');const { writeFactsToFence, lookupSourceLocalPath } = await import('./fence-write.ts');const { isAvailable, embedOne, getEmbeddingModel } = await import('../ai/gateway.ts');@@ -105,7 +123,12 @@ export async function writeSingleFact(const resolved = entityRef? await resolveEntitySlugWithSource(engine, sourceId, entityRef): null;- const resolvedSlug = entityRef ? (resolved?.slug ?? entityRef) : null;+ // #5504: a slug the resolver invented is not an entity. Unmanaged writes+ // store NULL (nothing for the stub guard to refuse); the managed intent keeps+ // it database-only as attribution. Decided before the dedup lookup so the+ // exact check keys on the entity the row will carry.+ const fallbackResolution = resolved?.source === 'fallback_slugify';+ const resolvedSlug = !entityRef ? null : fallbackResolution && !managed ? null : (resolved?.slug ?? entityRef);// #4108: provenance for the fence writer's stub guard. Null when the// resolver returned nothing (fail-closed — no live page was verified).const resolutionSource = resolved?.source ?? null;@@ -148,39 +171,25 @@ export async function writeSingleFact(valid_until: validUntil, degraded_dedup: degradedDedup };}- // Dedup + supersession decision (same candidates + threshold as the pipeline).+ // Dedup + supersession decision (#5152): the same SQL-first decision the+ // managed path and the backstop use. Exact fingerprint first (NULL-entity+ // aware), then cosine when an embedding exists; a cosine match of the same+ // kind is an update (X1), a different kind a duplicate. A private-sourced+ // candidate is visible only to a trusted local caller.let supersedeId: number | null = null;- if (resolvedSlug && embedding) {- const candidates = await engine.findCandidateDuplicates(sourceId, resolvedSlug, factText, {- embedding,- embeddingModel,- k: DEDUP_CANDIDATE_LIMIT,- });- let top: (typeof candidates)[number] | null = null;- let topScore = -1;- for (const c of candidates) {- if (!c.embedding) continue;- const s = cosineSimilarity(embedding, c.embedding);- if (s > topScore) {- topScore = s;- top = c;- }- }- if (top && topScore >= DEDUP_THRESHOLD) {- const textDiffers = collapse(top.fact) !== collapse(factText);- if (top.kind === kind && textDiffers) {- supersedeId = top.id; // X1: near-duplicate with changed content = update- } else {- return {- id: top.id,- status: 'duplicate',- entity_slug: resolvedSlug,- valid_until: top.valid_until ?? null,- degraded_dedup: false,- };- }- }+ const excludePrivate = await resolveExcludePrivatePages(engine, input.remote);+ const decision = await decideSingleFact(engine, sourceId, { fact: factText, kind, visibility, entity_slug: resolvedSlug },+ embedding, embeddingModel, input.provenance, { excludePrivate });+ if (decision.status === 'duplicate') {+ return {+ id: decision.candidate!.id,+ status: 'duplicate',+ entity_slug: resolvedSlug,+ valid_until: decision.candidate!.valid_until ?? null,+ degraded_dedup: degradedDedup,+ };}+ if (decision.status === 'superseded') supersedeId = decision.candidate!.id;const newFact: NewFact = {fact: factText,@@ -306,7 +315,3 @@ async function expireSuperseded(engine: BrainEngine, oldId: number, newId: numbereport('superseded_by link', err);}}--function collapse(s: string): string {- return s.replace(/\s+/g, ' ').trim().toLowerCase();-}diff --git a/test/e2e/consolidate-divergence-postgres.test.ts b/test/e2e/consolidate-divergence-postgres.test.tsnew file mode 100644index 0000000000..9c2641419e--- /dev/null+++ b/test/e2e/consolidate-divergence-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../consolidate-divergence.test.ts'));diff --git a/test/e2e/write-single-dedup-postgres.test.ts b/test/e2e/write-single-dedup-postgres.test.tsnew file mode 100644index 0000000000..db2a57f832--- /dev/null+++ b/test/e2e/write-single-dedup-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../write-single-dedup.test.ts'));diff --git a/test/facts-backstop.test.ts b/test/facts-backstop.test.tsindex 59eac4dbe6..7a7288d87a 100644--- a/test/facts-backstop.test.ts+++ b/test/facts-backstop.test.ts@@ -295,6 +295,63 @@ describe('runFactsBackstop — dedup fast-path', () => {});});+describe('runFactsBackstop — exact duplicates without a resolved entity (#5275)', () => {+ // The legacy DB-only path used to skip the exact-fingerprint check when the+ // entity was null or fell back to slugification, so every re-extraction+ // inserted an identical active row outside the fence-key unique index.+ const census = async (text: string) => (await engine.executeRaw<{ entity_slug: string | null; n: number }>(+ `SELECT entity_slug, count(*)::int AS n FROM facts WHERE fact = $1 AND expired_at IS NULL GROUP BY entity_slug ORDER BY entity_slug`, [text]));++ test('a NULL-entity fact re-extracted twice lands once and the repeat reports duplicate with the same id', async () => {+ chatStub([{ fact: 'unparented-claim-A', kind: 'event', notability: 'high', entity: null }]);+ const r1 = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline', source: 'sync:import' }));+ expect(r1.mode).toBe('inline');+ if (r1.mode !== 'inline') return;+ expect(r1.inserted).toBe(1);++ chatStub([{ fact: 'unparented-claim-A', kind: 'event', notability: 'high', entity: null }]);+ const r2 = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline', source: 'sync:import' }));+ if (r2.mode !== 'inline') return;+ expect({ inserted: r2.inserted, duplicate: r2.duplicate, ids: r2.fact_ids }).toEqual({ inserted: 0, duplicate: 1, ids: r1.fact_ids });+ expect(await census('unparented-claim-A')).toEqual([{ entity_slug: null, n: 1 }]);+ });++ test('a bare-name entity that falls back to slugification dedups the same way; a fingerprint variant too', async () => {+ chatStub([{ fact: 'Said hello, twice', kind: 'event', notability: 'high', entity: 'nobodyresolvable' }]);+ const r1 = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline', source: 'sync:import' }));+ if (r1.mode !== 'inline') return;+ expect(r1.inserted).toBe(1);+ // Same fingerprint (whitespace and case differences collapse), different bytes.+ chatStub([{ fact: 'said hello, twice', kind: 'event', notability: 'high', entity: 'nobodyresolvable' }]);+ const r2 = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline', source: 'sync:import' }));+ if (r2.mode !== 'inline') return;+ expect({ inserted: r2.inserted, duplicate: r2.duplicate }).toEqual({ inserted: 0, duplicate: 1 });+ expect(await census('Said hello, twice')).toEqual([{ entity_slug: null, n: 1 }]);+ });++ test('visibility and attribution still separate rows; different text inserts', async () => {+ chatStub([{ fact: 'unparented-claim-B', kind: 'event', notability: 'high', entity: null }]);+ const a = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline', source: 'sync:import' }));+ if (a.mode !== 'inline') return;+ expect(a.inserted).toBe(1);+ chatStub([{ fact: 'unparented-claim-B', kind: 'event', notability: 'high', entity: null }]);+ const b = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline', source: 'sync:import', visibility: 'world' }));+ if (b.mode !== 'inline') return;+ expect(b.inserted).toBe(1);+ chatStub([{ fact: 'unparented-claim-C', kind: 'event', notability: 'high', entity: null }]);+ const c = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline', source: 'sync:import' }));+ if (c.mode !== 'inline') return;+ expect(c.inserted).toBe(1);+ const rows = await engine.executeRaw<{ fact: string; visibility: string }>(+ `SELECT fact, visibility FROM facts WHERE fact LIKE 'unparented-claim-%' AND fact <> 'unparented-claim-A' ORDER BY id`);+ expect(rows).toEqual([+ { fact: 'unparented-claim-B', visibility: 'private' },+ { fact: 'unparented-claim-B', visibility: 'world' },+ { fact: 'unparented-claim-C', visibility: 'private' },+ ]);+ });+});+describe('runFactsBackstop — stub guard routing (v0.34.5)', () => {test('bare-name entity routes to legacy DB-only path (no phantom page)', async () => {const { mkdtempSync, rmSync, existsSync } = await import('node:fs');diff --git a/test/facts-drain-scheduler.test.ts b/test/facts-drain-scheduler.test.tsindex 81d1f52c9d..115c8727d9 100644--- a/test/facts-drain-scheduler.test.ts+++ b/test/facts-drain-scheduler.test.ts@@ -166,7 +166,9 @@ describe('acceptance: a resident serve on a real PGLite brain', () => {await engine.setConfig('facts.extraction_model', 'anthropic:claude-sonnet-4-6');__resetFactsDrainNoticesForTests();configureGateway({ embedding_disabled: true, env: KEYS } as never);- __setChatTransportForTests(async () => ({ text: JSON.stringify({ facts: [{ fact: 'Acme Example shipped the beta in 2026', kind: 'fact', entity: 'companies/acme-example', confidence: 0.9, notability: 'high' }] }),+ // #5275: an exact repeat with no resolved entity is a duplicate, so each extraction yields a distinct claim.+ let extraction = 0;+ __setChatTransportForTests(async () => ({ text: JSON.stringify({ facts: [{ fact: `Acme Example shipped the beta in 2026 (extraction ${++extraction})`, kind: 'fact', entity: 'companies/acme-example', confidence: 0.9, notability: 'high' }] }),blocks: [], stopReason: 'end', model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',usage: { input_tokens: 900, output_tokens: 120, cache_read_tokens: 0, cache_creation_tokens: 0 } } as ChatResult));});diff --git a/test/facts-fallback-stub-guard.test.ts b/test/facts-fallback-stub-guard.test.tsindex 6b5853a7e9..0e4b0075a7 100644--- a/test/facts-fallback-stub-guard.test.ts+++ b/test/facts-fallback-stub-guard.test.ts@@ -99,7 +99,9 @@ describe('writeSingleFact × resolution provenance (#4108 matrix)', () => {});expect(r.status).toBe('inserted');- expect(r.entity_slug).toBe('companies/zeta-widgets-nonexistent');+ // #5504: a slug the resolver could only invent is not an entity; the row+ // carries NULL (the backstop convention) instead of the fallback slug.+ expect(r.entity_slug).toBeNull();// The pre-#4108 bug: this exact write minted// companies/zeta-widgets-nonexistent.md as a canonical stub page that a@@ -107,7 +109,7 @@ describe('writeSingleFact × resolution provenance (#4108 matrix)', () => {expect(existsSync(join(brainDir, 'companies/zeta-widgets-nonexistent.md'))).toBe(false);const row = await factRow(r.id);- expect(row.entity_slug).toBe('companies/zeta-widgets-nonexistent');+ expect(row.entity_slug).toBeNull();// DB-only insert — no fence file backs the row.expect(row.source_markdown_slug).toBeNull();});@@ -120,7 +122,8 @@ describe('writeSingleFact × resolution provenance (#4108 matrix)', () => {});expect(r.status).toBe('inserted');- expect(r.entity_slug).toBe('zetaperson');+ // #5504: no unprefixed holding slug; the stub guard has nothing to refuse.+ expect(r.entity_slug).toBeNull();expect(existsSync(join(brainDir, 'zetaperson.md'))).toBe(false);const row = await factRow(r.id);diff --git a/test/fence-write.test.ts b/test/fence-write.test.tsindex 2deefb146e..27c95261f9 100644--- a/test/fence-write.test.ts+++ b/test/fence-write.test.ts@@ -690,14 +690,16 @@ describe('writeFactsToFence — sync.write_through opt-out', () => {});expect(r.status).toBe('inserted');- expect(r.entity_slug).toBe('people/frank-example');+ // #5504: people/frank-example has no page, so the resolver fell back to+ // slugification and the row carries no entity (the backstop convention).+ expect(r.entity_slug).toBeNull();expect(existsSync(join(brainDir, 'people/frank-example.md'))).toBe(false);// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst rows = await (engine as any).db.query('SELECT entity_slug, source_markdown_slug FROM facts WHERE id = $1',[r.id],);- expect(rows.rows[0].entity_slug).toBe('people/frank-example');+ expect(rows.rows[0].entity_slug).toBeNull();// No .md backs the row — the fence-tracking column stays null.expect(rows.rows[0].source_markdown_slug).toBeNull();});diff --git a/test/legacy-fact-extraction-dedup.test.ts b/test/legacy-fact-extraction-dedup.test.tsindex ec6ee234ac..90a3ccaba2 100644--- a/test/legacy-fact-extraction-dedup.test.ts+++ b/test/legacy-fact-extraction-dedup.test.ts@@ -43,11 +43,14 @@ test('legacy extraction deduplicates exact old facts without inferring their vecexpect(visible).toMatchObject({ inserted: 1, duplicate: 0 });expect(visible.fact_ids).not.toContain(old.id);extractedEntity = null;- for (const sourceSlug of ['notes/first', 'notes/second']) {- const unparented = await runFactsPipeline('Synthetic unparented extraction input.', { engine, sourceId: 'default', sessionId: null,- source: 'mcp:extract_facts', sourceSlug, visibility: 'private' });- expect(unparented).toMatchObject({ inserted: 1, duplicate: 0 });- }- expect(await engine.executeRaw('SELECT context FROM facts WHERE entity_slug IS NULL ORDER BY id')).toEqual([{ context: 'notes/first' }, { context: 'notes/second' }]);+ // #5275: the exact check no longer skips facts with no resolved entity, so the same unparented claim extracted+ // from a second page is a duplicate of the first (the managed path already decided it that way).+ const firstUnparented = await runFactsPipeline('Synthetic unparented extraction input.', { engine, sourceId: 'default', sessionId: null,+ source: 'mcp:extract_facts', sourceSlug: 'notes/first', visibility: 'private' });+ expect(firstUnparented).toMatchObject({ inserted: 1, duplicate: 0 });+ const secondUnparented = await runFactsPipeline('Synthetic unparented extraction input.', { engine, sourceId: 'default', sessionId: null,+ source: 'mcp:extract_facts', sourceSlug: 'notes/second', visibility: 'private' });+ expect(secondUnparented).toMatchObject({ inserted: 0, duplicate: 1, fact_ids: firstUnparented.fact_ids });+ expect(await engine.executeRaw('SELECT context FROM facts WHERE entity_slug IS NULL ORDER BY id')).toEqual([{ context: 'notes/first' }]);}}), 120_000);diff --git a/test/memory-verbs-conformance.test.ts b/test/memory-verbs-conformance.test.tsindex b2f9fbdf50..f69cdb2578 100644--- a/test/memory-verbs-conformance.test.ts+++ b/test/memory-verbs-conformance.test.ts@@ -690,6 +690,9 @@ describe('writeSingleFact — supersession rule [X1] + degraded dedup', () => {it('near-duplicate with changed text and same kind SUPERSEDES; identical text is a duplicate', async () => {installDeterministicEmbedder();+ // #5504: an entity the resolver can only slugify is stored with entity_slug NULL, and a NULL-entity fact dedups+ // by exact fingerprint only (candidate lookup is entity-keyed), so the supersession rule needs a live entity page.+ await seedEntityPage('people/supersede-test', 'Supersede Test');const a = await writeSingleFact(engine, 'default', {fact: 'SUPERSEDE-PAIR alice works at acme-example',provenance: 'test', entity: 'people/supersede-test', kind: 'fact',diff --git a/test/write-attribution-facts-takes.test.ts b/test/write-attribution-facts-takes.test.tsindex 10a33ebeb3..738f921c68 100644--- a/test/write-attribution-facts-takes.test.ts+++ b/test/write-attribution-facts-takes.test.ts@@ -85,6 +85,9 @@ describe('legacy facts helpers on an unmanaged brain', () => {test('writeSingleFact DB-only supersession: the new fact is maintenance-created and the old fact keeps its creator', () => withFixedEmbeddings(async () => {for (const engine of engines) {const brain = await unmanagedBrain(engine);+ // #5504: an entity the resolver can only slugify stores entity_slug NULL, so the page must exist for the+ // supersession candidate (keyed on the entity) to be found; the write itself stays DB-only (no local root).+ await importFromContent(engine, 'people/alice-example', '---\ntype: person\ntitle: Alice\n---\nA person.\n', { sourceId: brain.sourceId, sourcePath: 'people/alice-example.md', noEmbed: true });const old = await creatorFact(brain, 'Prefers morning meetings', { entity: 'people/alice-example' });const written = await writeSingleFact(engine, brain.sourceId, { fact: 'Prefers afternoon meetings', provenance: 'test', entity: 'people/alice-example' });diff --git a/test/write-single-dedup.test.ts b/test/write-single-dedup.test.tsnew file mode 100644index 0000000000..1c8cf48e8c--- /dev/null+++ b/test/write-single-dedup.test.ts@@ -0,0 +1,121 @@+/**+ * #5152 / #5504(a) — `writeSingleFact` (the helper behind loops extraction)+ * deduplicates exact repeats the way the managed path and the backstop do, and+ * never mints an unprefixed entity slug.+ *+ * Protects: an exact repeat with no entity, or with an entity but no+ * embedding, returns `duplicate` with the first row's id (one row); a+ * different visibility is a different fact; a counterparty the resolver can+ * only slugify (`fallback_slugify`) is stored with `entity_slug = NULL` and+ * still deduplicates; a caller whose trust is unknown or remote never learns+ * that a private-sourced fact exists (its exact repeat inserts), while the+ * local CLI dedups against it; the public `remember` verb on a classic brain+ * already dedups an entity-less repeat.+ * Fails when: the helper runs cosine-only dedup gated on entity + embedding+ * (two rows), or writes the slugified fallback as the entity.+ * Seams: none. PGLite always, Postgres when DATABASE_URL is set.+ * Dedup is sequential: the exact check runs before, not inside, the insert+ * transaction, so two identical submissions racing each other may both insert.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import { resetGateway } from '../src/core/ai/gateway.ts';+import { writeSingleFact } from '../src/core/facts/write-single.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const CLAIM = 'Will send the signed contract by Friday.';++for (const backend of testBackends()) {+ describe(`${backend}: writeSingleFact exact dedup (#5152) and NULL fallback entity (#5504)`, () => {+ let engine: BrainEngine;++ beforeAll(async () => {+ if (backend === 'postgres') {+ const pg = new PostgresEngine();+ await pg.connect({ database_url: requirePostgresTestDatabase() });+ engine = pg;+ } else {+ const lite = new PGLiteEngine();+ await lite.connect({});+ engine = lite;+ }+ await engine.initSchema();+ }, 180_000);++ afterAll(async () => {+ resetGateway();+ await engine.disconnect();+ });++ beforeEach(async () => {+ await engine.executeRaw(`DELETE FROM facts`);+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'people/%'`);+ await engine.executeRaw(`DELETE FROM config WHERE key = 'sync.write_through'`);+ });++ const rows = () => engine.executeRaw<{ id: number; entity_slug: string | null; visibility: string }>(+ 'SELECT id::int AS id, entity_slug, visibility FROM facts ORDER BY id');++ test('an exact repeat with no entity is a duplicate of the first row', async () => {+ const first = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', remote: false });+ const second = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', remote: false });+ expect(first).toMatchObject({ status: 'inserted', entity_slug: null });+ expect(second).toMatchObject({ status: 'duplicate', id: first.id, entity_slug: null });+ expect((await rows()).map(r => r.id)).toEqual([first.id]);+ });++ test('an exact repeat with an entity and no embedding is a duplicate; degraded_dedup only means semantic dedup was skipped', async () => {+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice.' }, { sourceId: 'default' });+ const first = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: 'people/alice-example', remote: false });+ const second = await writeSingleFact(engine, 'default', { fact: ` ${CLAIM} `, provenance: 'fixture', entity: 'people/alice-example', remote: false });+ expect(first).toMatchObject({ status: 'inserted', entity_slug: 'people/alice-example', degraded_dedup: true });+ expect(second).toMatchObject({ status: 'duplicate', id: first.id, degraded_dedup: true });+ expect(await rows()).toHaveLength(1);+ });++ test('a different visibility is a different fact', async () => {+ const a = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', visibility: 'private', remote: false });+ const b = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', visibility: 'world', remote: false });+ expect([a.status, b.status]).toEqual(['inserted', 'inserted']);+ expect((await rows()).map(r => r.visibility)).toEqual(['private', 'world']);+ });++ test('a counterparty the resolver can only slugify is stored with no entity and still dedups (#5504)', async () => {+ const first = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: 'Nobody Known', kind: 'commitment', remote: false });+ expect(first).toMatchObject({ status: 'inserted', entity_slug: null });+ expect(await rows()).toEqual([{ id: first.id, entity_slug: null, visibility: 'private' }]);+ const again = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: 'Nobody Known', kind: 'commitment', remote: false });+ expect(again).toMatchObject({ status: 'duplicate', id: first.id, entity_slug: null });+ expect(await rows()).toHaveLength(1);+ });++ test('a remote or unknown caller never dedups against a private-sourced fact; the local CLI does', async () => {+ await engine.putPage('people/secret-example', { type: 'person', title: 'Secret Example', compiled_truth: 'Private.', frontmatter: { visibility: 'private' } }, { sourceId: 'default' });+ const [seed] = await engine.executeRaw<{ id: number }>(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, visibility, source_markdown_slug, row_num)+ VALUES ('default', 'people/secret-example', $1, 'fact', 'fixture', 'private', 'people/secret-example', 1) RETURNING id::int AS id`, [CLAIM]);+ for (const remote of [true, undefined]) {+ const untrusted = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: 'people/secret-example', remote });+ expect(untrusted.status).toBe('inserted');+ expect(untrusted.id).not.toBe(seed.id);+ // The copy an untrusted caller wrote has no private provenance page; remove it so the next caller faces only the seed.+ await engine.executeRaw('DELETE FROM facts WHERE id = $1', [untrusted.id]);+ }+ const local = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: 'people/secret-example', remote: false });+ expect(local).toMatchObject({ status: 'duplicate', id: seed.id });+ });++ test('the public remember verb on a classic brain already dedups an entity-less repeat', async () => {+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default' };+ const first = JSON.parse((await dispatchToolCall(engine, 'remember', { fact: CLAIM, provenance: 'fixture' }, opts)).content[0].text);+ const second = JSON.parse((await dispatchToolCall(engine, 'remember', { fact: CLAIM, provenance: 'fixture' }, opts)).content[0].text);+ expect(first.status).toBe('inserted');+ expect(second.status).toBe('duplicate');+ expect(second.id).toBe(first.id);+ expect(await rows()).toHaveLength(1);+ });+ });+}