Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): currency amounts and label openers no longer veto a clear subject; an entity named only as an example is not the subject (#7405)

garrytan0acd3bc8173f
diff --git a/src/core/facts/subject-infer.ts b/src/core/facts/subject-infer.ts
index 02d323f069..0bf1b445d7 100644
--- a/src/core/facts/subject-infer.ts
+++ b/src/core/facts/subject-infer.ts
@@ -105,8 +105,12 @@ const SENTENCE_OPENERS = new Set([
'not', 'no', 'yes', 'after', 'before', 'during', 'since', 'until', 'while', 'per', 'via', 're', 'fyi', 'update', 'updated',
'lunch', 'dinner', 'breakfast', 'coffee', 'drinks', 'call', 'sync', 'standup', 'interview', 'demo', 'pitch', 'board',
'favorite', 'favourite', 'birthday', 'anniversary', 'allergic', 'vegetarian', 'vegan', 'lives', 'lived', 'works', 'worked',
+ 'work', 'invoice', 'invoiced', 'billed', 'receipt', 'payment',
]);
+/** #7405: ISO 4217 codes; one counts as a unit (not a name) only where every use sits next to an amount ("CHF 80", "80 CHF"). */
+const CURRENCY_CODES = new Set(Intl.supportedValuesOf('currency'));
+
/**
* Slugs written verbatim in the fact text ("people/alice-example owns the checklist", "people/例子").
* Segments use the lowercase page-slug letters the strict resolver's exact arm accepts (combining
@@ -127,6 +131,7 @@ export async function inferFactSubject(engine: BrainEngine, sourceId: string, in
...extractCandidates(input.fact).filter(c => !c.weak).map(shedOpener),
];
const resolved = new Set<string>();
+ const subjects = new Set<string>();
const misses: Array<Exclude<StrictResolution, { slug: string }>['miss']> = [];
let vetoed = false;
const memo = new Map<string, StrictResolution>();
@@ -140,15 +145,18 @@ export async function inferFactSubject(engine: BrainEngine, sourceId: string, in
}
if (r.slug !== null) {
resolved.add(r.slug);
+ if (!onlyExampleUses(input.fact, candidate.query)) subjects.add(r.slug);
if (resolved.size >= DISTINCT_ENTITY_LIMIT) return { slug: null, reason: 'ambiguous', resolved: [...resolved] };
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.
+ // capitalized sentence opener ("Met", "Raised") or a currency code next to
+ // an amount with no page is no name evidence; anything else unresolved is
+ // a real competing reference.
if (r.miss === 'not_entity') continue;
- if (r.miss === 'no_page' && (isNonName(candidate.query) || (candidate.sentenceStart && SENTENCE_OPENERS.has(candidate.query.toLowerCase())))) continue;
+ if (r.miss === 'no_page' && (isNonName(candidate.query) || isAmountUnit(input.fact, candidate.query)
+ || (candidate.sentenceStart && SENTENCE_OPENERS.has(candidate.query.toLowerCase())))) continue;
vetoed = true;
}
@@ -157,7 +165,7 @@ export async function inferFactSubject(engine: BrainEngine, sourceId: string, in
if (vetoed || (resolved.size === 1 && !resolved.has(page))) return { slug: null, reason: 'ambiguous', resolved: [...resolved] };
return { slug: page, via: 'page' };
}
- if (resolved.size === 1 && !vetoed) return { slug: [...resolved][0]!, via: 'mention' };
+ if (subjects.size === 1 && !vetoed) return { slug: [...subjects][0]!, via: 'mention' };
const miss = (reason: InferMissReason): InferResult => ({ slug: null, reason, resolved: [...resolved] });
if (resolved.size > 0 || misses.includes('ambiguous')) return miss('ambiguous');
if (misses.includes('unverified')) return miss('unverified_match');
@@ -176,6 +184,27 @@ function isNonName(query: string): boolean {
return isCommonCapitalizedWord(query) || ROLE_AND_TERM_TOKENS.has(query.toLowerCase());
}
+/** Every whole-word use of `query` in the fact, case-insensitive. */
+function referenceUses(fact: string, query: string): RegExpMatchArray[] {
+ const literal = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return [...fact.matchAll(new RegExp(`(?<![\\p{L}\\p{N}_/-])${literal}(?![\\p{L}\\p{N}_/-])`, 'giu'))];
+}
+
+/** #7405: a currency code is a unit only when every use is next to an amount; resolution runs first, so a page named CHF still competes. */
+function isAmountUnit(fact: string, query: string): boolean {
+ if (!CURRENCY_CODES.has(query)) return false;
+ const uses = referenceUses(fact, query);
+ return uses.length > 0 && uses.every(m =>
+ /^\s*\d/u.test(fact.slice(m.index! + m[0].length)) || /\d\s*$/u.test(fact.slice(0, m.index)));
+}
+
+/** #7405: an entity named only as an example ("... including Automation Example notes") resolves, but cannot be the subject. */
+function onlyExampleUses(fact: string, query: string): boolean {
+ const uses = referenceUses(fact, query);
+ return uses.length > 0 && uses.every(m =>
+ /\b(?:including|such as|for example|for instance|e\.g\.)\s+[^.!?;]*$/iu.test(fact.slice(0, m.index)));
+}
+
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 }>(
diff --git a/test/facts-subject-infer-7405.test.ts b/test/facts-subject-infer-7405.test.ts
new file mode 100644
index 0000000000..da5c041ee1
--- /dev/null
+++ b/test/facts-subject-infer-7405.test.ts
@@ -0,0 +1,100 @@
+/**
+ * #7405: fact subject inference. A clear single-person fact was rejected as
+ * ambiguous when it carried a currency amount ("CHF 80") or opened with a
+ * label word ("Invoice total ...", "Work session ..."), and an entity named
+ * only as an example inside an inventory ("... including Automation Example
+ * notes") was linked as the subject. Those unresolved non-names must not
+ * compete, an example must not establish the subject, and a real entity whose
+ * name is a currency code or label word still competes. The two-entity and
+ * unknown-issuer controls stay unresolved. Synthetic data only; PGLite always,
+ * Postgres when DATABASE_URL is set (testBackends).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { inferFactSubject } from '../src/core/facts/subject-infer.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: Array<{ backend: string; engine: BrainEngine }> = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+const page = (engine: BrainEngine, slug: string, title: string, type: string, sourceId = 'default') =>
+ importFromContent(engine, slug, `---\ntitle: ${title}\ntype: ${type}\nfacts_backstop: false\n---\n\n# ${title}\n`, { noEmbed: true, sourceId });
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema();
+ engines.push({ backend: 'pglite', engine });
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push({ backend: 'postgres', engine: pg.engine }); closePostgres = pg.close;
+ }
+ for (const { engine } of engines) {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('source-a', 'source-a') ON CONFLICT DO NOTHING`);
+ for (const sourceId of ['default', 'source-a']) {
+ await page(engine, 'people/alice-example', 'Alice Example', 'person', sourceId);
+ await page(engine, 'companies/acme-example', 'Acme Example', 'company', sourceId);
+ await page(engine, 'ideas/automation-example', 'Automation Example', 'concept', sourceId);
+ }
+ // source-a also holds real entities named like a currency code and two label words.
+ for (const title of ['CHF', 'Invoice', 'Work']) await page(engine, `companies/${title.toLowerCase()}`, title, 'company', 'source-a');
+ }
+}, 120_000);
+
+afterAll(async () => {
+ for (const { engine } of engines) await engine.disconnect();
+ await closePostgres?.();
+});
+
+const ALICE = 'people/alice-example';
+const CASES: Array<{ id: string; fact: string; expect: string | null }> = [
+ { id: 'identity-control', fact: 'Alice Example prefers async updates', expect: ALICE },
+ { id: 'currency', fact: 'Alice Example paid CHF 80 for gardening', expect: ALICE },
+ { id: 'invoice-label', fact: 'Invoice total for gardening work billed to Alice Example: CHF 80', expect: ALICE },
+ { id: 'work-label', fact: 'Work session on 2025-01-01: 2 hours of garden labour for Alice Example (CHF 80)', expect: ALICE },
+ { id: 'amount-first', fact: 'Alice Example was billed 80 CHF for gardening', expect: ALICE },
+ { id: 'two-real-entities', fact: 'Acme Example issued an invoice to Alice Example', expect: null },
+ { id: 'unknown-issuer', fact: 'Northstar Example issued an invoice to Alice Example', expect: null },
+ { id: 'incidental-example', fact: 'Has a venture research folder with 17 enrolled documents including Automation Example notes', expect: null },
+ { id: 'such-as-example', fact: 'Has research notes on concepts such as Automation Example', expect: null },
+ { id: 'example-literal', fact: 'Has research notes including ideas/automation-example', expect: null },
+ { id: 'currency-without-amount', fact: 'CHF billed Alice Example CHF 80', expect: null },
+ { id: 'label-mid-sentence', fact: 'Alice Example joined Work Example last year', expect: null },
+ { id: 'subject-also-named-as-example', fact: 'ideas/automation-example lists 17 documents including ideas/automation-example notes', expect: 'ideas/automation-example' },
+];
+
+describe('#7405 fact subject inference: currency amounts, label openers and incidental examples', () => {
+ for (const backend of backends) {
+ const engineFor = () => engines.find(e => e.backend === backend)!.engine;
+ for (const mode of ['relink', 'write'] as const) {
+ for (const c of CASES) {
+ test(`[${backend}] ${mode}: ${c.id}`, async () => {
+ const result = await inferFactSubject(engineFor(), 'default', { fact: c.fact, mode });
+ expect(result.slug).toBe(c.expect);
+ });
+ }
+
+ test(`[${backend}] ${mode}: an incidental example from another page never matches the page`, async () => {
+ expect(await inferFactSubject(engineFor(), 'default', {
+ fact: 'Has 17 documents including Automation Example notes', pageSlug: 'companies/acme-example', mode,
+ })).toMatchObject({ slug: null, reason: 'ambiguous' });
+ });
+
+ test(`[${backend}] ${mode}: real entities named CHF, Invoice or Work still compete`, async () => {
+ for (const fact of [
+ 'Alice Example paid CHF 80 for gardening',
+ 'Invoice total for gardening work billed to Alice Example: 80',
+ 'Work session on 2025-01-01: 2 hours of garden labour for Alice Example',
+ ]) {
+ expect(await inferFactSubject(engineFor(), 'source-a', { fact, mode })).toMatchObject({ slug: null, reason: 'ambiguous' });
+ }
+ expect((await inferFactSubject(engineFor(), 'source-a', { fact: 'Alice Example prefers async updates', mode })).slug).toBe(ALICE);
+ });
+ }
+ }
+});