Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(entities): non-Latin names mint the sync slug, never an empty one (#6691)
time-attack130f61842dfd
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 1bdbcfb816..4e97ccc75d 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -83,7 +83,7 @@ rejection of serve-only flags before a brain opens.- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).-- `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/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 holding fallback, per path segment: ASCII `slugify` for Latin names (`o-brien`, `soren`), the page-slug grammar sync mints (`slugifySegment`) for a segment whose letters `slugify` would delete (`Мария` → `мария`), and null when no letter or number is left, so a non-Latin name never resolves to `''` (an empty `entitySlug` matches nothing in `listFactsSince`). 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).diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.tsindex 0b92fcf833..8a53b1db1d 100644--- a/src/core/engine-sql/facts.ts+++ b/src/core/engine-sql/facts.ts@@ -430,7 +430,7 @@ export async function listFactsSince(SELECT *${opts?.fingerprint ? sqlFragment`, gbrain_fact_fingerprint(fact) AS fact_fingerprint` : sqlFragment``} FROM factsWHERE source_id = ${source_id}AND ${eventTime ? sqlFragment`COALESCE(valid_from, created_at)` : sqlFragment`created_at`} >= ${since}- ${entitySlug ? sqlFragment`AND entity_slug = ${entitySlug}` : sqlFragment``}+ ${entitySlug != null ? sqlFragment`AND entity_slug = ${entitySlug}` : sqlFragment``}${sessionId ? sqlFragment`AND source_session = ${sessionId}` : sqlFragment``}${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}${unconsolidatedOnly ? sqlFragment`AND consolidated_at IS NULL` : sqlFragment``}diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.tsindex c03aa92fc0..44d70bbb8c 100644--- a/src/core/entities/resolve.ts+++ b/src/core/entities/resolve.ts@@ -24,6 +24,7 @@import type { BrainEngine } from '../engine.ts';import { normalizeAlias } from '../search/alias-normalize.ts';import { foldNonDecomposingLatin } from '../latin-fold.ts';+import { slugifySegment } from '../sync.ts';/** Lazy: the mentions graph stays out of the OpenClaw plugin's static import graph. */const siblingCanonical: typeof import('../mentions/siblings.ts').siblingCanonical = async (...args) =>@@ -48,8 +49,9 @@ import { rankingLinkSql } from '../link-ranking-policy.ts';* hyphen-collapse. NOT prefixed with a directory — caller decides* whether to prefix `people/`, `companies/`, etc.*- * Returns null when raw is empty or whitespace-only. Non-empty input always- * produces a non-null slug — the fallback path is the floor.+ * Returns null when raw is empty, whitespace-only, or holds no letter or+ * number (the fallback would mint an empty slug). Any other input produces a+ * non-null slug: the fallback path is the floor.*/export async function resolveEntitySlug(engine: BrainEngine,@@ -111,13 +113,20 @@ export async function resolveEntitySlug(* corrupts a well-formed slug (`people/alice-example` → `people-alice-example`)* into one no page can ever have — and the flattened slug never resolves, so* every re-extraction re-mints it. Path-shaped input is slugified PER SEGMENT- * (identity for already-well-formed slugs); display names keep plain slugify.+ * (identity for already-well-formed slugs).+ *+ * #6691: a segment whose letters the ASCII slugify would delete (Cyrillic,+ * CJK, any non-Latin script) takes the page-slug grammar sync mints+ * (`slugifySegment`), so `Мария` lands on `мария`, not `''`. Latin names keep+ * the ASCII form (`o-brien`, `soren`). Null when nothing is left.*/-function fallbackSlugify(trimmed: string): string {- if (trimmed.includes('/')) {- return trimmed.split('/').map(slugify).filter(Boolean).join('/');- }- return slugify(trimmed);+function fallbackSlugify(trimmed: string): string | null {+ const slug = trimmed.split('/').map(fallbackSegment).filter(Boolean).join('/');+ return slug || null;+}++function fallbackSegment(segment: string): string {+ return /[\p{L}\p{N}]/u.test(foldForSlug(segment).replace(/[a-z0-9]/g, '')) ? slugifySegment(segment) : slugify(segment);}const IDENTITY_TYPES = new Set(['person', 'company', 'fund', 'organization']);@@ -284,7 +293,7 @@ export async function resolveEntitySlugWithSource(if (basenames.length > 1) {const sibling = await siblingCanonical(engine, source_id, basenames.map(b => b.slug));- return sibling ? { slug: sibling, source: 'fuzzy_match' } : { slug: fallbackSlugify(trimmed), source: 'fallback_slugify' };+ return sibling ? { slug: sibling, source: 'fuzzy_match' } : fallbackResult(trimmed);}if (isBareName(trimmed)) {@@ -295,7 +304,12 @@ export async function resolveEntitySlugWithSource(if (fuzzy) return { slug: fuzzy, source: 'fuzzy_match' };}- return { slug: fallbackSlugify(trimmed), source: 'fallback_slugify' };+ return fallbackResult(trimmed);+}++function fallbackResult(trimmed: string): ResolveResult | null {+ const slug = fallbackSlugify(trimmed);+ return slug ? { slug, source: 'fallback_slugify' } : null;}/**@@ -728,17 +742,15 @@ export function slugify(raw: string): string {// and the sweep below would DELETE them: "Đăng Example" slugged to// "ang-example". Fold after the strip so composed forms reduce in one pass// ("ǿ" → "ø" → "o").- const folded = foldNonDecomposingLatin(- raw- .toLowerCase()- .normalize('NFKD')- // NFKD decomposes accents into combining marks (U+0300..U+036F);- // strip them before replacing the rest with hyphens so "è" → "e",- // not "e" + "-".- .replace(/[̀-ͯ]/g, ''),- );- return folded+ return foldForSlug(raw).replace(/[^a-z0-9]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '');}++/** Lowercase, accent marks stripped, stroke letters folded: what `slugify` keeps `[a-z0-9]` from. */+function foldForSlug(raw: string): string {+ // NFKD decomposes accents into combining marks (U+0300..U+036F); strip them+ // before replacing the rest with hyphens so "è" → "e", not "e" + "-".+ return foldNonDecomposingLatin(raw.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, ''));+}diff --git a/test/entity-resolve.test.ts b/test/entity-resolve.test.tsindex 6cf1f63b33..91196248cd 100644--- a/test/entity-resolve.test.ts+++ b/test/entity-resolve.test.ts@@ -515,3 +515,46 @@ describe('Unicode slug shape (#5421)', () => {.toEqual({ slug: 'people/다른-예시', source: 'exact_page' });});});++describe('non-Latin fallback slugs (#6691)', () => {+ let e: PGLiteEngine;+ beforeAll(async () => {+ e = new PGLiteEngine();+ await e.connect({ database_url: '' });+ await e.initSchema();+ });+ afterAll(async () => { await e.disconnect(); });+ const resolve = (raw: string) => resolveEntitySlug(e as unknown as BrainEngine, 'default', raw);++ it('a non-Latin name with no page mints the slug sync would mint, never an empty slug', async () => {+ expect(await resolve('Мария')).toBe('мария');+ expect(await resolve('Иван Петров')).toBe('иван-петров');+ expect(await resolve('席位')).toBe('席位');+ expect(await resolveEntitySlugWithSource(e as unknown as BrainEngine, 'default', 'Мария'))+ .toEqual({ slug: 'мария', source: 'fallback_slugify' });+ });++ it('a path-shaped non-Latin ref keeps every segment', async () => {+ expect(await resolve('people/Мария Example')).toBe('people/мария-example');+ });++ it('input with no letters or numbers resolves to null instead of an empty slug', async () => {+ expect(await resolve('!!!')).toBeNull();+ expect(await resolveEntitySlugWithSource(e as unknown as BrainEngine, 'default', '—')).toBeNull();+ });++ it('Latin names keep their ASCII fallback slugs', async () => {+ expect(await resolve("O'Brien Example")).toBe('o-brien-example');+ expect(await resolve('AT&T')).toBe('at-t');+ expect(await resolve('Søren Example')).toBe('soren-example');+ expect(await resolve('Đăng Example')).toBe('dang-example');+ expect(await resolve('José García')).toBe('jose-garcia');+ });++ it('an empty entity slug filters listFactsSince to nothing, never to every entity', async () => {+ await e.insertFact({ fact: 'Alice ships weekly', entity_slug: 'people/alice-example', source: 'test', visibility: 'world' }, { source_id: 'default' });+ const since = new Date(Date.now() - 60_000);+ expect((await e.listFactsSince('default', since, { entitySlug: 'people/alice-example' })).length).toBe(1);+ expect(await e.listFactsSince('default', since, { entitySlug: '' })).toEqual([]);+ });+});