Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(mentions): preserve Hangul name boundaries and spacing

Javier Aldape709a07cf45f6
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index 3bb91b543a..558187c62b 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -71,6 +71,8 @@ export interface GazetteerEntry {
title: string;
/** Lowercase title tokens in order. Length 1 = single-word entity. */
tokens: string[];
+ /** Spelling being matched (the alias, not the display title, for aliases). */
+ matchText?: string;
}
/**
@@ -91,9 +93,10 @@ export type Gazetteer = Map<string, GazetteerEntry[]>;
export function hashGazetteer(gazetteer: Gazetteer): string {
const entries: string[] = [];
for (const bucket of gazetteer.values()) {
- for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}`);
+ for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}\0${e.matchText ?? ''}`);
}
- return createHash('sha256').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
+ // Matching semantics are part of the resume identity, not just DB contents.
+ return createHash('sha256').update('hangul-boundaries-v1\n').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
}
export interface Mention {
@@ -374,7 +377,8 @@ export function tokenizeTitle(title: string): string[] {
for (let i = 0; i < title.length;) {
const cp = title.codePointAt(i) ?? 0;
const charLen = cp > 0xffff ? 2 : 1;
- tokens.push(normalizeToken(title.slice(i, i + charLen)));
+ const ch = title.slice(i, i + charLen);
+ if (isCJKChar(ch)) tokens.push(normalizeToken(ch));
i += charLen;
}
return tokens;
@@ -446,6 +450,7 @@ export async function buildGazetteer(
source_id: row.source_id ?? 'default',
title: row.title,
tokens,
+ matchText: row.title,
};
const key = tokens[0]!;
const bucket = gazetteer.get(key);
@@ -508,7 +513,7 @@ export async function buildGazetteer(
const tokens = tokenizeTitle(alias);
if (tokens.length === 0) continue;
if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) continue;
- const entry: GazetteerEntry = { slug: a.slug, source_id: src, title: a.title, tokens };
+ const entry: GazetteerEntry = { slug: a.slug, source_id: src, title: a.title, tokens, matchText: alias };
const key = tokens[0]!;
const bucket = gazetteer.get(key);
if (bucket) bucket.push(entry);
@@ -541,6 +546,23 @@ export async function buildGazetteer(
// Body-text scanner (pure)
// ============================================================
+/** Korean uses word spaces; Han/Kana retain character-substring matching.
+ * Validate each candidate before maximal-munch selection so an invalid longer
+ * phrase does not consume a valid shorter name. Do not require an end boundary:
+ * Korean particles attach directly to names (지원은, 지원에게).
+ */
+function hasHangulMatchBoundary(
+ text: string, tokens: ScannedToken[], start: number, entry: GazetteerEntry,
+): boolean {
+ if (!entry.tokens.every(t => /^[가-힣]+$/u.test(t))) return true;
+ const first = tokens[start]!;
+ if (first.offset > 0 && /[가-힣]/u.test(text[first.offset - 1]!)) return false;
+ const last = tokens[start + entry.tokens.length - 1]!;
+ const actual = text.slice(first.offset, last.offset + last.length).replace(/\s+/gu, ' ');
+ const expected = (entry.matchText ?? entry.tokens.join('')).trim().replace(/\s+/gu, ' ');
+ return actual === expected;
+}
+
/**
* Scan body text for mentions of gazetteer entities. Pure function — no
* IO. Returns `Mention[]` ordered by offset, deduped per
@@ -595,6 +617,8 @@ export function findMentionedEntities(
let matched: GazetteerEntry | null = null;
let matchedTokens = 0;
for (const entry of bucket) {
+ if (i + entry.tokens.length > tokens.length) continue;
+ if (!hasHangulMatchBoundary(stripped, tokens, i, entry)) continue;
if (entry.tokens.length === 1) {
matched = entry;
matchedTokens = 1;
@@ -629,7 +653,8 @@ export function findMentionedEntities(
const own = bucket.find(
e => e.source_id === opts.fromSourceId
&& e.tokens.length === want.length
- && e.tokens.every((t, k) => t === want[k]),
+ && e.tokens.every((t, k) => t === want[k])
+ && hasHangulMatchBoundary(stripped, tokens, i, e),
);
if (own) matched = own;
}
diff --git a/test/by-mention-hangul.test.ts b/test/by-mention-hangul.test.ts
new file mode 100644
index 0000000000..4153bdeefc
--- /dev/null
+++ b/test/by-mention-hangul.test.ts
@@ -0,0 +1,122 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { buildGazetteer, findMentionedEntities, hashGazetteer, tokenizeTitle } from '../src/core/by-mention.ts';
+import type { Gazetteer } from '../src/core/by-mention.ts';
+
+let engine: PGLiteEngine;
+let gazetteer: Gazetteer;
+const opts = { fromSlug: 'notes/example', fromSourceId: 'default' };
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const [slug, title] of [
+ ['people/jiwon', '지원'],
+ ['companies/jangin', '장인'],
+ ['people/inha', '인하'],
+ ['companies/samsung-card', '삼성카드'],
+ ['companies/spaced', '삼성 카드'],
+ ['companies/longer', '지원 회사'],
+ ['companies/alias', 'Example Company'],
+ ['people/naval', '纳瓦尔'],
+ ]) {
+ await engine.putPage(slug!, {
+ type: 'company', title: title!, compiled_truth: '', timeline: '', frontmatter: {},
+ });
+ }
+ await engine.executeRaw(
+ "INSERT INTO page_aliases (source_id, slug, alias_norm) VALUES ('default', 'companies/alias', '아내')",
+ );
+ gazetteer = await buildGazetteer(engine);
+}, 60_000);
+
+afterAll(async () => { await engine.disconnect(); });
+
+function mentions(body: string): string[] {
+ return findMentionedEntities(body, gazetteer, opts).map(m => m.slug);
+}
+
+describe('Hangul mention boundaries', () => {
+ test.each(['재지원 안내', '로그인하기', '국가 성장 인프라로', '찾아내는 방법'])
+ ('rejects word-internal title/alias and cross-space matches: %s', body => {
+ expect(mentions(body)).toEqual([]);
+ });
+
+ test.each(['지 원', '지,원', '지\n원', '지😀원'])
+ ('does not join separated syllables into a contiguous name: %s', body => {
+ expect(mentions(body)).toEqual([]);
+ });
+
+ test.each(['지원이 왔다', '지원은 왔다', '지원에게 물었다', '지원의 문서', '지원과 만났다'])
+ ('keeps attached Korean particles: %s', body => {
+ expect(mentions(body)).toEqual(['people/jiwon']);
+ });
+
+ test('matches an alias using alias spelling, not its canonical Latin title', () => {
+ const body = '😀 아내와 만났다';
+ const found = findMentionedEntities(body, gazetteer, opts);
+ expect(found).toHaveLength(1);
+ expect(found[0]!.slug).toBe('companies/alias');
+ expect(found[0]!.name).toBe('Example Company');
+ expect(body.slice(found[0]!.offset, found[0]!.offset + 2)).toBe('아내');
+ });
+
+ test('preserves spaces explicitly present in a Hangul name', () => {
+ expect(tokenizeTitle('삼성 카드')).toEqual(['삼', '성', '카', '드']);
+ expect(mentions('삼성\t카드에서 일한다')).toEqual(['companies/spaced']);
+ expect(mentions('삼성카드에서 일한다')).toEqual(['companies/samsung-card']);
+ expect(mentions('삼성,카드')).toEqual([]);
+ });
+
+ test('rejecting the longest candidate still allows a valid shorter name', () => {
+ expect(mentions('지원,회사')).toEqual(['people/jiwon']);
+ expect(mentions('지원 회사에서 일한다')).toEqual(['companies/longer']);
+ });
+
+ test('a rejected early occurrence does not hide a later real mention', () => {
+ const body = '재지원 안내 다음에 지원이 왔다';
+ const found = findMentionedEntities(body, gazetteer, opts);
+ expect(found).toHaveLength(1);
+ expect(found[0]!.offset).toBe(body.indexOf('지원이'));
+ });
+
+ test('same-token own-source preference cannot override a spacing mismatch', () => {
+ const entry = gazetteer.get('삼')!.find(e => e.slug === 'companies/spaced')!;
+ const twin: Gazetteer = new Map([['삼', [
+ { ...entry, source_id: 'foreign' },
+ { ...entry, source_id: 'default', matchText: '삼성카드' },
+ ]]]);
+ expect(findMentionedEntities('삼성 카드에서 일한다', twin, {
+ ...opts, allowCrossSource: true,
+ }).map(m => m.source_id)).toEqual(['foreign']);
+ expect(findMentionedEntities('삼성 카드에서 일한다', twin, opts)).toEqual([]);
+ });
+
+ test('resume identity includes spelling and invalidates the old matcher fingerprint', () => {
+ const entry = gazetteer.get('삼')!.find(e => e.slug === 'companies/spaced')!;
+ const spaced: Gazetteer = new Map([['삼', [entry]]]);
+ const unspaced: Gazetteer = new Map([['삼', [{ ...entry, matchText: '삼성카드' }]]]);
+ expect(hashGazetteer(spaced)).not.toBe(hashGazetteer(unspaced));
+ const legacy = createHash('sha256').update(
+ `${entry.source_id}\0${entry.slug}\0${entry.title}\0${entry.tokens.join(' ')}`,
+ ).digest('hex').slice(0, 8);
+ expect(hashGazetteer(spaced)).not.toBe(legacy);
+ expect(hashGazetteer(spaced)).toBe(hashGazetteer(spaced));
+ });
+
+ test('preserves Han substring matching and self/cross-source/code guards', () => {
+ expect(mentions('我读了纳瓦尔的书')).toEqual(['people/naval']);
+ expect(mentions('```\n지원이 왔다\n```')).toEqual([]);
+ expect(findMentionedEntities('지원이 왔다', gazetteer, {
+ fromSlug: 'people/jiwon', fromSourceId: 'default',
+ })).toEqual([]);
+ expect(findMentionedEntities('지원이 왔다', gazetteer, {
+ fromSlug: 'notes/example', fromSourceId: 'other',
+ })).toEqual([]);
+ expect(findMentionedEntities('지원이 왔다', gazetteer, {
+ fromSlug: 'notes/example', fromSourceId: 'other', allowCrossSource: true,
+ })).toHaveLength(1);
+ });
+});
diff --git a/test/extract-by-mention-rebuild.test.ts b/test/extract-by-mention-rebuild.test.ts
index 3d26594339..a28270884c 100644
--- a/test/extract-by-mention-rebuild.test.ts
+++ b/test/extract-by-mention-rebuild.test.ts
@@ -16,6 +16,7 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tes
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runExtract } from '../src/commands/extract.ts';
import { setCliOptions } from '../src/core/cli-options.ts';
+import { scanStaleMentions } from '../src/core/by-mention.ts';
let engine: PGLiteEngine;
@@ -108,6 +109,25 @@ async function mentionTargets(fromSlug: string): Promise<Array<{ to: string; kin
}
describe('extract links --by-mention --rebuild (#3674)', () => {
+ test('Hangul boundary repair removes historical false links but keeps real mentions', async () => {
+ await engine.putPage('people/jiwon', {
+ type: 'person', title: '지원', compiled_truth: '', timeline: '', frontmatter: {},
+ });
+ await seedContentPage('writing/false', '재지원 안내');
+ await seedContentPage('writing/real', '지원에게 물었다');
+ // Persist the link an older character-only matcher would have written.
+ await engine.addLinksBatch([{
+ from_slug: 'writing/false', to_slug: 'people/jiwon', link_type: 'mentions',
+ link_source: 'mentions', context: '', from_source_id: 'default', to_source_id: 'default',
+ }]);
+ expect((await scanStaleMentions(engine)).staleLinks).toBe(1);
+ await runCli(['links', '--by-mention', '--rebuild', '--source', 'db']);
+ expect(exitedWith).toBeNull();
+ expect(await mentionTargets('writing/false')).toEqual([]);
+ expect((await mentionTargets('writing/real')).map(t => t.to)).toEqual(['people/jiwon']);
+ expect((await scanStaleMentions(engine)).staleLinks).toBe(0);
+ });
+
test('rebuild removes the stale mention the additive path leaves behind', async () => {
await seedEntities();
await seedContentPage('writing/post-1', 'We met with Acme Corp yesterday.');