Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(facts): write-time subject inference in the facts backstop (#5836)
garrytan15566876eaf1
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex d7bf48fe47..514a39d40f 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -47,6 +47,8 @@ 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 { appendContextNote, type InferredVia } from './subject-infer.ts';+import { inferenceNote, inferMissingSubjects } from './subject-infer-write.ts';/*** Notability-filter vocabulary shared by the durable facts-absorb payload@@ -71,10 +73,12 @@ export function coerceNotabilityFilter(v: unknown): FactNotabilityFilter {function annotateUnverifiedResolution(context: string | null,resolutionSource: ResolutionSource | null,+ inferred?: InferredVia,): string | null {+ // #5836: a write-time inferred subject says so, in the DB row and the fence cell alike.+ if (inferred) return appendContextNote(context, inferenceNote(inferred));if (resolutionSource !== 'prefix_expansion') return context;- const note = 'entity matched by bare name only (prefix expansion) — unverified, please confirm';- return context ? `${context} — ${note}` : note;+ return appendContextNote(context, 'entity matched by bare name only (prefix expansion) — unverified, please confirm');}export interface FactsBackstopCtx {@@ -649,12 +653,11 @@ async function runPipelineBodyInner(return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [], skipped_reason: outcome.reason };}- const facts = outcome.facts;-// [ENG-8] Explicit ctx.visibility wins; unset resolves the operator-set// facts.default_visibility (fail-closed to 'private').const { resolveDefaultVisibility } = await import('./visibility.ts');const visibility = ctx.visibility ?? (await resolveDefaultVisibility(ctx.engine));+ const facts = await inferMissingSubjects(ctx, outcome.facts, visibility, input.pageSlug, managed);if (managed) return publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug);let inserted = 0;@@ -695,7 +698,7 @@ async function runPipelineBodyInner(// at write time). Threshold 0.95 unchanged.const exact = resolvedSlug ? await decideSingleFact(ctx.engine, ctx.sourceId, { entity_slug: resolvedSlug, fact: f.fact, kind: f.kind ?? 'fact', visibility }, null) : null;let matchedExistingId: number | null = exact?.candidate?.id ?? null;- if (matchedExistingId === null && resolvedSlug && f.embedding) {+ if (matchedExistingId === null && resolvedSlug && f.embedding && !f.entity_inferred) {const candidates = await ctx.engine.findCandidateDuplicates(ctx.sourceId,resolvedSlug,@@ -791,7 +794,7 @@ async function runPipelineBodyInner(// DB-only row has no fence to name the page it came from, so the page// path's slug fills context when the caller passed no sourceSlug.valid_from: f.valid_from ?? ctx.validFrom,- context: annotateUnverifiedResolution(ctx.sourceSlug ?? input.pageSlug ?? null, resolutionSource),+ context: annotateUnverifiedResolution(ctx.sourceSlug ?? input.pageSlug ?? null, resolutionSource, f.entity_inferred),};const result = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: legacy DB-only fallback for unparented / thin-client facts (no entity page to fence onto)fact_ids.push(result.id);@@ -819,7 +822,7 @@ async function runPipelineBodyInner(source: f.source,// #4206: the caller's source_slug (which page/transcript the turn came// from) lands in the fence context cell — visible in recall projections.- context: annotateUnverifiedResolution(ctx.sourceSlug ?? null, resolutionSource),+ context: annotateUnverifiedResolution(ctx.sourceSlug ?? null, resolutionSource, f.entity_inferred),visibility,confidence: f.confidence,// #4206: extractor-derived date wins; then the caller's event time@@ -868,7 +871,7 @@ async function runPipelineBodyInner(const newFact: NewFact = {fact: f.fact,kind: f.kind,- entity_slug: slug,+ entity_slug: f.entity_inferred ? null : slug,visibility,notability: f.notability,source: f.source,@@ -901,7 +904,7 @@ async function runPipelineBodyInner(const newFact: NewFact = {fact: f.fact,kind: f.kind,- entity_slug: slug,+ entity_slug: f.entity_inferred ? null : slug,visibility,notability: f.notability,source: f.source,diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.tsindex c25f29cf5c..09c283296b 100644--- a/src/core/facts/extract.ts+++ b/src/core/facts/extract.ts@@ -226,7 +226,11 @@ export interface ExtractInput {}/** A pre-INSERT fact ready for the engine.insertFact path. */-export type ExtractedFact = NewFact & { entity_slug: string | null };+export type ExtractedFact = NewFact & {+ entity_slug: string | null;+ /** #5836: the subject was inferred at write time (subject-infer-write.ts), not named by the extractor. */+ entity_inferred?: 'page' | 'mention';+};/*** Unknown/anonymous-speaker attribution gate.diff --git a/src/core/facts/subject-infer-write.ts b/src/core/facts/subject-infer-write.tsnew file mode 100644index 0000000000..eb82d1fbee--- /dev/null+++ b/src/core/facts/subject-infer-write.ts@@ -0,0 +1,87 @@+/**+ * Write-time fact subject inference for the facts backstop (#5836).+ *+ * The extractor sometimes returns a fact with no entity, or one that names+ * no live page. `inferMissingSubjects` gives such a fact the subject that+ * `inferFactSubject` proves from identity evidence (the page being written,+ * or one exact mention), and marks it `entity_inferred` so the writers+ * annotate its context and never supersede or drop a similar fact for it.+ *+ * Inference is applied only where the fact will be fenced: the unmanaged+ * DB-only branch (no local_path, or write-through off) would leave a+ * row_num-NULL row on a live page and jam the extract_facts legacy guard,+ * so those facts stay unattributed. A link is also dropped whenever the+ * writer would refuse it: caller slug fences, the managed batch's grant and+ * page visibility, a withdrawn claim, or a malformed target fence (which+ * would fail the whole write). Remote callers infer only from the page+ * actually being written and never from pages they cannot read.+ */++import type { BrainEngine } from '../engine.ts';+import type { FactsBackstopCtx } from './backstop.ts';+import type { ExtractedFact } from './extract.ts';+import type { ManagedFactsSession } from '../persistence/facts-maintenance.ts';+import { inferFactSubject, isEntityInferenceEnabled, type InferredVia } from './subject-infer.ts';++/** The context note an inferred link carries, in the DB row and the fence cell alike. */+export function inferenceNote(via: InferredVia): string {+ return `entity inferred from ${via}`;+}++export async function inferMissingSubjects(ctx: FactsBackstopCtx, facts: ExtractedFact[], visibility: 'private' | 'world',+ pageSlug: string | undefined, managed: ManagedFactsSession | null): Promise<ExtractedFact[]> {+ const engine = ctx.engine;+ if (!facts.length || !(await isEntityInferenceEnabled(engine))) return facts;+ if (!managed && await writesDatabaseOnly(engine, ctx.sourceId)) return facts;+ const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');+ const { excludesPrivateWrites } = await import('../persistence/page-visibility.ts');+ const remote = managed ? managed.authority.remote : (ctx.operationContext?.remote ?? ctx.remote) !== false;+ const excludePrivate = managed?.authority.excludePrivate === true || await excludesPrivateWrites(engine, remote);+ const fromPage = remote ? pageSlug : ctx.sourceSlug ?? pageSlug;+ const out: ExtractedFact[] = [];+ for (const f of facts) {+ const named = f.entity_slug ? await resolveEntitySlugWithSource(engine, ctx.sourceId, f.entity_slug) : null;+ if (named && named.source !== 'fallback_slugify') { out.push(f); continue; }+ const inferred = await inferFactSubject(engine, ctx.sourceId, { fact: f.fact, pageSlug: fromPage, mode: 'write', excludePrivate });+ if (inferred.slug !== null && await linkAllowed(ctx, inferred.slug, f.fact, visibility, remote, managed)) {+ out.push({ ...f, entity_slug: inferred.slug, entity_inferred: inferred.via });+ } else out.push(f);+ }+ return out;+}++async function writesDatabaseOnly(engine: BrainEngine, sourceId: string): Promise<boolean> {+ const { isWriteThroughDisabled } = await import('../write-through.ts');+ const { lookupSourceLocalPath } = await import('./fence-write.ts');+ return await isWriteThroughDisabled(engine) || await lookupSourceLocalPath(engine, sourceId) === null;+}++async function linkAllowed(ctx: FactsBackstopCtx, slug: string, fact: string, visibility: string, remote: boolean,+ managed: ManagedFactsSession | null): Promise<boolean> {+ const engine = ctx.engine;+ const { isFactWithdrawn } = await import('./withdrawal.ts');+ if (await isFactWithdrawn(engine, ctx.sourceId, visibility, fact, slug)) return false;+ try {+ const op = ctx.operationContext;+ if (remote && op) {+ const { enforceClientSlugFence, enforceSubagentSlugFence, validatePageSlug } = await import('../ops/context.ts');+ validatePageSlug(slug);+ enforceClientSlugFence(op, slug, 'extract_facts');+ enforceSubagentSlugFence(op, slug, 'extract_facts');+ }+ if (managed) {+ const { authorizeWrite } = await import('../persistence/authority.ts');+ const { authorizePageVisibility } = await import('../persistence/page-visibility.ts');+ await authorizeWrite(engine, managed.authority, 'extract_facts', slug);+ await authorizePageVisibility(engine, managed.authority, slug);+ }+ } catch (error) {+ const { OperationError } = await import('../ops/contract.ts');+ if (error instanceof OperationError) return false;+ throw error;+ }+ const page = await engine.readPageSnapshot(slug, { sourceId: ctx.sourceId });+ if (!page) return false;+ const { parseFactsFence } = await import('../facts-fence.ts');+ return parseFactsFence(page.page.compiled_truth).warnings.length === 0;+}diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex 0ca5beb6b5..ee1373f5b3 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -7,6 +7,8 @@ import { readFactsEmbeddingDim } from '../embedding-dim-check.ts';import type { OperationContext } from '../ops/contract.ts';import { OperationError } from '../ops/contract.ts';import { resolveEntitySlugWithSource } from '../entities/resolve.ts';+import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';+import { inferenceNote } from '../facts/subject-infer-write.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './authority.ts';import { authorizePageVisibility } from './page-visibility.ts';@@ -26,6 +28,8 @@ export interface ManagedFactsResult {export interface ManagedFactOrigin { slug: string; pageId: number; revision: string; }export type FrozenExtractedFact = Omit<NewFact, 'embedding' | 'valid_from' | 'valid_until' | 'expired_at'> & {embedding: number[] | null; valid_from: string; valid_until: string | null;+ /** #5836: a write-time inferred subject dedups exact text only, never superseding or dropping a similar fact. */+ entity_inferred?: InferredVia;};export interface ManagedFactIntent extends Record<string, unknown> {kind: 'managed_facts_entity' | 'managed_facts_complete';@@ -232,7 +236,9 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFawait authorizeWrite(engine, session.authority, 'extract_facts', slug);await authorizePageVisibility(engine, session.authority, slug);const group = groups.get(slug) ?? [];- group.push({ ...fact, entity_slug: attributed, visibility, context: options.explicitContext ? fact.context ?? null : ctx.sourceSlug ?? pageSlug ?? null,+ const context = options.explicitContext ? fact.context ?? null : ctx.sourceSlug ?? pageSlug ?? null;+ // #5836: an inferred subject carries its provenance note into the fence cell and the row.+ group.push({ ...fact, entity_slug: attributed, visibility, context: fact.entity_inferred ? appendContextNote(context, inferenceNote(fact.entity_inferred)) : context,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);diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex 1757d40531..c8d59c206c 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -15,6 +15,11 @@ import type { WriteRequest } from './model.ts';import type { ManagedFactIntent, FrozenExtractedFact } from './facts-maintenance.ts';import { assertManagedFactsEmbedding } from './facts-maintenance.ts';+/** #5836: an inferred subject dedups exact text only, so a similar fact is never superseded or dropped for it. */+function dedupEmbedding(fact: { embedding?: Float32Array | null; entity_inferred?: unknown }): Float32Array | null {+ return fact.entity_inferred ? null : fact.embedding ?? null;+}+function thawFact(fact: FrozenExtractedFact): NewFact & { entity_slug: string | null; kind: NonNullable<NewFact['kind']>; visibility: NonNullable<NewFact['visibility']> } {return { ...fact, entity_slug: fact.entity_slug ?? null, kind: fact.kind ?? 'fact', visibility: fact.visibility ?? 'private',valid_from: new Date(fact.valid_from), valid_until: fact.valid_until ? new Date(fact.valid_until) : null,@@ -93,7 +98,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writconst 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 decision = await decideSingleFact(engine, row.source_id, fact, dedupEmbedding(fact), 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 && !fallback(fact) ? nextRow++ : undefined;@@ -131,7 +136,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writfor (const entry of entries) {await assertFactNotWithdrawn(tx, row.source_id, entry.fact);if (entry.duplicateOf !== undefined) continue;- const current = await decideSingleFact(tx, row.source_id, entry.fact, entry.fact.embedding ?? null, entry.fact.embedding_model);+ const current = await decideSingleFact(tx, row.source_id, entry.fact, dedupEmbedding(entry.fact), entry.fact.embedding_model);if ((current.candidate?.id ?? null) !== (entry.duplicateId ?? entry.supersedes?.id ?? null)) throw new OperationError('revision_conflict', 'The fact deduplication state changed before publication.');}}, apply: async tx => {diff --git a/test/facts-backstop-entity-inference.test.ts b/test/facts-backstop-entity-inference.test.tsnew file mode 100644index 0000000000..5be7a97a68--- /dev/null+++ b/test/facts-backstop-entity-inference.test.ts@@ -0,0 +1,148 @@+/**+ * #5836 — the facts backstop infers a missing subject (zero LLM) from the+ * page being written or one exact mention, applies it only where the fact is+ * fenced, notes it in the context cell, and keeps remote callers inside+ * their fences and readable pages. Every write is followed by the+ * extract_facts reconcile, whose legacy guard must stay clear.+ *+ * PGLite, unmanaged (persistence off), chat stubbed. Synthetic names only.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runFactsBackstop, runFactsPipeline, type FactsBackstopCtx } from '../src/core/facts/backstop.ts';+import { __setChatTransportForTests, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';+import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';++let engine: PGLiteEngine;+let dir: string;+const BODY = 'notes from the quarterly planning review with the whole team present '.repeat(3);++function chatStub(facts: Array<{ fact: string; entity?: string | null }>) {+ __setChatTransportForTests(async (): Promise<ChatResult> => ({+ text: JSON.stringify({ facts: facts.map(f => ({ fact: f.fact, kind: 'fact', entity: f.entity ?? null, confidence: 1, notability: 'high' })) }),+ blocks: [], stopReason: 'end', model: 'test:stub', providerId: 'test',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },+ }));+}+const ctx = (overrides: Partial<FactsBackstopCtx> = {}): FactsBackstopCtx =>+ ({ engine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'inline', visibility: 'world', ...overrides });+const remoteOp = (overrides: Partial<OperationContext> = {}): OperationContext =>+ ({ engine, remote: true, sourceId: 'default', config: { engine: 'pglite' }, dryRun: false, logger: console, ...overrides } as OperationContext);+async function rows(ids: number[]) {+ return engine.executeRaw<{ id: number; fact: string; entity_slug: string | null; context: string | null; row_num: number | null; expired_at: Date | null }>(+ 'SELECT id,fact,entity_slug,context,row_num,expired_at FROM facts WHERE id=ANY($1::int[]) ORDER BY id', [ids]);+}+async function expectGuardClear() {+ const reconcile = await runExtractFacts(engine, { sourceId: 'default' });+ expect(reconcile.legacyRowsPending).toBe(0);+}+async function backstopPage(slug: string, type: 'note' | 'meeting') {+ const r = await runFactsBackstop({ slug, type, compiled_truth: BODY, frontmatter: {} }, ctx());+ if (r.mode !== 'inline') throw new Error('expected inline');+ return r;+}++beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ const page = (slug: string, title: string, type: string, frontmatter: Record<string, unknown> = {}) =>+ engine.putPage(slug, { type: type as never, title, compiled_truth: `# ${title}\n\n${BODY}`, frontmatter }, { sourceId: 'default' });+ await page('companies/acme-example', 'Acme Example', 'note');+ await page('companies/widget-example', 'Widget Example', 'company');+ await page('people/dana-private-example', 'Dana Private-Example', 'person', { visibility: 'private' });+ await page('meetings/2026-09-30-planning', 'Planning Review', 'meeting');+}, 60_000);+beforeEach(async () => {+ dir = mkdtempSync(join(tmpdir(), 'backstop-infer-'));+ await engine.executeRaw(`UPDATE sources SET local_path=$1 WHERE id='default'`, [dir]);+ _resetWriteThroughCacheForTest();+});+afterEach(async () => {+ __setChatTransportForTests(null); resetGateway(); __resetFactsQueueForTests();+ await engine.unsetConfig('sync.write_through'); await engine.unsetConfig('facts.entity_inference');+ await engine.executeRaw(`UPDATE sources SET local_path=NULL WHERE id='default'`);+ _resetWriteThroughCacheForTest();+ rmSync(dir, { recursive: true, force: true });+});+afterAll(async () => { await engine.disconnect(); });++describe('facts backstop write-time inference (#5836)', () => {+ test('a subjectless fact on an entity page lands on that page fence with the inference note', async () => {+ chatStub([{ fact: 'Raised a seed round led by a new fund' }]);+ const r = await backstopPage('companies/acme-example', 'note');+ expect(r.inserted).toBe(1);+ const [row] = await rows(r.fact_ids);+ expect(row).toMatchObject({ entity_slug: 'companies/acme-example', context: 'entity inferred from page' });+ expect(row.row_num).not.toBeNull();+ expect((r as { entity_slugs?: string[] }).entity_slugs).toEqual(['companies/acme-example']);+ const file = readFileSync(join(dir, 'companies/acme-example.md'), 'utf8');+ expect(file).toContain('Raised a seed round led by a new fund');+ expect(file).toContain('entity inferred from page');+ await expectGuardClear();+ });++ test('a meeting page never becomes a subject; an exact mention on it still links', async () => {+ chatStub([{ fact: 'The team agreed to ship in October' }, { fact: 'Widget Example asked for a pilot extension' }]);+ const r = await backstopPage('meetings/2026-09-30-planning', 'meeting');+ const [unlinked, linked] = await rows(r.fact_ids);+ expect(unlinked.entity_slug).toBeNull();+ expect(linked).toMatchObject({ entity_slug: 'companies/widget-example', context: 'entity inferred from mention' });+ await expectGuardClear();+ });++ test('a remote extract_facts never infers from source_slug, a private page or an out-of-fence entity', async () => {+ chatStub([{ fact: 'Opened a second office in the spring' }]);+ const local = await runFactsPipeline('turn', ctx({ source: 'mcp:extract_facts', sourceSlug: 'companies/acme-example',+ operationContext: remoteOp({ remote: false }) }));+ expect((await rows(local.fact_ids))[0].entity_slug).toBe('companies/acme-example');+ const remoteSlug = await runFactsPipeline('turn', ctx({ source: 'mcp:extract_facts', sourceSlug: 'companies/acme-example',+ remote: true, operationContext: remoteOp() }));+ expect((await rows(remoteSlug.fact_ids))[0].entity_slug).toBeNull();++ chatStub([{ fact: 'Dana Private-Example is relocating to the coast' }]);+ const hidden = await runFactsPipeline('turn', ctx({ source: 'mcp:extract_facts', remote: true, operationContext: remoteOp() }));+ expect((await rows(hidden.fact_ids))[0].entity_slug).toBeNull();++ chatStub([{ fact: 'Widget Example renewed the annual contract' }]);+ const fenced = await runFactsPipeline('turn', ctx({ source: 'mcp:extract_facts', remote: true,+ operationContext: remoteOp({ auth: { token: 'fixture', clientId: 'c', scopes: ['read', 'write'], boundSlugPrefixes: ['people/'] } as OperationContext['auth'] }) }));+ expect((await rows(fenced.fact_ids))[0].entity_slug).toBeNull();+ const open = await runFactsPipeline('turn', ctx({ source: 'mcp:extract_facts', remote: true, operationContext: remoteOp() }));+ expect(open.duplicate + open.inserted).toBe(1);+ expect((await rows(open.fact_ids))[0].entity_slug).toBe('companies/widget-example');+ await expectGuardClear();+ });++ test('the unmanaged DB-only branch never applies an inferred subject', async () => {+ await engine.setConfig('sync.write_through', 'false');+ _resetWriteThroughCacheForTest();+ chatStub([{ fact: 'Acme Example hired a VP of engineering' }]);+ const off = await backstopPage('meetings/2026-09-30-planning', 'meeting');+ expect((await rows(off.fact_ids))[0]).toMatchObject({ entity_slug: null, row_num: null });+ await expectGuardClear();+ await engine.unsetConfig('sync.write_through');+ _resetWriteThroughCacheForTest();+ chatStub([{ fact: 'Acme Example hired a VP of sales' }]);+ const on = await backstopPage('meetings/2026-09-30-planning', 'meeting');+ expect((await rows(on.fact_ids))[0].entity_slug).toBe('companies/acme-example');+ await expectGuardClear();+ });++ test('the facts.entity_inference kill switch leaves the fact unlinked', async () => {+ await engine.setConfig('facts.entity_inference', 'off');+ chatStub([{ fact: 'Closed the bridge round in August' }]);+ const r = await backstopPage('companies/acme-example', 'note');+ expect((await rows(r.fact_ids))[0].entity_slug).toBeNull();+ await expectGuardClear();+ await engine.unsetConfig('facts.entity_inference');+ chatStub([{ fact: 'Closed the bridge round in September' }]);+ const on = await backstopPage('companies/acme-example', 'note');+ expect((await rows(on.fact_ids))[0].entity_slug).toBe('companies/acme-example');+ await expectGuardClear();+ });+});diff --git a/test/helpers/managed-facts-contract.ts b/test/helpers/managed-facts-contract.tsindex 287ec17050..3467fcaea5 100644--- a/test/helpers/managed-facts-contract.ts+++ b/test/helpers/managed-facts-contract.ts@@ -36,6 +36,9 @@ export async function exerciseManagedFacts(engine: BrainEngine, scenario: Case):await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');await engine.setConfig('version', '162');await engine.setConfig('facts.default_visibility', 'private');+ // The unparented case pins the fallback-entity -> NULL path; its fixture text names a+ // registered entity, which #5836 write-time inference would otherwise link.+ if (scenario === 'unparented') await engine.setConfig('facts.entity_inference', 'off');await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);const firstSlug = 'people/alice-example', secondSlug = 'companies/acme-example';const oldBody = upsertFactRow('A registered entity.', { claim: 'An older retained fact.', kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium', source: 'fixture' }).body;@@ -184,5 +187,5 @@ export async function exerciseManagedFacts(engine: BrainEngine, scenario: Case):expect(afterVector.vector).toBe(beforeVector.vector);if (scenario === 'unparented') expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND entity_slug IS NULL', [sourceId])).toHaveLength(1);});- } finally { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); __setChatTransportForTests(null); __setEmbedTransportForTests(null); resetGateway(); rmSync(home, { recursive: true, force: true }); }+ } finally { await disposePersistenceConsumer(engine); await engine.unsetConfig('facts.entity_inference'); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); __setChatTransportForTests(null); __setEmbedTransportForTests(null); resetGateway(); rmSync(home, { recursive: true, force: true }); }}diff --git a/test/managed-facts-entity-inference.test.ts b/test/managed-facts-entity-inference.test.tsnew file mode 100644index 0000000000..f773a6c995--- /dev/null+++ b/test/managed-facts-entity-inference.test.ts@@ -0,0 +1,67 @@+/**+ * #5836 — managed (coordinator) extract_facts: an inferred subject publishes+ * through publishManagedFacts with its context note in the fence cell and the+ * row, and a similar fact on the same entity is kept rather than deduped,+ * while exact text still dedups. PGLite, synthetic names only.+ */+import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+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 { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);+beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');+ await engine.setConfig('embedding_dimensions', '1536');+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'test' } });+});+afterEach(() => { __setChatTransportForTests(null); __setEmbedTransportForTests(null); resetGateway(); });+afterAll(async () => { await engine.disconnect(); });++function chatStub(facts: Array<{ fact: string; entity: string | null }>) {+ __setChatTransportForTests(async () => ({ text: JSON.stringify({ facts: facts.map(f => ({ ...f, kind: 'fact', confidence: 1, 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' }));+}++test('managed extract_facts links an inferred subject with its note and keeps a similar fact', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-infer-'));+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'A registered entity.' }, { sourceId: 'default' });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => Array(1536).fill(0.01)) })) as never);+ const ctx = { engine, config: { engine: 'pglite' as const }, remote: false, sourceId: 'default', dryRun: false, logger: console };+ const extract = (fact: string, entity: string | null) => {+ chatStub([{ fact, entity }]);+ return operationsByName.extract_facts.handler(ctx, { turn_text: `A synthetic turn about ${fact}`, request_id: randomUUID(), visibility: 'world' }) as Promise<{ inserted: number; duplicate: number; fact_ids: number[] }>;+ };+ const explicit = await extract('Acme Example targets 40 percent gross margin', 'companies/acme-example');+ expect(explicit.inserted).toBe(1);+ const inferred = await extract('Acme Example targets 45 percent gross margin', null);+ expect(inferred).toMatchObject({ inserted: 1, duplicate: 0 });+ const facts = await engine.executeRaw<{ id: number; fact: string; entity_slug: string | null; context: string | null; expired_at: Date | null; row_num: number | null }>(+ 'SELECT id,fact,entity_slug,context,expired_at,row_num FROM facts WHERE id=ANY($1::int[]) ORDER BY id', [[...explicit.fact_ids, ...inferred.fact_ids]]);+ expect(facts.map(f => [f.entity_slug, f.expired_at])).toEqual([['companies/acme-example', null], ['companies/acme-example', null]]);+ expect(facts[1].context).toBe('entity inferred from mention');+ expect(facts[1].row_num).not.toBeNull();+ const fence = parseFactsFence((await engine.getPage('companies/acme-example', { sourceId: 'default' }))!.compiled_truth).facts;+ expect(fence.find(f => f.claim === 'Acme Example targets 45 percent gross margin')?.context).toBe('entity inferred from mention');+ expect(fence.every(f => f.active)).toBe(true);+ const exact = await extract('Acme Example targets 45 percent gross margin', null);+ expect(exact).toMatchObject({ inserted: 0, duplicate: 1 });+ expect((await runExtractFacts(engine, { sourceId: 'default' })).legacyRowsPending).toBe(0);+ });+ } finally { await disposePersistenceConsumer(engine); rmSync(home, { recursive: true, force: true }); }+}, 60_000);