Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(mentions): reject Katakana names inside longer Katakana words (#6843)

time-attack706db82571e7
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index 4d2ca4ed88..871f24f971 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -5,7 +5,7 @@ subject, frontmatter alias or declared code) to that entity page, keeps the
links current from `gbrain extract --stale`, and serves them on the `entity`
card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
-- `src/core/by-mention.ts` — the pure mention matcher plus its gazetteer. `buildGazetteer(engine, opts)` loads linkable entity titles and aliases per source (drops below-minimum, generic, ambiguous-first-word and colliding names (a name claimed at one origin by an identity-sibling group stays, marked `shared`), reported as `DroppedName`), keyed by lowercase first token and sorted longest-first. `findMentionedEntities(text, gazetteer, opts)` masks code and HTML comments (the `<!--- gbrain:... -->` fence markers included) with `stripCodeBlocks`, offsets preserved, then picks the longest matching entry at each token (maximal munch), first mention per target only (a `shared` match links every sibling with those tokens, unless the scanning page is one of them), skipping self-links and other sources unless `allowCrossSource` (an own-source twin wins, except that a connector contact stub, `connector_stub` from `google_contact_id` frontmatter, yields under `allowCrossSource` to the one canonical same-name page in another source or the one sharing its slug; #6158). Word-run scripts match whole tokens; Han and Kana match character substrings. A Hangul name must start a word, keep its written spacing, and end at a non-Hangul character or an attached title/particle/copula suffix (`HANGUL_NAME_SUFFIX_RE`), so 지원에게 matches and 지원하는 does not ([measurement](../../designs/hangul-mention-boundaries.md)). A matcher change bumps `MENTION_EXTRACTOR_VERSION` (`mentions/pass.ts`, every page rescans once) and the semantics tag inside `hashGazetteer` (the `extract links --by-mention` resume checkpoint). `scanStaleMentions` is the read-only doctor scan for mention rows the current gazetteer no longer produces.
+- `src/core/by-mention.ts` — the pure mention matcher plus its gazetteer. `buildGazetteer(engine, opts)` loads linkable entity titles and aliases per source (drops below-minimum, generic, ambiguous-first-word and colliding names (a name claimed at one origin by an identity-sibling group stays, marked `shared`), reported as `DroppedName`), keyed by lowercase first token and sorted longest-first. `findMentionedEntities(text, gazetteer, opts)` masks code and HTML comments (the `<!--- gbrain:... -->` fence markers included) with `stripCodeBlocks`, offsets preserved, then picks the longest matching entry at each token (maximal munch), first mention per target only (a `shared` match links every sibling with those tokens, unless the scanning page is one of them), skipping self-links and other sources unless `allowCrossSource` (an own-source twin wins, except that a connector contact stub, `connector_stub` from `google_contact_id` frontmatter, yields under `allowCrossSource` to the one canonical same-name page in another source or the one sharing its slug; #6158). Word-run scripts match whole tokens; Han and Kana match character substrings. A Hangul name must start a word, keep its written spacing, and end at a non-Hangul character or an attached title/particle/copula suffix (`HANGUL_NAME_SUFFIX_RE`), so 지원에게 matches and 지원하는 does not ([measurement](../../designs/hangul-mention-boundaries.md)). A name written only in Katakana (ー included) must be a whole contiguous Katakana run (`hasKatakanaMatchBoundary`): Katakana, small and supplementary kana, ー and voicing marks continue it, Hiragana, Han, Latin, punctuation and ・ end it, so デン matches 喫茶デン and デン・カフェ but not インシデント. A matcher change bumps `MENTION_EXTRACTOR_VERSION` (`mentions/pass.ts`, every page rescans once) and the semantics tag inside `hashGazetteer` (the `extract links --by-mention` resume checkpoint). `scanStaleMentions` is the read-only doctor scan for mention rows the current gazetteer no longer produces.
- `src/core/mentions/policy.ts` — the one linkable-type resolver. `linkableTypesFor(pack, policy)`: `person`, `company`, `organization`, `entity` (`ALWAYS_LINKABLE_TYPES`, never removable) plus every pack type with `primitive: entity` and its type aliases (`product` excluded), adjusted by `mentions.entity_types` (`+type`/`type` adds, `-type` removes). `readMentionPolicy` reads `auto_link`, `mentions.auto_link`, `mentions.entity_types`, `mentions.ignore`, `mentions.exclude_slugs` (#5829: listed pages get no gazetteer entry by title or alias, dropped as `excluded_slug`; JSON array or comma list, `parseNameList`), `mentions.alias_deny`, `mentions.multiword_aliases` and `mentions.sibling_merge` (both default on): from the request's config snapshot when one is open (`config-snapshot.ts`), else in one keyed config read. `canonicalTypeOf` / `typeAliasPairs` map a stored type through the pack's type aliases (`untyped` for none); pairs are bound as two `text[]`. `loadSourcePack(engine, sourceId, {strict})` returns null on a resolution failure unless strict. Tests: `test/mentions-policy-aliases.test.ts`.
- `src/core/mentions/siblings.ts` — identity siblings: pages in one source naming the same normalized title subject under pairwise different prefixes, all linkable entities of one canonical type other than `person`, none excluded or `identity: separate`, at most `SIBLING_GROUP_CAP` (3; a larger group is `capped`). `siblingVerdict` is the one rule (card, search fan-out, gazetteer); `readIdentitySiblings` reads a page's group with the private-page predicate for untrusted callers. `siblingCanonical` (the group's lowest slug, for fact attribution by name) and `factEntitySlugs` (the page, its siblings and its bare subject slug, read by the entity card's facts and `recall {entity}`). Nothing is written to `entity_identities`, and aliases and references are never unioned. Tests: `test/mentions-identity-siblings.test.ts`.
- `src/core/mentions/aliases.ts` — derived names of an entity page, implementing `docs/designs/ALIAS_CONVENTIONS.md`. Stored aliases and card identity lines read declarations with `anchored: true` (a cue must attach to the page itself; search's per-result `aliasDeclarations` scan reads them all). `titleSubject` (text after the last `: `), `declarationsIn` (each declaration with its line: prose cues, label and value lines and table rows whose label names an alias field (also a label opening a later sentence of a line, alias noun within its first two words, at most 7 words), the quoted-only "calls it" cue, a quoted defined term right after the page's own name; a capture is a quoted name or a run of up to 4 capitalized or code tokens ending at punctuation, a lowercase word or the line end, rejected on a possessive, a run of only common words or a cue after a relational noun; linear in the line length), `declaredNames` (its post-filtered names, shared with search's `aliasDeclarations`), `deriveEntityAliases(page, {multiword, deny})` (subject `origin='subject'`, declarations `origin='declared'` with their lines, read from `publicBody`: private takes and facts fences stripped; a single-token declaration is `case_sensitive`; `mentions.alias_deny` and frontmatter `alias_deny` reject as `denied`). `aliasRejection`: under 4 characters (unless a short code the page declares for itself: a declaration marked `selfCode`), a generic word, or the first word of the page's own multi-word name. Rejections are returned with their line for explain. Tests: `test/mentions-policy-aliases.test.ts`.
diff --git a/docs/guides/entity-recall.md b/docs/guides/entity-recall.md
index 5c7859ddf0..37ae184815 100644
--- a/docs/guides/entity-recall.md
+++ b/docs/guides/entity-recall.md
@@ -196,8 +196,15 @@ with its reason, and the identity-sibling decision.
| `mentions.sibling_merge` | `true` | `false` stops showing identity siblings and linking a shared name to each sibling; frontmatter `identity: separate` does it for one page. |
| `search.alias_fanout_max` | `4` | Other names search and query also search per call; `0` turns the fan-out off. |
+A name written only in Katakana must stand as a whole Katakana run: デン
+links 「デン」, デンに, 喫茶デン and デン・カフェ, but not インシデント or デンタル.
+Katakana, small kana, ー and voicing marks continue a run; Hiragana, Han,
+Latin, punctuation and ・ end it. A short name inside a real Katakana compound
+is refused too, so add the compound as its own alias when it names the entity.
+
Mention links written inside a longer Hangul word, or across a space, by a
-matcher older than the Hangul boundary rule (#5829) are stale:
+matcher older than the Hangul boundary rule (#5829), and links written inside a
+longer Katakana word by a matcher older than the Katakana rule (#6843), are stale:
`gbrain doctor` counts them in `stale_mentions`, and
`gbrain extract links --by-mention --rebuild --source db` removes them while
keeping real mentions. A name that is also a common word (a person titled
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index cc2f0f5bfc..0039ea3480 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -904,6 +904,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },
{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },
{ since: '0.60.307.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },
+ { since: '0.60.307.0', text: 'A name written only in Katakana (an alias such as デン) no longer links a page that has it inside a longer Katakana word (インシデント, デンタル): the name must stand as a whole Katakana run, so 「デン」, デンに, 喫茶デン and デン・カフェ still link. A short name inside a real Katakana compound is refused too; add the compound as its own alias when it names the entity. Mention links already written that way are counted by `gbrain doctor` (`stale_mentions`) and removed by `gbrain extract links --by-mention --rebuild --source db`.', id: 'katakana_mention_boundaries' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index 2c81bd7461..29647b5ab8 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -125,7 +125,7 @@ export function hashGazetteer(gazetteer: Gazetteer): string {
for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}\0${e.matchText ?? ''}${e.caseTokens ? `\0${e.caseTokens.join(' ')}` : ''}`);
}
// Matching semantics are part of the resume identity, not just DB contents.
- return createHash('sha256').update('html-comments-masked-v4\n').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
+ return createHash('sha256').update('katakana-boundaries-v5\n').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
}
/** One row of the saved entry set the mention pass diffs (mention_gazetteer_entries). */
@@ -716,6 +716,30 @@ function hasHangulMatchBoundary(
return actual === expected && HANGUL_NAME_SUFFIX_RE.test(text.slice(end, end + 12));
}
+/** A name written only in Katakana (ー included) must be a whole Katakana run,
+ * so デン matches 「デン」, デンに, 喫茶デン and デン・カフェ but not インシデント
+ * or デンタル. Katakana (small and supplementary kana included), ー and the
+ * voicing marks continue a run; Hiragana, Han, Latin, punctuation and ・ end it.
+ * This is a script-span rule, not morphology: a short name inside a real
+ * Katakana compound is refused too, and the compound can be its own alias.
+ */
+const KATAKANA_NAME_TOKEN_RE = /^[\p{Script=Katakana}ー]$/u;
+const KATAKANA_RUN_CHARS = '\\p{Script=Katakana}ー\\u3099-\\u309c\\uff70\\uff9e\\uff9f';
+const KATAKANA_RUN_BEFORE_RE = new RegExp(`[${KATAKANA_RUN_CHARS}]$`, 'u');
+const KATAKANA_RUN_AFTER_RE = new RegExp(`^[${KATAKANA_RUN_CHARS}]`, 'u');
+
+function hasKatakanaMatchBoundary(
+ text: string, tokens: ScannedToken[], start: number, entry: GazetteerEntry,
+): boolean {
+ if (!entry.tokens.every(t => KATAKANA_NAME_TOKEN_RE.test(t))) return true;
+ const first = tokens[start]!;
+ const last = tokens[start + entry.tokens.length - 1]!;
+ const end = last.offset + last.length;
+ return text.slice(first.offset, end) === entry.tokens.join('')
+ && !KATAKANA_RUN_BEFORE_RE.test(text.slice(Math.max(0, first.offset - 2), first.offset))
+ && !KATAKANA_RUN_AFTER_RE.test(text.slice(end, end + 2));
+}
+
/**
* Scan body text for mentions of gazetteer entities. Pure function — no
* IO. Returns `Mention[]` ordered by offset, deduped per
@@ -778,6 +802,7 @@ export function findMentionedEntities(
for (const entry of bucket) {
if (i + entry.tokens.length > tokens.length) continue;
if (!hasHangulMatchBoundary(stripped, tokens, i, entry)) continue;
+ if (!hasKatakanaMatchBoundary(stripped, tokens, i, entry)) continue;
if (!caseMatches(entry, i)) continue;
if (entry.tokens.length === 1) {
matched = entry;
@@ -812,7 +837,8 @@ export function findMentionedEntities(
e.tokens.length === want.tokens.length
&& e.tokens.every((t, k) => t === want.tokens[k])
&& caseMatches(e, i)
- && hasHangulMatchBoundary(stripped, tokens, i, e);
+ && hasHangulMatchBoundary(stripped, tokens, i, e)
+ && hasKatakanaMatchBoundary(stripped, tokens, i, e);
if (matched.source_id !== opts.fromSourceId) {
const want = matched;
const own = bucket.find(e => e.source_id === opts.fromSourceId && sameName(e, want));
diff --git a/test/by-mention-katakana.test.ts b/test/by-mention-katakana.test.ts
new file mode 100644
index 0000000000..d0890b01a1
--- /dev/null
+++ b/test/by-mention-katakana.test.ts
@@ -0,0 +1,89 @@
+/**
+ * Protects Katakana names from matching inside a longer Katakana word (#6843):
+ * character-level CJK maximal munch accepted デン in インシデント and stored a
+ * false mention edge. Existing Hangul and Han suites cover other scripts only.
+ * Uses the public matcher and the real mention pass; no production seam.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { findMentionedEntities, hashGazetteer, tokenizeTitle, type Gazetteer, type GazetteerEntry } from '../src/core/by-mention.ts';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runMentionPass } from '../src/core/mentions/pass.ts';
+import { mentionBrain, mentionLinks, page } from './helpers/mention-brain.ts';
+
+const opts = { fromSlug: 'notes/example', fromSourceId: 'default' };
+
+function entryFor(name: string, sourceId = 'default', slug = 'entities/acme-example'): GazetteerEntry {
+ return { slug, source_id: sourceId, title: 'Acme Example', origin: 'frontmatter', matchText: name, tokens: tokenizeTitle(name) };
+}
+
+function gazetteerOf(...entries: GazetteerEntry[]): Gazetteer {
+ return new Map([[entries[0]!.tokens[0]!, entries]]);
+}
+
+const found = (body: string, name = 'デン') => findMentionedEntities(body, gazetteerOf(entryFor(name)), opts);
+
+describe('Katakana mention boundaries (#6843)', () => {
+ test.each(['インシデント対応の手順を確認する。', 'デンタル', 'カデン', 'デンー', 'ーデン', 'デンァ', 'ァデン',
+ 'デン\u3099', 'デン\u309a', '\u{1b164}デン', 'デン\u{1b164}', 'カデン', 'デ ン'])
+ ('rejects a name inside a longer Katakana run: %s', body => {
+ expect(found(body)).toEqual([]);
+ });
+
+ test.each(['デンに行った', '「デン」', '喫茶デン', 'デン・カフェ', '😀デンで会う', 'DENデン', 'デン。'])
+ ('keeps Hiragana, Han, Latin, punctuation and ・ as boundaries: %s', body => {
+ expect(found(body)).toHaveLength(1);
+ });
+
+ test('applies to every pure-Katakana name, with no length cap', () => {
+ expect(found('ハイライトを読む', 'ライト')).toEqual([]);
+ expect(found('ライトに聞く', 'ライト')).toHaveLength(1);
+ expect(found('スーパーマーケットへ', 'マーケット')).toEqual([]);
+ expect(found('「マーケット」へ', 'マーケット')).toHaveLength(1);
+ });
+
+ test('mixed-script and non-Katakana names keep character matching', () => {
+ expect(found('カフェデンに行った', '喫茶デン')).toEqual([]);
+ expect(found('老舗喫茶デンタルに行った', '喫茶デン')).toHaveLength(1);
+ expect(found('我读了艾例丝的书', '艾例丝')).toHaveLength(1);
+ });
+
+ test('a rejected substring leaves the original offset of a later real mention', () => {
+ const body = '😀インシデント対応。その後「デン」に行った';
+ const hits = found(body);
+ expect(hits).toHaveLength(1);
+ expect(hits[0]!.offset).toBe(body.indexOf('デン」'));
+ });
+
+ test('own-source sibling selection applies the same boundary', () => {
+ const foreign = entryFor('デン', 'other', 'entities/acme-example');
+ const own = entryFor('デン', 'default', 'entities/widget-co');
+ const g = gazetteerOf(foreign, own);
+ const cross = { ...opts, allowCrossSource: true };
+ expect(findMentionedEntities('インシデント', g, cross)).toEqual([]);
+ expect(findMentionedEntities('「デン」', g, cross).map(m => m.slug)).toEqual(['entities/widget-co']);
+ });
+
+ test('the resume fingerprint changes with the matcher semantics', () => {
+ const entry = entryFor('デン');
+ const prior = createHash('sha256').update('html-comments-masked-v4\n').update(
+ `${entry.source_id}\0${entry.slug}\0${entry.title}\0${entry.tokens.join(' ')}\0${entry.matchText}`,
+ ).digest('hex').slice(0, 8);
+ expect(hashGazetteer(gazetteerOf(entry))).not.toBe(prior);
+ });
+});
+
+describe('Katakana mention publication (#6843)', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+
+ test('the mention pass stores no edge for a word-internal alias', async () => {
+ await page(engine, 'entities/acme-example', 'entity', 'Acme Example', 'A synthetic entity.', { frontmatter: { aliases: ['デン'] } });
+ await engine.executeRaw("INSERT INTO page_aliases (source_id, slug, alias_norm) VALUES ('default', 'entities/acme-example', 'デン')");
+ await page(engine, 'notes/incident', 'note', 'Incident response', 'インシデント対応の手順を確認する。');
+ await page(engine, 'notes/visit', 'note', 'Visit', '「デン」に行った');
+ expect((await runMentionPass(engine)).state).toBe('complete');
+ expect(await mentionLinks(engine)).toEqual(['notes/visit -> entities/acme-example']);
+ }, 120_000);
+});