Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): strip Korean particles in the CJK keyword match (#6666)
time-attackf998cf58c4a4
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 6b3edc9396..f63ea62911 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/planner-stats.ts` + `src/core/planner-stats-schema.ts` — F4b row-delta ANALYZE for PGLite (no autovacuum). Migration f4_planner_stats (`sqlFor.pglite` only; a Postgres no-op) adds `planner_stats_deltas` / `planner_stats_state` and AFTER STATEMENT transition-table triggers on pages, links, facts, takes, content_chunks and timeline_entries, so modification counts commit or roll back with the data and survive restarts. `maybeRefreshPlannerStats(engine, reason)` ANALYZEs tables whose pending count exceeds max(500, 10% of reltuples) (or that have rows but no pg_stats) and publishes a watermark read before the ANALYZE, so a concurrent modification stays pending; checks are throttled to one per 2 s per engine. Call sites: PGLite planner-sensitive reads (`beforePlannerRead`, deferring a table whose last ANALYZE exceeded `planner.first_read_budget_ms`), import and managed sync every `import.analyze_every_pages`, stale link drains and the `extract --source db` links walk of at least `LINK_DRAIN_ANALYZE_MIN_STALE` (500) pages through `plannerStatsForLinkDrain` (first page, then the same cadence; `link_transitions`/`link_relationships`, no deltas, with `links`), the cycle after extract_facts, the consumer idle tick, and `refreshProjectionStatistics` (full ANALYZE publishes every watermark). `planner.auto_analyze=false` / `GBRAIN_PLANNER_AUTO_ANALYZE=0` disables them all. Doctor `planner_stats_stale` (Postgres: `pg_stat_user_tables` plus absent `missingSearchStatistics`) and repair kind `planner-stats` keep working. Guide: `docs/guides/planner-stats.md`. Tests: `test/planner-stats*.test.ts` (`planner-stats-link-drain.test.ts` EXPLAINs the drain's snapshot read), `test/e2e/planner-stats-postgres.test.ts`.- `src/core/timeline-grading.ts` — `loadTimelineGradedPredicate(engine)`: which pages the 15-point brain_score timeline component grades (#5828). `engine-sql/health.ts` applies the predicate per page type to the linkable groups; `gradeTimelinePages` (re-exported by `orphan-policy.ts`) keeps the linkable (orphan-policy) pages whose active-pack primitive is `entity` or `temporal` (aliases resolve to the canonical type); undeclared and untyped types, and every page when no pack resolves, stay graded. Labelled "timeline density (entity and event pages)" in doctor and `get_health` output. Pinned by `test/brain-score-timeline-grading.test.ts`.-- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `SLUG_WORD_CHARS` + `PAGE_SLUG_SEG` (the shared slug-grammar fragments) and `SLUG_VARIATION_SELECTORS_RE` (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH `sync.ts:slugifySegment` and its twin `link-extraction.ts:normalizeBasename` apply, so the two grammars cannot drift on selectors), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.+- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `SLUG_WORD_CHARS` + `PAGE_SLUG_SEG` (the shared slug-grammar fragments) and `SLUG_VARIATION_SELECTORS_RE` (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH `sync.ts:slugifySegment` and its twin `link-extraction.ts:normalizeBasename` apply, so the two grammars cannot drift on selectors), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`), and `cjkMatchTerms(query)` (whitespace terms with a trailing Korean particle stripped by `stripKoreanParticle`, longest particle first, stem kept only at 2+ characters; the one term list every CJK keyword builder matches, so the count, the keyword pages and the chunk search agree). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.- `src/core/credential-projection.ts` — `credentialSafeProjection(text)`: the retrieval text of a canonical body. Every private-key span from `privateKeySpans` (`secret-scan.ts`: complete keys and keys cut off at their `BEGIN` or `END` line) becomes `PRIVATE_KEY_PROJECTION_TOKEN` (`<REDACTED:private_key_pem>`) followed by as many newlines as the span held, so line offsets and chunk anchors stay stable. A cheap `PRIVATE KEY-----` substring gate returns the text unchanged otherwise; idempotent (the token holds no marker). Applied after `sanitizeRemoteBody` by the recursive chunker (`chunkers/recursive.ts`, markdown and embed paths), fenced-code extraction (`markdown-chunks.ts`), `prepareCodeChunks` (`code-chunks.ts`) and evidence delivery's `pageEvidenceText` (`window`/`section`/`page` units), so no chunk, embedding input or delivered evidence carries key material, including a mid-key chunk with neither fence. The stored body and the raw page reads are unchanged. Not covered: image OCR chunks, and key material with no `BEGIN`/`END` marker anywhere on the page. Existing pages are re-chunked by `page-state/credential-reseal.ts`. Chunker and safe-fence versions are unchanged (4).- `src/core/code-graph-readiness.ts` — shared seven-state code readiness: not_built, no_symbols, indexing, ready, out_of_scope, projection_pending, unknown. Checks scoped current-projection readiness before accepting nonempty results as ready; empty probes apply the same live/current policy as code reads. The brain-wide out_of_scope comparison remains trusted-local-only. Edge readiness uses the resolver backfill watermark. Code definitions/references, callers/callees and recursive operations expose the result; code_blast/code_flow bypass traversal caching until cached data can be revalidated. Recursive disambiguation, language probes and concrete edge endpoints also require current live pages. All six agent-facing code tools remain suspended.diff --git a/src/core/cjk.ts b/src/core/cjk.tsindex 0062c6722b..b9d7012f23 100644--- a/src/core/cjk.ts+++ b/src/core/cjk.ts@@ -209,3 +209,42 @@ export function splitCJKQueryTerms(query: string): string[] {return Array.from(new Set(terms));}++/**+ * Korean postpositions (조사), longest first so `endsWith` takes the longest+ * particle ("에서" before "에"/"서", "으로" before "로").+ */+const KO_PARTICLES: readonly string[] = [+ '에서는', '에게서', '으로는', '으로서',+ '에서', '에게', '한테', '까지', '부터', '보다', '처럼', '마다',+ '조차', '라도', '이나', '으로', '로서',+ '은', '는', '이', '가', '을', '를', '에', '의', '로', '와', '과', '도', '만',+];++/** One-syllable stems ("회의" → "회") match almost everything, so a stem keeps 2+ characters. */+const KO_MIN_STEM_LENGTH = 2;++/**+ * The noun stem of a Korean term with a trailing particle ("혈당에서" →+ * "혈당"), or the term unchanged. Korean attaches particles to the noun, so+ * the substring match would otherwise miss a page that says "혈당 수치". The+ * stem is a substring of the inflected form, so matching the stem alone+ * covers both spellings. Stripping is lexical (고양이 → 고양), which only+ * widens a fallback match.+ */+export function stripKoreanParticle(term: string): string {+ for (const p of KO_PARTICLES) {+ if (term.length - p.length >= KO_MIN_STEM_LENGTH && term.endsWith(p)) return term.slice(0, -p.length);+ if (term.endsWith(p)) return term;+ }+ return term;+}++/**+ * The terms every CJK keyword builder matches: whitespace-split, Korean+ * particles stripped, deduplicated in order. The count, the keyword pages and+ * the chunk search all read this, so a count never disagrees with the rows.+ */+export function cjkMatchTerms(query: string): string[] {+ return Array.from(new Set(splitCJKQueryTerms(query).map(stripKoreanParticle)));+}diff --git a/src/core/search/cjk-keyword-sql.ts b/src/core/search/cjk-keyword-sql.tsindex 05a4e58e68..4f82b49b4b 100644--- a/src/core/search/cjk-keyword-sql.ts+++ b/src/core/search/cjk-keyword-sql.ts@@ -22,7 +22,7 @@*/import type { SearchOpts } from '../types.ts';import { buildBestPerPagePoolCte } from './sql-ranking.ts';-import { escapeLikePattern, splitCJKQueryTerms } from '../cjk.ts';+import { escapeLikePattern, cjkMatchTerms } from '../cjk.ts';/** Query-shape context shared by both engines' CJK fallback call sites. */export interface CjkKeywordCtx {@@ -63,7 +63,7 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx, variant: Cconst { limit, offset, innerLimit, sourceFactorCase, hardExcludeClause, visibilityClause, detailFilter, opts, dedup } = ctx;const qRaw = query;if (qRaw.length === 0) return null;- const terms = splitCJKQueryTerms(qRaw);+ const terms = cjkMatchTerms(qRaw);if (terms.length === 0) return null;const any = variant.match === 'any' && terms.length > 1;@@ -152,7 +152,7 @@ export function buildCJKCandidateSql(ctx: CjkKeywordCtx,stage: { match: 'all' | 'any'; cap: number; excludeIds?: number[] },): CjkKeywordSql | null {- const terms = splitCJKQueryTerms(query);+ const terms = cjkMatchTerms(query);if (query.length === 0 || terms.length === 0) return null;const params: unknown[] = [];const likeParamIndices = terms.map(term => { params.push(`%${escapeLikePattern(term)}%`); return params.length; });diff --git a/src/core/search/keyword-statement.ts b/src/core/search/keyword-statement.tsindex 8d690900a5..c58dd3ec8f 100644--- a/src/core/search/keyword-statement.ts+++ b/src/core/search/keyword-statement.ts@@ -20,7 +20,7 @@* round-trips through JSON exactly.*/import type { SearchOpts } from '../types.ts';-import { escapeLikePattern, hasCJK, splitCJKQueryTerms } from '../cjk.ts';+import { escapeLikePattern, hasCJK, cjkMatchTerms } from '../cjk.ts';import { getFtsLanguage } from '../fts-language.ts';import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';import { buildHardExcludeClause, buildSourceFactorCase, buildVisibilityClause } from './sql-ranking.ts';@@ -43,7 +43,7 @@ export function buildKeywordMatch(query: string, opts: SearchOpts | undefined):let predicate: string;let rank: string;if (hasCJK(query)) {- const terms = splitCJKQueryTerms(query);+ const terms = cjkMatchTerms(query);if (terms.length === 0) return null;const likes = terms.map(term => {params.push(`%${escapeLikePattern(term)}%`);diff --git a/test/cjk-keyword-fallback.test.ts b/test/cjk-keyword-fallback.test.tsindex fff21e8eee..353045cc96 100644--- a/test/cjk-keyword-fallback.test.ts+++ b/test/cjk-keyword-fallback.test.ts@@ -116,3 +116,25 @@ describe('hybrid wiring (#5989)', () => {}});});++describe('Korean particles in the CJK keyword match (#6666)', () => {+ test('an inflected term finds the page about its stem, on the chunk and page paths', async () => {+ await page('notes/glucose', '혈당 수치가 아침에 높았다.');+ await page('notes/other', '오늘은 운동을 했다.');+ expect(slugs(await engine.searchKeyword('혈당에서'))).toEqual(['notes/glucose']);+ expect(slugs(await engine.searchKeywordPages('혈당에서', undefined, { limit: 10 }))).toEqual(['notes/glucose']);+ });++ test('the strict AND keeps every term: a second stemmed term that matches nothing still finds nothing', async () => {+ await page('notes/glucose', '혈당 수치가 아침에 높았다.');+ expect(await engine.searchKeyword('혈당에서 검진을')).toEqual([]);+ await page('notes/both', '혈당 검진 결과를 받았다.');+ expect(slugs(await engine.searchKeyword('혈당에서 검진을'))).toEqual(['notes/both']);+ });++ test('a word that merely ends in a particle syllable is not stripped to one syllable', async () => {+ await page('notes/meeting', '회의 일정을 잡았다.');+ await page('notes/hoe', '회 한 접시를 먹었다.');+ expect(slugs(await engine.searchKeyword('회의'))).toEqual(['notes/meeting']);+ });+});diff --git a/test/cjk-keyword-sql.test.ts b/test/cjk-keyword-sql.test.tsindex 43466798e5..0b97deb514 100644--- a/test/cjk-keyword-sql.test.ts+++ b/test/cjk-keyword-sql.test.ts@@ -4,7 +4,8 @@* DATABASE_URL-gated block in test/e2e/engine-parity.test.ts.*/import { describe, test, expect } from 'bun:test';-import { buildCJKKeywordSql, type CjkKeywordCtx } from '../src/core/search/cjk-keyword-sql.ts';+import { buildKeywordMatch } from '../src/core/search/keyword-statement.ts';+import { buildCJKKeywordSql, buildCJKCandidateSql, type CjkKeywordCtx } from '../src/core/search/cjk-keyword-sql.ts';import { searchKeywordCJK, type ScopedReadRunner } from '../src/core/engine-sql/cjk-search.ts';import { scopedRead } from '../src/core/engine-sql/brands.ts';import type { SqlExecutor } from '../src/core/engine-sql/executor.ts';@@ -166,3 +167,20 @@ describe('engine-sql searchKeywordCJK executor (#3986)', () => {expect(called).toBe(false);});});++describe('Korean particles in the CJK builders (#6666)', () => {+ const likes = (params: unknown[]) => params.filter(p => typeof p === 'string' && p.startsWith('%'));+ test('the scoring query matches and scores the stem, not the inflected form', () => {+ const { params } = buildCJKKeywordSql('혈당에서', ctx())!;+ expect(likes(params)).toEqual(['%혈당%']);+ expect(params.filter(p => typeof p === 'string' && !p.startsWith('%'))).toEqual(['혈당', '혈당에서']);+ });++ test('the capped candidate stage matches the stem too', () => {+ expect(likes(buildCJKCandidateSql('혈당에서', ctx(), { match: 'all', cap: 50 })!.params)).toEqual(['%혈당%']);+ });++ test('the keyword count and pages match the stem', () => {+ expect(likes(buildKeywordMatch('혈당에서 검진을', undefined)!.params)).toEqual(['%혈당%', '%검진%']);+ });+});diff --git a/test/cjk.test.ts b/test/cjk.test.tsindex a75130cbc0..6844975a16 100644--- a/test/cjk.test.ts+++ b/test/cjk.test.ts@@ -9,6 +9,8 @@ import {CJK_CLAUSE_DELIMITERS,escapeLikePattern,splitCJKQueryTerms,+ stripKoreanParticle,+ cjkMatchTerms,} from '../src/core/cjk.ts';describe('hasCJK', () => {@@ -169,3 +171,36 @@ describe('splitCJKQueryTerms', () => {});});++describe('stripKoreanParticle (#6666)', () => {+ test('strips the longest trailing particle', () => {+ expect(stripKoreanParticle('혈당에서')).toBe('혈당');+ expect(stripKoreanParticle('검진을')).toBe('검진');+ expect(stripKoreanParticle('병원으로')).toBe('병원');+ expect(stripKoreanParticle('진료실에서')).toBe('진료실');+ expect(stripKoreanParticle('결과에서는')).toBe('결과');+ });++ test('keeps a word that only ends in a particle syllable', () => {+ expect(stripKoreanParticle('회의')).toBe('회의');+ expect(stripKoreanParticle('결과')).toBe('결과');+ expect(stripKoreanParticle('도로')).toBe('도로');+ expect(stripKoreanParticle('에서')).toBe('에서');+ expect(stripKoreanParticle('는')).toBe('는');+ });++ test('leaves Chinese, Japanese and ASCII terms alone', () => {+ expect(stripKoreanParticle('席位')).toBe('席位');+ expect(stripKoreanParticle('東京で')).toBe('東京で');+ expect(stripKoreanParticle('LDL')).toBe('LDL');+ expect(stripKoreanParticle('LDL수치가')).toBe('LDL수치');+ });+});++describe('cjkMatchTerms (#6666)', () => {+ test('stems each term and drops duplicates in order', () => {+ expect(cjkMatchTerms('혈당에서 검진을')).toEqual(['혈당', '검진']);+ expect(cjkMatchTerms('혈당 혈당에서 수치')).toEqual(['혈당', '수치']);+ expect(cjkMatchTerms('席位 升级')).toEqual(['席位', '升级']);+ });+});