Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): Unicode literal slugs never bind an ASCII prefix (#6620)
time-attack05bf4807eefa
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 47292c3507..5bfd59e1c6 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -85,7 +85,7 @@ rejection of serve-only flags before a brain opens.- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug (slug-shaped input via `looksLikeSlug`: lowercase Unicode letters and numbers plus `/`, `_`, `-`, so non-Latin slugs match exactly) → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC` (non-ranking link types never count). Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard). When a name resolves to two or three pages that form one identity-sibling group (`mentions/siblings.ts` `siblingCanonical`), the alias and basename arms of `resolveEntitySlugWithSource` and `resolveStrictEntityReference` return the group's lowest slug instead of an ambiguity or a fallback slug; `resolveStrictEntityReference` also accepts the source pack's linkable entity types (accounts, CRM records) as fact entities.-- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text, resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).+- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text (lowercase Unicode page-slug letters without combining marks; a literal glued to further letters is not a literal), resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).- `src/core/facts/drain.ts` + `drain-scheduler.ts` + `src/core/cycle/facts-drain.ts` + `src/commands/doctor/checks/facts-drain.ts` — the automatic facts drain on PGLite (no job worker there). `runFactsDrain(engine, { owner, signal, wallClockMs })` runs queued `facts-absorb` jobs one at a time through the real handler (`withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)`), with `authorizeJobExecution`/`withSubmissionAuthority`, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one `BudgetTracker` (`facts:drain`) capped at min(`facts.drain_budget_usd` 1.00, the rest of `facts.drain_daily_budget_usd` 5.00 over a rolling 24 h); `capSource` is `user` once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the `gbrain pricing set` fix under a user cap. Before each claim the job's worst case (8,000-char turn + `facts.extraction_max_tokens`) must fit; `facts.drain_max_jobs` (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (`queue.deferJob`): `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config `facts.drain_state`; `readFactsDrainStatus` feeds doctor `facts_drain` and the readiness capability `facts_drain`. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a `facts_drain_first_run` notice; deferrals raise one `facts_drain_deferred` notice per reason per process (`takeFactsDrainNotice`, taken by stdio `dispatch.ts`). Never writes stdout. `startFactsDrainScheduler` owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (`canRun`), the timer callback returns the tick's promise (a test awaits it), and `stop()` aborts and waits up to 5 s. Owners: stdio `serve` (`installFactsDrain`, stdin-data activity, delegated-sync veto, stopped first in the shutdown chain), `serve --http` (every tick; stopped before engine disconnect) and the cycle phase `facts_drain` (PGLite only; Postgres skips `not_applicable`). Opt-out: `facts.extraction_enabled false`. Tests: `test/facts-drain.test.ts`, `test/facts-drain-scheduler.test.ts`, `test/facts-absorb-keyless-deferral.test.ts`, the `facts_drain` row of `test/managed-phase-matrix.test.ts`.- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes drop at the embedding model's calibrated threshold (`supersession-threshold.ts`; none for an uncalibrated model); capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `wouldDedupSamePage(ctx, existing, score, claim)` (#6333, shadow only, wave 15 [UC2]) is the explicit-lane same-page rewording rule the backstop measures but never acts on: the nearest candidate shares the lane, `source_session` and visibility, sits at or above `SAME_PAGE_REWORDING_THRESHOLD` (0.85) and does not `claimsDiverge`; the backstop counts it as `would_dedup_same_page` on its result, logs the matched id, cosine and session on stderr, and inserts the fact as before. Its measured false positives (Lisbon→Porto, approved→rejected, email→phone are all counted) are pinned in `test/backstop-same-page-shadow-6333.test.ts` and are why no drop path ships. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).diff --git a/src/core/facts/subject-infer.ts b/src/core/facts/subject-infer.tsindex b4a5b8c37b..02d323f069 100644--- a/src/core/facts/subject-infer.ts+++ b/src/core/facts/subject-infer.ts@@ -107,8 +107,16 @@ const SENTENCE_OPENERS = new Set(['favorite', 'favourite', 'birthday', 'anniversary', 'allergic', 'vegetarian', 'vegan', 'lives', 'lived', 'works', 'worked',]);-/** 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;+/**+ * 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+ * marks are not among them, so a marked literal is never a literal). A literal glued to further+ * letters or marks on either side is not a literal, so "people/alice-example未知" never resolves to+ * its ASCII prefix.+ */+const SLUG_SEG = '[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}][\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}_-]*';+const SLUG_EDGE = '[\\p{L}\\p{M}\\p{N}_/-]';+const SLUG_IN_TEXT_RE = new RegExp(`(?<!${SLUG_EDGE})${SLUG_SEG}(?:/${SLUG_SEG})+(?!${SLUG_EDGE})`, 'gu');/** Two distinct entities already make the subject unknown; more resolution is wasted work. */const DISTINCT_ENTITY_LIMIT = 2;diff --git a/test/facts-subject-infer.test.ts b/test/facts-subject-infer.test.tsindex 06928e09df..c67e4b50d1 100644--- a/test/facts-subject-infer.test.ts+++ b/test/facts-subject-infer.test.ts@@ -31,6 +31,13 @@ beforeAll(async () => {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');+ await page('people/literal-example', 'Literal Example', 'person');+ await page('people/例子', 'Literal Unicode Example', 'person');+ await page('people/日本語例', 'Japanese Literal Example', 'person');+ await page('people/किरण', 'Marked Literal Example', 'person');+ await page('人物/例子', 'Unicode Directory Example', 'person');+ await page('people/mixed例子-7', 'Mixed Script Example', 'person');+ await page('people/私的例子', 'Private Unicode Example', 'person', 'visibility: private\n');});afterAll(async () => {@@ -163,6 +170,65 @@ describe('inferFactSubject reasons', () => {});});+describe('literal Unicode subject slugs (#6620)', () => {+ for (const mode of ['write', 'relink'] as const) {+ test(`${mode}: resolves complete Unicode paths at punctuation boundaries`, async () => {+ for (const slug of ['people/例子', 'people/日本語例', '人物/例子', 'people/mixed例子-7']) {+ expect(await inferFactSubject(engine, 'default', { fact: `「${slug}」 owns the checklist`, mode }))+ .toEqual({ slug, via: 'mention' });+ }+ expect(await inferFactSubject(engine, 'default', { fact: 'checklist owner is people/例子. weekly updates follow.', mode }))+ .toEqual({ slug: 'people/例子', via: 'mention' });+ for (const slug of ['people/charlie-example', 'people/例子']) {+ for (const fact of [`${slug}: owns the launch`, `${slug}:`]) {+ expect(await inferFactSubject(engine, 'default', { fact, mode }))+ .toEqual({ slug, via: 'mention' });+ }+ }+ });++ test(`${mode}: never resolves an unknown Unicode extension to its ASCII prefix`, async () => {+ expect(await inferFactSubject(engine, 'default', { fact: 'people/literal-example未知 owns the checklist', mode }))+ .toMatchObject({ slug: null });+ expect(await inferFactSubject(engine, 'default', { fact: '人物people/literal-example owns the checklist', mode }))+ .toMatchObject({ slug: null });+ expect(await inferFactSubject(engine, 'default', { fact: 'people/例子未知 owns the checklist', mode }))+ .toMatchObject({ slug: null });+ });++ test(`${mode}: unsupported marked literals preserve trusted page attribution`, async () => {+ expect(await inferFactSubject(engine, 'default', { fact: 'people/किरण owns the checklist', pageSlug: 'people/किरण', mode }))+ .toEqual({ slug: 'people/किरण', via: 'page' });+ });++ test(`${mode}: an ASCII literal followed by a file suffix still names its page`, async () => {+ expect(await inferFactSubject(engine, 'default', { fact: 'people/charlie-example.md owns the launch checklist', mode }))+ .toEqual({ slug: 'people/charlie-example', via: 'mention' });+ });++ test(`${mode}: Unicode literals preserve competing-subject vetoes`, async () => {+ for (const fact of [+ 'people/例子 and people/literal-example own the checklist',+ 'people/例子 and people/literal-example未知 own the checklist',+ ]) expect(await inferFactSubject(engine, 'default', { fact, mode }))+ .toMatchObject({ slug: null, reason: 'ambiguous' });+ });++ test(`${mode}: Unicode literals preserve source and private visibility`, async () => {+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('unicode-other', 'unicode-other') ON CONFLICT DO NOTHING`);+ expect((await inferFactSubject(engine, 'unicode-other', { fact: 'people/例子 owns the checklist', mode })).slug).toBeNull();+ expect(await inferFactSubject(engine, 'default', { fact: 'people/私的例子 owns the checklist', mode }))+ .toEqual({ slug: 'people/私的例子', via: 'mention' });+ expect((await inferFactSubject(engine, 'default', { fact: 'people/私的例子 owns the checklist', mode, excludePrivate: true })).slug)+ .toBeNull();+ });+ }++ test('does not promote natural-language weak CJK names', async () => {+ expect((await inferFactSubject(engine, 'default', { fact: '例子负责项目。', mode: 'write' })).slug).toBeNull();+ });+});+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 });