Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(facts): zero-LLM fact subject inference (#5836)

garrytane7ea7c35b720
diff --git a/src/core/context/entity-salience.ts b/src/core/context/entity-salience.ts
index 6f6fbeab7b..6a48d022c2 100644
--- a/src/core/context/entity-salience.ts
+++ b/src/core/context/entity-salience.ts
@@ -46,6 +46,11 @@ export interface EntityCandidate {
* lowercase words cannot fabricate pointers.
*/
weak?: true;
+ /**
+ * Single-token strong candidate seen capitalized only at the start of a
+ * sentence, so the capital is no evidence that it is a name ("Met", "Raised").
+ */
+ sentenceStart?: true;
}
/** Max STRONG candidates returned per turn — bounds downstream DB work regardless of pointer cap. */
@@ -109,6 +114,11 @@ const COMMON_WORDS = new Set<string>([
'next', 'new', 'old', 'good', 'bad', 'great', 'nice', 'thing', 'something', 'anything',
]);
+/** True for frequent non-entity words (weekdays, months, time words) that get capitalized. */
+export function isCommonCapitalizedWord(token: string): boolean {
+ return COMMON_WORDS.has(token.toLowerCase());
+}
+
const HANDLE_RE = /@([A-Za-z0-9_]{2,})/g;
// Capitalized token runs: an uppercase-initial word, up to 4 tokens total.
// A token allows internal letters/digits/apostrophes/hyphens, plus internal
@@ -237,7 +247,7 @@ export function extractCandidates(text: string): EntityCandidate[] {
// "Apple" or a person whose name collides with a common word).
if (COMMON_WORDS.has(lc) && !c.seenMidSentence) continue;
}
- out.push({ display: c.display, query: c.query });
+ out.push({ display: c.display, query: c.query, ...(!c.multiToken && !c.seenMidSentence ? { sentenceStart: true as const } : {}) });
if (out.length >= MAX_CANDIDATES) break;
}
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index 3b85b230d8..c9245cc9f0 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -25,6 +25,7 @@ import type { BrainEngine } from '../engine.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
import { foldNonDecomposingLatin } from '../latin-fold.ts';
import { isUndefinedTableError } from '../utils.ts';
+import { privatePagesFilterFragment } from '../search/private-visibility.ts';
/**
* Canonicalize a free-form entity reference to a page slug.
@@ -126,7 +127,7 @@ const FACT_ENTITY_TYPES = new Set(['concept', 'project', 'deal']);
const FACT_ENTITY_DIRS = ['hosts/', 'projects/', 'concepts/', 'deals/'];
/** Pages a fuzzy fact attribution may land on: entities, never meetings, notes or other documents. */
-function isFactEntityPage(slug: string, type: string | null): boolean {
+export function isFactEntityPage(slug: string, type: string | null): boolean {
return isIdentityEntity(slug, type) || (type != null && FACT_ENTITY_TYPES.has(type))
|| FACT_ENTITY_DIRS.some(dir => slug.startsWith(dir));
}
@@ -288,6 +289,93 @@ export async function resolveEntitySlugWithSource(
return { slug: fallbackSlugify(trimmed), source: 'fallback_slugify' };
}
+/**
+ * How a strict reference resolution found its page. `basename` is the
+ * unique-slug-basename arm and `same_name` the trigram arm restricted to
+ * pages carrying the same name tokens (both are `fuzzy_match` in
+ * resolveEntitySlugWithSource).
+ */
+export type StrictResolutionArm = 'exact_page' | 'alias_exact' | 'basename' | 'same_name';
+
+/**
+ * A strict resolution miss: `ambiguous` (two live pages qualify),
+ * `unverified` (only a bare-name prefix guess exists), `not_entity` (the
+ * reference names a live page that is not a fact entity, e.g. a meeting) or
+ * `no_page`.
+ */
+export type StrictResolution =
+ | { slug: string; arm: StrictResolutionArm }
+ | { slug: null; miss: 'ambiguous' | 'unverified' | 'not_entity' | 'no_page' };
+
+/**
+ * Resolve a name to a live fact-entity page using only identity evidence:
+ * exact slug, unique slug basename, unique alias and, with `sameName`, the
+ * same-name trigram arm. Never guesses from a bare-name prefix and never
+ * falls back to a slugified name. With `excludePrivate`, private pages are
+ * removed before uniqueness is counted, so an unreadable namesake can neither
+ * be returned nor change the outcome for a remote caller.
+ */
+export async function resolveStrictEntityReference(
+ engine: BrainEngine,
+ source_id: string,
+ raw: string,
+ opts: { sameName?: boolean; excludePrivate?: boolean } = {},
+): Promise<StrictResolution> {
+ const trimmed = raw.trim();
+ if (!trimmed) return { slug: null, miss: 'no_page' };
+ const privacy = opts.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';
+ const live = async (slugs: string[]) => slugs.length === 0 ? [] : engine.executeRaw<{ slug: string; type: string | null }>(
+ `SELECT p.slug, p.type FROM pages p
+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.slug = ANY($2::text[]) ${privacy}`,
+ [source_id, [...new Set(slugs)]],
+ );
+ const pick = (rows: Array<{ slug: string; type: string | null }>, arm: StrictResolutionArm): StrictResolution | null => {
+ if (rows.length > 1) return { slug: null, miss: 'ambiguous' };
+ if (rows.length === 0) return null;
+ return isFactEntityPage(rows[0].slug, rows[0].type) ? { slug: rows[0].slug, arm } : { slug: null, miss: 'not_entity' };
+ };
+
+ if (looksLikeSlug(trimmed)) {
+ const exact = pick(await live([trimmed]), 'exact_page');
+ if (exact) return exact;
+ }
+ const token = slugify(trimmed);
+ if (!trimmed.includes('/') && token.includes('-')) {
+ const basename = pick(await live([...PREFIX_EXPANSION_DIRS, 'concepts'].map(dir => `${dir}/${token}`)), 'basename');
+ if (basename) return basename;
+ }
+ const norm = normalizeAlias(trimmed);
+ if (norm) {
+ try {
+ const hits = (await engine.resolveAliases([norm], { sourceId: source_id })).get(norm) ?? [];
+ const aliased = pick(await live(hits.map(h => h.slug)), 'alias_exact');
+ if (aliased) return aliased;
+ } catch (err) {
+ if (!isUndefinedTableError(err)) throw err;
+ }
+ }
+ if (opts.sameName && !isBareName(trimmed)) {
+ try {
+ const rows = await engine.executeRaw<{ slug: string; title: string; type: string | null }>(
+ `SELECT p.slug, p.title, p.type FROM pages p
+ WHERE p.source_id = $1 AND p.deleted_at IS NULL ${privacy}
+ AND (lower(p.title) % $2 OR p.slug ILIKE '%' || $3 || '%')
+ ORDER BY GREATEST(similarity(lower(p.title), $2), similarity(p.slug, $3)) DESC, p.slug ASC
+ LIMIT 5`,
+ [source_id, trimmed.toLowerCase(), token],
+ );
+ const named = pick(rows.filter(row => isFactEntityPage(row.slug, row.type) && sameEntityName(trimmed, row.title, row.slug)), 'same_name');
+ if (named) return named;
+ } catch (err) {
+ if (!isMissingTrigramError(err)) throw err;
+ }
+ }
+ if (isBareName(trimmed) && token && (await findPrefixCandidates(engine, source_id, token)).length > 0) {
+ return { slug: null, miss: 'unverified' };
+ }
+ return { slug: null, miss: 'no_page' };
+}
+
/**
* v0.35.5 — phantom-canonical resolver. Variant of `resolveEntitySlug` that
* SKIPS the exact-slug step at the top: a phantom slug like `'alice'` would
@@ -463,7 +551,7 @@ async function tryPrefixExpansion(
return null;
}
-function looksLikeSlug(s: string): boolean {
+export function looksLikeSlug(s: string): boolean {
// Slug shape: lowercase letters/digits with at least one slash OR matches
// [a-z0-9-]+ exactly. Anything with whitespace or capital letters fails.
if (/\s/.test(s)) return false;
diff --git a/src/core/facts/subject-infer.ts b/src/core/facts/subject-infer.ts
new file mode 100644
index 0000000000..9a6a296392
--- /dev/null
+++ b/src/core/facts/subject-infer.ts
@@ -0,0 +1,151 @@
+/**
+ * Zero-LLM fact subject inference (#5836).
+ *
+ * A fact saved without an entity is invisible to everything that groups facts
+ * by entity: the `## Facts` fence, entity-scoped recall and the System One
+ * conflict sweep. This module names the entity a fact is about using identity
+ * evidence only, so the write paths (remember, the facts backstop) and the
+ * `gbrain facts relink` repair share one rule:
+ *
+ * - page: the fact came from a live fact-entity page (the page being written,
+ * or a recorded page provenance for relink), and the text names no other
+ * entity.
+ * - mention: the text names exactly one live fact-entity page by exact slug,
+ * unique slug basename or unique alias (relink also accepts the same-name
+ * trigram arm), and no other real name competes with it.
+ *
+ * A competing name vetoes the link even when it has no page ("Northstar
+ * Example copied Acme Example's pricing" names two companies; only one has a
+ * page, so the subject is unknown, not Acme). Bare first names are never
+ * guessed. Every lookup is source-scoped; `excludePrivate` keeps a remote
+ * caller from inferring (or detecting) pages it cannot read.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { extractCandidates, isCommonCapitalizedWord } from '../context/entity-salience.ts';
+import { isFactEntityPage, resolveStrictEntityReference, type StrictResolution } from '../entities/resolve.ts';
+import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+
+export type InferredVia = 'page' | 'mention';
+export type InferMissReason = 'ambiguous' | 'unverified_match' | 'no_mention' | 'no_page';
+export type InferResult = { slug: string; via: InferredVia } | { slug: null; reason: InferMissReason };
+
+export interface InferSubjectInput {
+ fact: string;
+ /** A trusted page the fact came from: the page being written, or relink's recorded page provenance. */
+ pageSlug?: string | null;
+ /** `write` (remember, backstop) accepts identity arms only; `relink` also accepts the same-name trigram arm. */
+ mode: 'write' | 'relink';
+ /** Remote callers: private pages never resolve and never count toward uniqueness. */
+ excludePrivate?: boolean;
+}
+
+/** The note separator every fact context annotation uses ("<page slug> — <note>"). */
+export const CONTEXT_NOTE_SEPARATOR = ' — ';
+
+/** Append a provenance note to a fact context cell, keeping any page slug prefix parseable. */
+export function appendContextNote(context: string | null | undefined, note: string): string {
+ return context ? `${context}${CONTEXT_NOTE_SEPARATOR}${note}` : note;
+}
+
+/** The context cell with every appended note removed (the original page slug or free text). */
+export function contextHead(context: string | null | undefined): string | null {
+ if (!context) return null;
+ const head = context.split(CONTEXT_NOTE_SEPARATOR, 1)[0]!.trim();
+ return head || null;
+}
+
+/** facts.source values written by page-extraction paths, whose context head is the source page slug. */
+const PAGE_EXTRACTION_SOURCES = new Set(['mcp:put_page', 'sync:import', 'file_upload', 'code_import']);
+
+/**
+ * The page a stored fact was extracted from, when its row records one: a
+ * page-extraction source and a context head that is a path-shaped slug.
+ * Liveness and entity type are checked by inferFactSubject. Free-text
+ * provenance (remember's "chat 2026-06-12") is never page provenance.
+ */
+export function recordedPageSlug(context: string | null | undefined, source: string | null | undefined): string | null {
+ if (!source || !PAGE_EXTRACTION_SOURCES.has(source)) return null;
+ const head = contextHead(context);
+ return head && head.includes('/') && !/\s/.test(head) ? head : null;
+}
+
+/** `facts.entity_inference` off values disable write-time inference (relink is unaffected). */
+export async function isEntityInferenceEnabled(engine: BrainEngine): Promise<boolean> {
+ const raw = await engine.getConfig('facts.entity_inference');
+ return !/^(off|false|0|no|disabled)$/i.test((raw ?? '').trim());
+}
+
+/**
+ * Capitalized role and business terms that are not names, so they never veto
+ * ("Acme Example hired a CFO"). Real acronym names (a company called IBM) are
+ * not here and still compete.
+ */
+const ROLE_AND_TERM_TOKENS = new Set([
+ 'ceo', 'cfo', 'cto', 'coo', 'cmo', 'cpo', 'cro', 'vp', 'svp', 'evp', 'gm', 'pm', 'hr', 'qa', 'ops',
+ 'api', 'sdk', 'ai', 'ml', 'mvp', 'kpi', 'okr', 'okrs', 'arr', 'mrr', 'ipo', 'loi', 'nda', 'saas', 'b2b', 'b2c',
+ 'pr', 'ui', 'ux', 'q1', 'q2', 'q3', 'q4', 'h1', 'h2', 'fy', 'eod', 'eow', 'asap', 'faq', 'tbd', 'n/a',
+]);
+
+/** Slugs written verbatim in the fact text ("people/alice-example owns the checklist"). */
+const SLUG_IN_TEXT_RE = /(?<![\w/-])[a-z0-9][a-z0-9_-]*(?:\/[a-z0-9][a-z0-9_-]*)+(?![\w/-])/g;
+
+/** Two distinct entities already make the subject unknown; more resolution is wasted work. */
+const DISTINCT_ENTITY_LIMIT = 2;
+
+export async function inferFactSubject(engine: BrainEngine, sourceId: string, input: InferSubjectInput): Promise<InferResult> {
+ const candidates: Array<{ query: string; sentenceStart?: true }> = [
+ ...[...new Set(input.fact.match(SLUG_IN_TEXT_RE) ?? [])].map(query => ({ query })),
+ ...extractCandidates(input.fact).filter(c => !c.weak),
+ ];
+ const resolved = new Set<string>();
+ const misses: Array<Exclude<StrictResolution, { slug: string }>['miss']> = [];
+ let vetoed = false;
+ const memo = new Map<string, StrictResolution>();
+ for (const candidate of candidates) {
+ const key = candidate.query.toLowerCase();
+ let r = memo.get(key);
+ if (!r) {
+ r = await resolveStrictEntityReference(engine, sourceId, candidate.query,
+ { sameName: input.mode === 'relink', excludePrivate: input.excludePrivate });
+ memo.set(key, r);
+ }
+ if (r.slug !== null) {
+ resolved.add(r.slug);
+ if (resolved.size >= DISTINCT_ENTITY_LIMIT) return { slug: null, reason: 'ambiguous' };
+ continue;
+ }
+ misses.push(r.miss);
+ // A name that is not an entity page (a meeting title) does not compete. A
+ // capitalized sentence opener with no page ("Met", "Raised") is no name
+ // evidence; anything else unresolved is a real competing reference.
+ if (r.miss === 'not_entity') continue;
+ if (r.miss === 'no_page' && (candidate.sentenceStart || isNonName(candidate.query))) continue;
+ vetoed = true;
+ }
+
+ const page = input.pageSlug ? await liveFactEntityPage(engine, sourceId, input.pageSlug, input.excludePrivate) : null;
+ if (page) {
+ if (vetoed || (resolved.size === 1 && !resolved.has(page))) return { slug: null, reason: 'ambiguous' };
+ return { slug: page, via: 'page' };
+ }
+ if (resolved.size === 1 && !vetoed) return { slug: [...resolved][0]!, via: 'mention' };
+ if (resolved.size > 0 || misses.includes('ambiguous')) return { slug: null, reason: 'ambiguous' };
+ if (misses.includes('unverified')) return { slug: null, reason: 'unverified_match' };
+ if (misses.some(m => m === 'no_page')) return { slug: null, reason: vetoed ? 'no_page' : 'no_mention' };
+ return { slug: null, reason: 'no_mention' };
+}
+
+function isNonName(query: string): boolean {
+ if (/\s/.test(query)) return false;
+ return isCommonCapitalizedWord(query) || ROLE_AND_TERM_TOKENS.has(query.toLowerCase());
+}
+
+async function liveFactEntityPage(engine: BrainEngine, sourceId: string, slug: string, excludePrivate?: boolean): Promise<string | null> {
+ const privacy = excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';
+ const [row] = await engine.executeRaw<{ slug: string; type: string | null }>(
+ `SELECT p.slug, p.type FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL ${privacy} LIMIT 1`,
+ [sourceId, slug],
+ );
+ return row && isFactEntityPage(row.slug, row.type) ? row.slug : null;
+}
diff --git a/test/facts-subject-infer.test.ts b/test/facts-subject-infer.test.ts
new file mode 100644
index 0000000000..bcc62e1182
--- /dev/null
+++ b/test/facts-subject-infer.test.ts
@@ -0,0 +1,210 @@
+/**
+ * #5836 — zero-LLM fact subject inference. A labeled synthetic fixture pins
+ * precision (write time >= 0.99, relink free tiers >= 0.95) and the
+ * competing-name veto, plus the page tier, private-page scope and source
+ * isolation. Synthetic data only.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import {
+ appendContextNote, contextHead, inferFactSubject, isEntityInferenceEnabled, recordedPageSlug,
+} from '../src/core/facts/subject-infer.ts';
+
+let engine: PGLiteEngine;
+
+const page = (slug: string, title: string, type: string, extra = '') =>
+ importFromContent(engine, slug, `---\ntitle: ${title}\ntype: ${type}\n${extra}---\n\n# ${title}\n`, { noEmbed: true });
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await page('companies/acme-example', 'Acme Example', 'company');
+ await page('companies/widget-co', 'Widget Co', 'company', 'aliases:\n - "WidgetWorks"\n');
+ await page('people/alice-example', 'Alice Example', 'person', 'aliases:\n - "Ali Example"\n');
+ await page('people/charlie-example', 'Charlie Example', 'person');
+ await page('people/bob-example', 'Bob Example', 'person');
+ await page('projects/apollo-example', 'Apollo Example', 'project');
+ await page('people/sam-lee-example', 'Sam Lee-Example', 'person');
+ await page('companies/sam-lee-example', 'Sam Lee-Example', 'company');
+ await page('people/dana-private-example', 'Dana Private-Example', 'person', 'visibility: private\n');
+ await page('meetings/2026-04-03', 'Acme Example Sync', 'meeting');
+ await page('concepts/hiring-plan-example', 'Hiring Plan Example', 'concept');
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+type Case = { fact: string; expect: string | null; page?: string };
+
+// Labeled write-time fixture: `expect` is the correct subject, or null when
+// the subject is unknown, has no page, or more than one entity competes.
+const WRITE_CASES: Case[] = [
+ { fact: 'Acme Example raised a seed round', expect: 'companies/acme-example' },
+ { fact: 'Acme Example hired a CFO', expect: 'companies/acme-example' },
+ { fact: "Met with Acme Example's founders about pricing", expect: 'companies/acme-example' },
+ { fact: 'The board at Acme Example approved the budget', expect: 'companies/acme-example' },
+ { fact: 'She joined Acme Example as head of sales', expect: 'companies/acme-example' },
+ { fact: 'Alice Example prefers async updates', expect: 'people/alice-example' },
+ // A place name competes like any other name: a recall miss, never a wrong link.
+ { fact: 'Alice Example moved to Lisbon', expect: 'people/alice-example' },
+ { fact: 'Ali Example is vegetarian', expect: 'people/alice-example' },
+ { fact: 'Talked to WidgetWorks about the renewal', expect: 'companies/widget-co' },
+ { fact: 'Widget Co signed the pilot', expect: 'companies/widget-co' },
+ { fact: 'Charlie Example wants weekly check-ins', expect: 'people/charlie-example' },
+ { fact: 'Apollo Example ships next quarter', expect: 'projects/apollo-example' },
+ { fact: 'Hiring Plan Example needs two more engineers', expect: 'concepts/hiring-plan-example' },
+ { fact: 'people/charlie-example owns the launch checklist', expect: 'people/charlie-example' },
+ // Two entities with pages: unknown subject.
+ { fact: 'Alice Example introduced me to Charlie Example', expect: null },
+ { fact: 'Acme Example is buying Widget Co', expect: null },
+ { fact: 'Charlie Example left Acme Example for Widget Co', expect: null },
+ // A competing real name with no page vetoes the one with a page.
+ { fact: "Northstar Example copied Acme Example's pricing", expect: null },
+ { fact: 'Acme Example lost the deal to Bluebird Labs', expect: null },
+ { fact: 'Charlie Example and Morgan Example cofounded a fund', expect: null },
+ // Bare first names are never guessed, and veto a real match.
+ { fact: 'Bob said the demo went well', expect: null },
+ { fact: 'Bob joined Acme Example last month', expect: null },
+ { fact: 'Alice wants the deck by Friday', expect: null },
+ // Ambiguous basename: two pages share the name.
+ { fact: 'Sam Lee-Example closed the round', expect: null },
+ // Names that resolve to a non-entity page do not count.
+ { fact: 'Acme Example Sync moved to Thursday', expect: null },
+ // No names at all.
+ { fact: 'I prefer dark mode in every editor', expect: null },
+ { fact: 'ate oatmeal and two eggs for breakfast', expect: null },
+ { fact: 'slept 7 hours, resting heart rate 52', expect: null },
+ { fact: 'remember to renew the passport before june', expect: null },
+ { fact: 'Need to book flights for the offsite', expect: null },
+ { fact: 'Raised the thermostat to 70', expect: null },
+ // Lowercase mentions are not identity evidence at write time.
+ { fact: 'acme example raised a seed round', expect: null },
+ // Private page: local callers resolve it (remote scope is tested below).
+ { fact: 'Dana Private-Example is relocating', expect: 'people/dana-private-example' },
+ // Page tier: the fact came from an entity page.
+ { fact: 'raised a seed round in March', page: 'companies/acme-example', expect: 'companies/acme-example' },
+ { fact: 'Acme Example raised a seed round', page: 'companies/acme-example', expect: 'companies/acme-example' },
+ { fact: 'prefers async updates', page: 'people/alice-example', expect: 'people/alice-example' },
+ { fact: "Northstar Example copied Acme Example's pricing", page: 'companies/acme-example', expect: null },
+ { fact: 'Widget Co signed the pilot', page: 'companies/acme-example', expect: null },
+ { fact: 'Bob said the demo went well', page: 'people/alice-example', expect: null },
+ // Page tier never applies to non-entity pages.
+ { fact: 'decided to ship on Friday', page: 'meetings/2026-04-03', expect: null },
+ { fact: 'Acme Example raised a seed round', page: 'meetings/2026-04-03', expect: 'companies/acme-example' },
+ { fact: 'ate oatmeal for breakfast', page: 'daily/2026-04-03', expect: null },
+];
+
+async function score(cases: Case[], mode: 'write' | 'relink') {
+ let links = 0;
+ let correct = 0;
+ let found = 0;
+ const wrong: string[] = [];
+ for (const c of cases) {
+ const r = await inferFactSubject(engine, 'default', { fact: c.fact, pageSlug: c.page ?? null, mode });
+ if (c.expect) found += 1;
+ if (r.slug === null) {
+ if (c.expect) wrong.push(`missed: ${c.fact} -> ${c.expect} (${r.reason})`);
+ continue;
+ }
+ links += 1;
+ if (r.slug === c.expect) correct += 1;
+ else wrong.push(`wrong: ${c.fact} -> ${r.slug} (want ${c.expect})`);
+ }
+ return { precision: links ? correct / links : 1, recall: found ? correct / found : 1, wrong };
+}
+
+describe('inferFactSubject precision fixture', () => {
+ test('fixture has at least 40 labeled facts', () => {
+ expect(WRITE_CASES.length).toBeGreaterThanOrEqual(40);
+ });
+
+ test('write-time precision >= 0.99', async () => {
+ const r = await score(WRITE_CASES, 'write');
+ console.log(`[subject-infer] write precision=${r.precision.toFixed(3)} recall=${r.recall.toFixed(3)}`, r.wrong);
+ expect(r.wrong.filter(w => w.startsWith('wrong'))).toEqual([]);
+ expect(r.precision).toBeGreaterThanOrEqual(0.99);
+ });
+
+ test('relink free-tier precision >= 0.95', async () => {
+ const r = await score(WRITE_CASES, 'relink');
+ console.log(`[subject-infer] relink precision=${r.precision.toFixed(3)} recall=${r.recall.toFixed(3)}`);
+ expect(r.precision).toBeGreaterThanOrEqual(0.95);
+ });
+});
+
+describe('inferFactSubject reasons', () => {
+ test('veto by a name with no page reports ambiguous', async () => {
+ expect(await inferFactSubject(engine, 'default', { fact: "Northstar Example copied Acme Example's pricing", mode: 'write' }))
+ .toEqual({ slug: null, reason: 'ambiguous' });
+ });
+ test('a bare first name with a prefix candidate reports unverified_match', async () => {
+ expect(await inferFactSubject(engine, 'default', { fact: 'Bob said the demo went well', mode: 'write' }))
+ .toEqual({ slug: null, reason: 'unverified_match' });
+ });
+ test('a real name with no page reports no_page', async () => {
+ expect(await inferFactSubject(engine, 'default', { fact: 'Bluebird Labs raised a seed round', mode: 'write' }))
+ .toEqual({ slug: null, reason: 'no_page' });
+ });
+ test('no names reports no_mention', async () => {
+ expect(await inferFactSubject(engine, 'default', { fact: 'slept 7 hours', mode: 'write' }))
+ .toEqual({ slug: null, reason: 'no_mention' });
+ });
+ test('mention and page tiers are labeled', async () => {
+ expect(await inferFactSubject(engine, 'default', { fact: 'Acme Example raised a seed round', mode: 'write' }))
+ .toEqual({ slug: 'companies/acme-example', via: 'mention' });
+ expect(await inferFactSubject(engine, 'default', { fact: 'raised a seed round', pageSlug: 'companies/acme-example', mode: 'write' }))
+ .toEqual({ slug: 'companies/acme-example', via: 'page' });
+ });
+});
+
+describe('inferFactSubject scope', () => {
+ test('a remote caller never infers a private page', async () => {
+ const r = await inferFactSubject(engine, 'default', { fact: 'Dana Private-Example is relocating', mode: 'write', excludePrivate: true });
+ expect(r.slug).toBeNull();
+ const p = await inferFactSubject(engine, 'default', { fact: 'is relocating', pageSlug: 'people/dana-private-example', mode: 'write', excludePrivate: true });
+ expect(p.slug).toBeNull();
+ });
+
+ test('an unreadable namesake does not change the remote outcome', async () => {
+ await page('companies/charlie-example', 'Charlie Example', 'company', 'visibility: private\n');
+ try {
+ const remote = await inferFactSubject(engine, 'default', { fact: 'Charlie Example wants weekly check-ins', mode: 'write', excludePrivate: true });
+ expect(remote).toEqual({ slug: 'people/charlie-example', via: 'mention' });
+ const local = await inferFactSubject(engine, 'default', { fact: 'Charlie Example wants weekly check-ins', mode: 'write' });
+ expect(local).toEqual({ slug: null, reason: 'ambiguous' });
+ } finally {
+ await engine.executeRaw(`DELETE FROM pages WHERE slug = 'companies/charlie-example'`);
+ }
+ });
+
+ test('lookups are source-scoped', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('other', 'other') ON CONFLICT DO NOTHING`);
+ const r = await inferFactSubject(engine, 'other', { fact: 'Acme Example raised a seed round', mode: 'write' });
+ expect(r.slug).toBeNull();
+ });
+});
+
+describe('context helpers and kill switch', () => {
+ test('appendContextNote and contextHead round-trip', () => {
+ expect(appendContextNote(null, 'entity inferred from mention')).toBe('entity inferred from mention');
+ const c = appendContextNote('companies/acme-example', 'entity inferred from page');
+ expect(c).toBe('companies/acme-example — entity inferred from page');
+ expect(contextHead(c)).toBe('companies/acme-example');
+ });
+
+ test('recordedPageSlug accepts page-extraction rows only', () => {
+ expect(recordedPageSlug('companies/acme-example — entity matched by bare name only', 'mcp:put_page')).toBe('companies/acme-example');
+ expect(recordedPageSlug('companies/acme-example', 'chat 2026-06-12')).toBeNull();
+ expect(recordedPageSlug('chat', 'mcp:put_page')).toBeNull();
+ });
+
+ test('facts.entity_inference off disables write-time inference', async () => {
+ expect(await isEntityInferenceEnabled(engine)).toBe(true);
+ await engine.setConfig('facts.entity_inference', 'off');
+ expect(await isEntityInferenceEnabled(engine)).toBe(false);
+ await engine.setConfig('facts.entity_inference', 'on');
+ });
+});