Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): managed writeSingleFact keeps an absent entity's fallback slug, so dedup is per entity
garrytand57e87239d6a
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 6e91b02c4c..3ba3913a2e 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -17,8 +17,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`.-- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims.-- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.+- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims.+- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; `attributeFallback` sets the intent's `attribute_fallback`), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 161031a465..97284f4612 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -34,6 +34,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {// Fix wave 5 (#5731): the extractor-facts restore and its doctor check."src/core/repair/extractor-facts.ts": ["test/e2e/repair-extractor-facts-postgres.test.ts"],"src/commands/doctor/checks/extractor-facts.ts": ["test/e2e/repair-extractor-facts-postgres.test.ts"],+ // Fix wave 5: managed writeSingleFact keeps an absent entity's fallback slug (attribute_fallback).+ "src/core/facts/write-single.ts": ["test/e2e/managed-write-single-attribution-postgres.test.ts", "test/e2e/managed-facts-writers.test.ts"],+ "src/core/facts/managed-fact-write.ts": ["test/e2e/managed-write-single-attribution-postgres.test.ts", "test/e2e/managed-facts-writers.test.ts"],"src/core/persistence/deactivation.ts": ["test/e2e/persistence-deactivate-race.test.ts", "test/e2e/fix-wave-4-integration.test.ts"],// SkillOpt orchestrator, outcome/resume, models plan + strict mode, spend ledger."src/core/skillopt/**": [diff --git a/src/core/facts/managed-fact-write.ts b/src/core/facts/managed-fact-write.tsindex 18659d4c46..8f827aeae4 100644--- a/src/core/facts/managed-fact-write.ts+++ b/src/core/facts/managed-fact-write.ts@@ -24,13 +24,14 @@ export async function managedFactWritePreflight(engine: BrainEngine, sourceId: s* replays its receipt. Returned ids follow input order.*/export async function publishManagedEntityFacts(engine: BrainEngine, sourceId: string, entity: string | null,- facts: FenceInputFact[], options: { supersede?: boolean } = {}): Promise<{ inserted: number; duplicate: number; superseded: number; ids: number[] }> {+ facts: FenceInputFact[], options: { supersede?: boolean; attributeFallback?: boolean } = {}): Promise<{ inserted: number; duplicate: number; superseded: number; ids: number[] }> {const out = { inserted: 0, duplicate: 0, superseded: 0, ids: new Array<number>(facts.length) };for (const visibility of ['private', 'world'] as const) {const positions = facts.flatMap((fact, i) => fact.visibility === visibility ? [i] : []);if (!positions.length) continue;const group = positions.map(i => facts[i]);const ctx = factsContext(engine, sourceId, { writer: 'fence_write', entity, visibility, supersede: options.supersede === true,+ ...(options.attributeFallback ? { attribute_fallback: true } : {}),facts: group.map(f => [f.fact, f.kind, f.source, f.notability, f.confidence ?? 1, f.validFrom?.toISOString() ?? null,f.validUntil?.toISOString() ?? null, f.sessionId, f.context ?? null]) }, group[0].sessionId);const session = (await prepareManagedFactsSession(ctx, { turnText: '' }))!;@@ -42,7 +43,8 @@ export async function publishManagedEntityFacts(engine: BrainEngine, sourceId: snotability: f.notability, source: f.source, context: f.context ?? null, confidence: f.confidence ?? 1,valid_from: f.validFrom, valid_until: f.validUntil ?? null, source_session: f.sessionId,embedding: signature && f.embedding_model === signature.model && f.embedding?.length === signature.dimensions ? f.embedding : null }));- result = await publishManagedFacts(engine, session, ctx, extracted, visibility, undefined, { supersede: options.supersede, explicitContext: true });+ result = await publishManagedFacts(engine, session, ctx, extracted, visibility, undefined,+ { supersede: options.supersede, explicitContext: true, attributeFallback: options.attributeFallback });}out.inserted += result.inserted;out.duplicate += result.duplicate;diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.tsindex c76dba294b..e48e72cdd1 100644--- a/src/core/facts/write-single.ts+++ b/src/core/facts/write-single.ts@@ -127,11 +127,13 @@ export async function writeSingleFact(if (managed) {// The coordinator's fact intent owns dedup, supersession, the fence row and- // the file on a managed brain; the legacy direct writes stay unmanaged.+ // the file on a managed brain; the legacy direct writes stay unmanaged. An+ // entity with no page keeps its resolver slug database-only, as the+ // unmanaged path stores it, so dedup is per entity.const { publishManagedEntityFacts } = await import('./managed-fact-write.ts');const written = await publishManagedEntityFacts(engine, sourceId, resolvedSlug, [{ fact: factText, kind, notability: 'medium',source: input.provenance, visibility, confidence: input.confidence ?? 1.0, validFrom: new Date(), validUntil,- embedding, embedding_model: embeddingModel, sessionId: input.sessionId ?? null }], { supersede: true });+ embedding, embedding_model: embeddingModel, sessionId: input.sessionId ?? null }], { supersede: true, attributeFallback: true });const [stored] = await engine.executeRaw<{ entity_slug: string | null }>('SELECT entity_slug FROM facts WHERE id=$1', [written.ids[0]]);return { id: written.ids[0], status: written.superseded ? 'superseded' : written.inserted ? 'inserted' : 'duplicate', entity_slug: stored?.entity_slug ?? null,valid_until: validUntil, degraded_dedup: degradedDedup };diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex 08c5d0da3a..0ca5beb6b5 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -33,6 +33,11 @@ export interface ManagedFactIntent extends Record<string, unknown> {expected_revision?: string; facts?: FrozenExtractedFact[]; children?: string[];/** Direct single-fact writes keep writeSingleFact's supersession rule. */supersede?: true;+ /**+ * writeSingleFact only: a `memory/unattributed` row keeps the resolver's+ * fallback slug as its entity (no row number), so dedup stays per entity.+ */+ attribute_fallback?: true;embedding?: FactEmbeddingSignature | null;}export interface ManagedFactsSession {@@ -212,7 +217,7 @@ export async function resumeManagedFacts(engine: BrainEngine, session: ManagedFaexport async function publishManagedFacts(engine: BrainEngine, session: ManagedFactsSession, ctx: FactsBackstopCtx,facts: ExtractedFact[], visibility: 'private' | 'world', pageSlug?: string,- options: { supersede?: boolean; explicitContext?: boolean } = {}): Promise<ManagedFactsResult> {+ options: { supersede?: boolean; explicitContext?: boolean; attributeFallback?: boolean } = {}): Promise<ManagedFactsResult> {const embedded = facts.some(fact => fact.embedding !== null && fact.embedding !== undefined);if (embedded) await assertManagedFactsEmbedding(engine, session.config, session.embedding);const sourceId = session.authority.sourceId;@@ -223,10 +228,11 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFconst resolved = fact.entity_slug ? await resolveEntitySlugWithSource(engine, sourceId, fact.entity_slug) : null;const entitySlug = resolved && resolved.source !== 'fallback_slugify' ? resolved.slug : null;const slug = entitySlug ?? 'memory/unattributed';+ const attributed = entitySlug ?? (options.attributeFallback && resolved ? resolved.slug : null);await authorizeWrite(engine, session.authority, 'extract_facts', slug);await authorizePageVisibility(engine, session.authority, slug);const group = groups.get(slug) ?? [];- group.push({ ...fact, entity_slug: entitySlug, visibility, context: options.explicitContext ? fact.context ?? null : ctx.sourceSlug ?? pageSlug ?? null,+ group.push({ ...fact, entity_slug: attributed, visibility, context: options.explicitContext ? fact.context ?? null : ctx.sourceSlug ?? pageSlug ?? null,embedding: fact.embedding ? Array.from(fact.embedding) : null,valid_from: (fact.valid_from ?? ctx.validFrom ?? new Date()).toISOString(), valid_until: fact.valid_until?.toISOString() ?? null });groups.set(slug, group);@@ -234,10 +240,11 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFconst inputs: Array<{ slug: string; pageId: number | null; intent: ManagedFactIntent }> = [];for (const [slug, group] of groups) {const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });- if (snapshot?.page.deleted_at || group.some(fact => fact.entity_slug !== null) && !snapshot) throw new OperationError('page_identity_changed', 'The resolved fact entity was removed.');+ if (snapshot?.page.deleted_at || group.some(fact => fact.entity_slug === slug) && !snapshot) throw new OperationError('page_identity_changed', 'The resolved fact entity was removed.');inputs.push({ slug, pageId: snapshot?.page.id ?? null, intent: { kind: 'managed_facts_entity', batchKey: session.batchKey,inputDigest: session.inputDigest, origin: session.origin, originalRequestId: session.originalRequestId,embedding: session.embedding ?? null, ...(options.supersede ? { supersede: true as const } : {}),+ ...(options.attributeFallback ? { attribute_fallback: true as const } : {}),...(snapshot ? { expected_revision: snapshot.revision } : {}), facts: group } });}const rows = await engine.transaction(async tx => {diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex 3826221cfb..1757d40531 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -74,7 +74,10 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writthrow new OperationError('revision_conflict', 'The fact entity changed after extraction admission.');}const facts = (p.facts ?? []).map(fact => ({ ...thawFact(fact), embedding_model: fact.embedding ? p.embedding?.model ?? null : null }));- if (!facts.length || facts.some(fact => fact.entity_slug !== null && fact.entity_slug !== row.slug || fact.entity_slug !== null && !snapshot)) {+ // writeSingleFact's opt-in: an unattributed row keeps its fallback entity slug, database-only.+ const fallback = (fact: { entity_slug: string | null }) => p.attribute_fallback === true && row.slug === 'memory/unattributed'+ && fact.entity_slug !== null && fact.entity_slug !== row.slug;+ if (!facts.length || facts.some(fact => !fallback(fact) && (fact.entity_slug !== null && fact.entity_slug !== row.slug || fact.entity_slug !== null && !snapshot))) {throw new OperationError('invalid_params', 'The prepared facts do not match their entity.');}let body = snapshot?.page.compiled_truth ?? '';@@ -86,14 +89,14 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writconst seen = new Map<string, number>();for (const fact of facts) {await assertFactNotWithdrawn(engine, row.source_id, fact);- const key = JSON.stringify([fact.fact, fact.visibility]);+ const key = JSON.stringify([fact.fact, fact.visibility, fact.entity_slug]);const earlier = seen.get(key);if (earlier !== undefined) { entries.push({ fact, duplicateId: null, duplicateOf: earlier }); continue; }seen.set(key, entries.length);const decision = await decideSingleFact(engine, row.source_id, fact, fact.embedding ?? null, fact.embedding_model);const supersedes = p.supersede === true && decision.status === 'superseded' ? decision.candidate! : undefined;if (decision.candidate && !supersedes) { entries.push({ fact, duplicateId: decision.candidate.id }); continue; }- const rowNum = fact.entity_slug !== null ? nextRow++ : undefined;+ const rowNum = fact.entity_slug !== null && !fallback(fact) ? nextRow++ : undefined;if (rowNum !== undefined) body = upsertFactRow(body, { rowNum, claim: fact.fact, kind: fact.kind, visibility: fact.visibility,confidence: fact.confidence ?? 1, notability: fact.notability ?? 'medium', source: fact.source, context: fact.context ?? undefined,validFrom: formatFenceDate(fact.valid_from!), validUntil: fact.valid_until ? formatFenceDate(fact.valid_until) : undefined,diff --git a/test/e2e/managed-write-single-attribution-postgres.test.ts b/test/e2e/managed-write-single-attribution-postgres.test.tsnew file mode 100644index 0000000000..5c4115c99d--- /dev/null+++ b/test/e2e/managed-write-single-attribution-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../managed-write-single-attribution.test.ts'));diff --git a/test/managed-write-single-attribution.test.ts b/test/managed-write-single-attribution.test.tsnew file mode 100644index 0000000000..56aea8d261--- /dev/null+++ b/test/managed-write-single-attribution.test.ts@@ -0,0 +1,109 @@+/**+ * Managed `writeSingleFact` attribution (fix wave 5, TODOS "Managed+ * writeSingleFact keeps unresolved entity attribution"), on PGLite and, with a+ * safe DATABASE_URL, Postgres (test/e2e/managed-write-single-attribution-postgres.test.ts).+ *+ * Protects: on a managed brain, the same commitment remembered for two people+ * who have no pages lands as two facts, each keeping the resolver's fallback+ * slug database-only (no row number, no page, no file); the same claim for the+ * same absent person still deduplicates. The facts backstop (extract_facts)+ * never opts in: its absent-entity rows stay unattributed, deduplicate within+ * a batch, and replay without provider calls.+ * Fails when: the managed fact intent drops the fallback slug for+ * writeSingleFact (the second person's fact dedups against the first), or the+ * opt-in leaks into the backstop.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, readdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { operationsByName } from '../src/core/operations.ts';+import { writeSingleFact } from '../src/core/facts/write-single.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const CLAIM = 'Will send the signed contract by Friday.';++for (const backend of testBackends()) {+ describe(`managed writeSingleFact attribution (${backend})`, () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-write-single-attribution-'));+ beforeAll(async () => {+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }+ }, 120_000);+ afterEach(async () => {+ __setChatTransportForTests(null); __setEmbedTransportForTests(null); resetGateway();+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ });+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); rmSync(dir, { recursive: true, force: true }); });++ /** A fresh source with a claimed worktree, then managed mode on. */+ async function managedSource(run: (sourceId: string, root: string) => Promise<void>): Promise<void> {+ const sourceId = `attr-${randomUUID().slice(0, 8)}`;+ const root = mkdtempSync(join(dir, 'root-'));+ await withEnv({ GBRAIN_HOME: join(dir, `home-${sourceId}`) }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await run(sourceId, root);+ });+ }+ const rows = (sourceId: string) => engine.executeRaw<{ id: number; entity_slug: string | null; row_num: number | null; source_markdown_slug: string | null }>(+ 'SELECT id::int AS id, entity_slug, row_num, source_markdown_slug FROM facts WHERE source_id=$1 ORDER BY id', [sourceId]);++ test('the same commitment for two people with no pages lands as two facts, each keeping its fallback slug', async () => {+ await managedSource(async (sourceId, root) => {+ const remember = (entity: string) => writeSingleFact(engine, sourceId, { fact: CLAIM, provenance: 'fixture', entity, kind: 'commitment' });+ const alice = await remember('Alice Absent');+ const bob = await remember('Bob Absent');+ expect([alice.status, bob.status]).toEqual(['inserted', 'inserted']);+ expect(bob.id).not.toBe(alice.id);+ expect([alice.entity_slug, bob.entity_slug]).toEqual(['alice-absent', 'bob-absent']);+ const again = await remember('Alice Absent');+ expect(again).toMatchObject({ status: 'duplicate', id: alice.id, entity_slug: 'alice-absent' });+ expect(await rows(sourceId)).toEqual([+ { id: alice.id, entity_slug: 'alice-absent', row_num: null, source_markdown_slug: null },+ { id: bob.id, entity_slug: 'bob-absent', row_num: null, source_markdown_slug: null },+ ]);+ const requests = await engine.executeRaw<{ slug: string; flag: string | null }>(`SELECT slug, intent->>'attribute_fallback' AS flag FROM persistence_requests+ WHERE source_id=$1 AND operation='extract_facts' AND state='committed' AND intent->>'kind'='managed_facts_entity' ORDER BY sequence`, [sourceId]);+ expect(requests).toEqual([0, 1, 2].map(() => ({ slug: 'memory/unattributed', flag: 'true' })));+ expect(await engine.getPage('memory/unattributed', { sourceId })).toBeNull();+ expect(readdirSync(root).filter(name => !name.startsWith('.gbrain'))).toEqual([]);+ });+ }, 120_000);++ test('the facts backstop never opts in: absent entities stay unattributed, dedup within the batch, and replay without provider calls', async () => {+ await managedSource(async sourceId => {+ let calls = 0;+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'test' } });+ __setChatTransportForTests(async () => { calls++; return { text: JSON.stringify({ facts: [+ { fact: CLAIM, kind: 'commitment', entity: 'Alice Absent', confidence: 0.9, notability: 'high' },+ { fact: CLAIM, kind: 'commitment', entity: 'Bob Absent', confidence: 0.9, notability: 'high' },+ ] }), blocks: [], stopReason: 'end', usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test' }; });+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, remote: false, sourceId, dryRun: false, logger: console };+ const params = { turn_text: 'Alice Absent and Bob Absent both said they will send the signed contract by Friday.', request_id: randomUUID() };+ const first = await operationsByName.extract_facts.handler(ctx as never, params) as { inserted: number; duplicate: number; fact_ids: number[] };+ expect(first).toMatchObject({ inserted: 1, duplicate: 1 });+ expect(new Set(first.fact_ids).size).toBe(1);+ expect((await rows(sourceId)).map(row => row.entity_slug)).toEqual([null]);+ const flags = await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND intent ? 'attribute_fallback'", [sourceId]);+ expect(flags).toEqual([]);+ const replay = await operationsByName.extract_facts.handler(ctx as never, params);+ expect(replay).toEqual(first);+ expect(calls).toBe(1);+ });+ }, 120_000);+ });+}