Repository navigation
Expand file tree
/
Copy pathquery-normalize.mjs
More file actions
416 lines (386 loc) · 15.6 KB
/
Copy pathquery-normalize.mjs
File metadata and controls
416 lines (386 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/**
* Deterministic Chinese/English query normalization and entity extraction.
* Pure ESM, zero third-party dependencies.
*/
import { normalizeText } from './security.mjs'
import { foldEnglishInflection } from './retrieval.mjs'
const PUNCTUATION_RE = /[??!!。,,、;;::""''“”‘’()()《》【】\[\]「」『』…—–~·/\\]+/g
const EDGE_SYMBOL_RE = /(?<![\p{L}\p{N}])[-_.]+|[-_.]+(?![\p{L}\p{N}])/gu
// These are retrieval cues, not assertions that two terms mean the same thing in every context.
const CONCEPT_GROUPS = [
['称呼', '昵称', '叫我', 'nickname', 'name'],
['风格', '画风', '调性', 'style', 'tone'],
['克制', '简洁', '不花哨', '素雅', 'minimal', 'concise', 'restrained', 'understated'],
['艳丽', '鲜艳', 'vivid', 'colorful', 'colourful'],
['颜色', '配色', '调色', 'color', 'colour', 'palette', 'grade'],
['预算', '费用', '价格', 'budget', 'cost', 'price', 'expense'],
['偏好', '习惯', 'preference', 'habit'],
['交付', '输出', '格式', 'delivery', 'output', 'format'],
['淘汰', '弃用', '旧版', '不要用', 'deprecated', 'obsolete', 'retired'],
]
const CONCEPT_BY_TERM = new Map(CONCEPT_GROUPS.flatMap(aliases => aliases.map(term => [term, aliases])))
const HAN_CONCEPT = new RegExp([...CONCEPT_BY_TERM.keys()].filter(term => /^\p{Script=Han}/u.test(term)).join('|'), 'gu')
function conceptTerms(tokens) {
const terms = new Set()
for (const token of tokens) {
const lower = token.toLowerCase()
if (CONCEPT_BY_TERM.has(lower)) terms.add(lower)
else if (/\p{Script=Han}/u.test(lower)) {
for (const [term] of lower.matchAll(HAN_CONCEPT)) terms.add(term)
}
}
return terms
}
/** Expand concept cues once. Literal terms retain their original lexical weight. */
export function expandConceptSynonyms(tokens) {
const literal = conceptTerms(tokens)
const expanded = new Set()
for (const term of literal) {
for (const alias of CONCEPT_BY_TERM.get(term)) if (!literal.has(alias)) expanded.add(alias)
}
return expanded
}
/**
* High-frequency Chinese question/filler phrases stripped only when substantive terms remain.
* Ordered longest-first for multi-character phrases; single-character particles handled separately.
*/
const MULTI_FILLERS = [
'最后敲定',
'最后定了',
'采用的是',
'还要不要用',
'还要不要',
'可不可以',
'应该怎么',
'怎么处理',
'怎么定的',
'用的哪款',
'哪个版本',
'什么格式',
'改成啥了',
'敲定了没',
'的时候',
'应该用',
'有没有',
'是什么',
'哪一套',
'要怎么',
'用的是',
'是不是',
'能不能',
'请问',
'一下',
'到底',
'原来',
'原本',
'打算',
'以后',
'之后',
'哪套',
'哪个',
'哪些',
'怎么',
'现在',
'目前',
'时用',
'用了',
]
const MULTI_FILLER_RE = new RegExp(MULTI_FILLERS.join('|'), 'g')
const SINGLE_PARTICLE_INNER_RE = /(?<=[\p{Script=Han}\p{L}\p{N}])(?:的|了)(?=[\p{Script=Han}\p{L}\p{N}])/gu
const SINGLE_PARTICLE_TRAIL_RE = /(?<=[\p{Script=Han}\p{L}\p{N}]{2,})[吗呢啊呀的了](?![\p{Script=Han}\p{L}\p{N}])/gu
const SINGLE_PARTICLE_OTHER_TRAIL_RE = /(?<=[\p{Script=Han}\p{L}\p{N}])[吗呢啊呀](?![\p{Script=Han}\p{L}\p{N}])/gu
const STANDALONE_PARTICLE_RE = /(?:^|\s)[吗呢啊呀的了](?=\s|$)/gu
const MIXED_WHOLE_RE = /^[\p{Script=Han}]{1,4}[A-Za-z0-9]{1,8}$/u
const TOKEN_PIECE_RE = /(?:(?!\p{Script=Han})[\p{L}\p{N}])+(?:[-_.](?:(?!\p{Script=Han})[\p{L}\p{N}])+)+|\p{Script=Han}+(?:\d+[A-Za-z0-9]*|(?![a-z]+[A-Z])[A-Za-z]{2,8}\d*)|\p{Script=Han}+|(?:(?!\p{Script=Han})[\p{L}\p{N}])+/gu
const HAN_RUN_RE = /\p{Script=Han}{2,}/gu
let hanSegmenter
function segmentHanWords(text) {
const words = new Set()
const runs = text.match(HAN_RUN_RE)
if (!runs) return words
if (hanSegmenter === undefined) {
hanSegmenter = typeof globalThis.Intl?.Segmenter === 'function'
? new Intl.Segmenter('zh', { granularity: 'word' })
: null
}
if (!hanSegmenter) return words
for (const run of runs) {
for (const { segment, isWordLike } of hanSegmenter.segment(run)) {
if (isWordLike && [...segment].length >= 2) words.add(segment)
}
}
return words
}
/**
* Clean punctuation while preserving internal identifier characters (-, _, .).
* @param {string} text
* @returns {string}
*/
function stripPunctuation(text) {
return text
.replace(PUNCTUATION_RE, ' ')
.replace(EDGE_SYMBOL_RE, ' ')
.replace(/\s+/g, ' ')
.trim()
}
/**
* Strip Chinese filler phrases & particles if substantive terms remain.
* @param {string} text
* @returns {string}
*/
function stripFillers(text) {
const afterMulti = text.replace(MULTI_FILLER_RE, ' ').replace(/\s+/g, ' ').trim()
const afterParticles = afterMulti
.replace(SINGLE_PARTICLE_INNER_RE, ' ')
.replace(SINGLE_PARTICLE_TRAIL_RE, ' ')
.replace(SINGLE_PARTICLE_OTHER_TRAIL_RE, ' ')
.replace(STANDALONE_PARTICLE_RE, ' ')
.replace(/\s+/g, ' ')
.trim()
if (extractClauses(afterParticles).length > 0) return afterParticles
if (extractClauses(afterMulti).length > 0) return afterMulti
return text
}
/**
* Extract substantive clauses from punctuation-cleaned text.
* Keeps Han runs >= 2 chars, alphanumeric/identifier runs, and mixed Han+digit/Latin tokens intact.
* @param {string} cleanedText
* @returns {string[]}
*/
export function extractClauses(cleanedText) {
if (!cleanedText) return []
const clauses = []
for (const chunk of cleanedText.split(/\s+/u)) {
if (!chunk) continue
if (MIXED_WHOLE_RE.test(chunk)) {
clauses.push(chunk)
continue
}
for (const match of chunk.matchAll(TOKEN_PIECE_RE)) {
const piece = match[0]
const chars = [...piece]
const hasHan = /\p{Script=Han}/u.test(piece)
const hasNonHan = /(?:(?!\p{Script=Han})[\p{L}\p{N}])/u.test(piece)
if (hasHan && hasNonHan) {
const mixed = piece.match(/^(\p{Script=Han}+)(.+)$/u)
if (mixed && [...mixed[1]].length >= 4) {
const hChars = [...mixed[1]]
const prefix = hChars.slice(0, -2).join('')
if ([...prefix].length >= 2) clauses.push(prefix)
clauses.push(hChars.slice(-2).join('') + mixed[2])
} else {
clauses.push(piece)
}
} else if (hasHan) {
if (chars.length >= 2) clauses.push(piece)
} else if (chars.length >= 2 || /\d/.test(piece)) {
clauses.push(piece)
}
}
}
return clauses
}
/**
* Populate bigrams (Han 2-grams + folded English tokens + intact identifiers) and character 3-grams.
* @param {string[]} clauses
* @returns {{ bigrams: Set<string>, trigrams: Set<string> }}
*/
function buildNgrams(clauses) {
const bigrams = new Set()
const trigrams = new Set()
for (const clause of clauses) {
const lower = clause.toLowerCase()
const chars = [...lower]
for (let i = 0; i <= chars.length - 3; i += 1) {
trigrams.add(chars.slice(i, i + 3).join(''))
}
const hasHan = /\p{Script=Han}/u.test(lower)
const hasNonHan = /[a-z0-9]/i.test(lower)
if (hasHan && hasNonHan) {
bigrams.add(lower)
for (const hanRun of lower.match(/\p{Script=Han}+/gu) ?? []) {
const hChars = [...hanRun]
for (let i = 0; i < hChars.length - 1; i += 1) {
bigrams.add(hChars[i] + hChars[i + 1])
}
}
for (const alnumRun of lower.match(/[a-z0-9]+(?:[-_.][a-z0-9]+)*/g) ?? []) {
if (/^[a-z]{5,}$/.test(alnumRun)) bigrams.add(foldEnglishInflection(alnumRun))
else bigrams.add(alnumRun)
}
} else if (hasHan) {
for (let i = 0; i < chars.length - 1; i += 1) {
bigrams.add(chars[i] + chars[i + 1])
}
} else if (/^[a-z]{5,}$/.test(lower)) {
bigrams.add(foldEnglishInflection(lower))
} else {
bigrams.add(lower)
}
}
return { bigrams, trigrams }
}
/**
* Normalize a search query into substantive clauses, Han words, bigrams, and trigrams.
* @param {string} query
* @returns {{ raw: string, cleaned: string, clauses: string[], words: Set<string>, bigrams: Set<string>, trigrams: Set<string>, hasQuestionMark: boolean }}
*/
export function normalizeQuery(query) {
const raw = String(query ?? '')
const normalized = normalizeText(raw)
const hasQuestionMark = /[??]/.test(normalized)
const noPunct = stripPunctuation(normalized)
const cleaned = stripFillers(noPunct)
const clauses = extractClauses(cleaned)
const { bigrams, trigrams } = buildNgrams(clauses)
return { raw, cleaned, clauses, words: segmentHanWords(cleaned), bigrams, trigrams, hasQuestionMark }
}
/**
* Tokenize stored document text for FTS5 indexing and JS cosine similarity without stripping content fillers.
* @param {string} text
* @returns {{ clauses: string[], words: Set<string>, bigrams: Set<string>, trigrams: Set<string>, concepts: Set<string>, tokenString: string }}
*/
export function tokenizeDocument(text) {
const normalized = normalizeText(String(text ?? ''))
const noPunct = stripPunctuation(normalized)
const clauses = extractClauses(noPunct)
const { bigrams, trigrams } = buildNgrams(clauses)
const words = segmentHanWords(noPunct)
const concepts = conceptTerms([...clauses, ...bigrams, ...words])
const allTerms = new Set([...bigrams, ...words, ...clauses.map((c) => c.toLowerCase()), ...concepts])
for (const ent of extractEntities(normalized)) {
const lower = ent.entity.toLowerCase()
bigrams.add(lower)
allTerms.add(lower)
}
return {
clauses,
words,
bigrams,
trigrams,
concepts,
tokenString: [...allTerms].join(' '),
}
}
const WORK_RE = /《([^《》\n]{2,40})》/g
const FILE_RE = /(?<![\p{L}\p{N}._-])(?:[\p{L}\p{N}_.-]+\/)*[\p{L}\p{N}_.-]+\.(?:md|py|ts|js|mjs|json|txt|pdf|docx)(?![\p{L}\p{N}_])/giu
const VERSION_ID_RE = /(?<![A-Za-z0-9._-])v?\d+(?:\.\d+){1,3}(?:-[A-Za-z0-9]+)?(?![A-Za-z0-9._-])/g
const DASH_ID_RE = /(?<![A-Za-z0-9._-])[A-Za-z0-9]+(?:-[A-Za-z0-9]+)+(?![A-Za-z0-9._-])/g
const UPPER_SNAKE_ID_RE = /(?<![A-Za-z0-9._-])[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+(?![A-Za-z0-9._-])/g
const CODE_ID_RE = /(?<![A-Za-z0-9._-])[A-Z]{1,4}\d+[A-Za-z0-9-]*(?![A-Za-z0-9._-])/g
const HAN_MIXED_RE = /([\p{Script=Han}]{2,6})(\d{2,}[A-Za-z0-9-]*|[A-Za-z]{2,10}\d*)(?![A-Za-z0-9._-])/gu
const HAN_NEG_PREFIX_RE = /^(?:不再使用|不再采用|不再用|不要用|不使用|不用|禁用|弃用|废弃|废除|取消|删除|替代旧|替换旧|替换掉|放弃|而不是|而非)+/u
const HAN_LEADING_VERBS = /^[的了是用在和与把将按改换定采使为]+/u
const SNAKE_SYMBOL_RE = /(?<![A-Za-z0-9._-])[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+(?![A-Za-z0-9._-])/g
const CAMEL_SYMBOL_RE = /(?<![A-Za-z0-9._-])[A-Za-z][a-z0-9]+(?:[A-Z][a-z0-9]*)+(?![A-Za-z0-9._-])/g
const CLAUSE_DELIM_RE = /[,,。;;!?!?\n]/u
const PREFIX_NEGATION_RE = /(?:不再使用|不再采用|不再用|不要用|不使用|不用|禁用|弃用|废弃|废除|取消|删除|替代旧|替换旧|替换掉|放弃|而不是|而非|instead\s+of|no\s+longer|deprecated|disabled|rather\s+than|do\s+not\s+use|don't\s+use)/iu
const SUFFIX_NEGATION_RE = /(?:已删除|删除|已废弃|已弃用|已下线|禁用|deprecated|removed|disabled|replaced\s+by)/iu
const MAX_ENTITIES = 12
/**
* Determine whether an entity match at [startIdx, endIdx) is negated in its local clause.
* Checks up to 24 chars of immediate clause prefix and up to 16 chars of immediate clause suffix.
* @param {string} text
* @param {number} startIdx
* @param {number} endIdx
* @returns {boolean}
*/
function isEntityNegated(text, startIdx, endIdx) {
const preStart = Math.max(0, startIdx - 24)
const rawPrefix = text.slice(preStart, startIdx)
let lastDelim = -1
for (let i = rawPrefix.length - 1; i >= 0; i -= 1) {
if (CLAUSE_DELIM_RE.test(rawPrefix[i])) {
lastDelim = i
break
}
}
const prefix = lastDelim >= 0 ? rawPrefix.slice(lastDelim + 1) : rawPrefix
if (PREFIX_NEGATION_RE.test(prefix)) return true
const rawSuffix = text.slice(endIdx, Math.min(text.length, endIdx + 16))
const delimMatch = rawSuffix.search(CLAUSE_DELIM_RE)
const suffix = delimMatch >= 0 ? rawSuffix.slice(0, delimMatch) : rawSuffix
return SUFFIX_NEGATION_RE.test(suffix)
}
/**
* Deterministically extract high-signal entities from text for 1-hop linking.
* Deduplicates case-insensitively (positive mention wins over negated) and caps at 12 entities per record.
* @param {string} text
* @returns {Array<{ entity: string, kind: 'work' | 'preset_or_id' | 'file' | 'symbol', negated: boolean }>}
*/
export function extractEntities(text) {
const normalized = normalizeText(String(text ?? ''))
if (!normalized.trim()) return []
const entities = []
const seen = new Map()
const add = (entity, kind, negated = false) => {
const clean = entity.trim()
if (!clean) return entities.length < MAX_ENTITIES
const key = clean.toLowerCase()
const existing = seen.get(key)
if (existing) {
if (!negated) existing.negated = false
return entities.length < MAX_ENTITIES
}
if (entities.length >= MAX_ENTITIES) return false
const entry = { entity: clean, kind, negated: Boolean(negated) }
seen.set(key, entry)
entities.push(entry)
return entities.length < MAX_ENTITIES
}
for (const match of normalized.matchAll(WORK_RE)) {
const inner = match[1].trim()
if (inner.length >= 2 && inner.length <= 40) {
const negated = isEntityNegated(normalized, match.index, match.index + match[0].length)
if (!add(inner, 'work', negated)) return entities
}
}
// Blank out SoloPup structural topic-file suffixes (e.g. "— project.md") and matched file paths/IDs.
let masked = normalized.replace(/—\s*(?:project|user|preference|reference|episode|MEMORY)\.md(?:\s+\(exp:[^)]+\))?\s*$/u, (m) => ' '.repeat(m.length))
for (const match of masked.matchAll(FILE_RE)) {
const negated = isEntityNegated(normalized, match.index, match.index + match[0].length)
if (!add(match[0], 'file', negated)) return entities
}
masked = masked.replace(FILE_RE, (m) => ' '.repeat(m.length))
for (const re of [VERSION_ID_RE, DASH_ID_RE, UPPER_SNAKE_ID_RE, CODE_ID_RE]) {
for (const match of masked.matchAll(re)) {
const negated = isEntityNegated(normalized, match.index, match.index + match[0].length)
if (!add(match[0], 'preset_or_id', negated)) return entities
}
masked = masked.replace(re, (m) => ' '.repeat(m.length))
}
for (const match of masked.matchAll(HAN_MIXED_RE)) {
const hanPart = match[1]
const tailPart = match[2]
// Skip camelCase/snake_case symbols attached to Chinese verbs (e.g. 调用createCall).
if (/^[a-z]+[A-Z]/.test(tailPart) || tailPart.includes('_')) continue
const strippedNeg = hanPart.replace(HAN_NEG_PREFIX_RE, '')
const trimmedHan = strippedNeg.replace(HAN_LEADING_VERBS, '')
const hanChars = [...strippedNeg]
let entHan = null
if (trimmedHan.length >= 2 && trimmedHan.length <= 4) {
entHan = trimmedHan
} else if (hanChars.length >= 2) {
entHan = hanChars.slice(-2).join('')
}
if (entHan) {
const entityStart = match.index + hanPart.length - entHan.length
const entityEnd = match.index + match[0].length
const negated = isEntityNegated(normalized, entityStart, entityEnd)
if (!add(entHan + tailPart, 'preset_or_id', negated)) return entities
}
}
for (const match of masked.matchAll(SNAKE_SYMBOL_RE)) {
if (match[0].length >= 4) {
const negated = isEntityNegated(normalized, match.index, match.index + match[0].length)
if (!add(match[0], 'symbol', negated)) return entities
}
}
for (const match of masked.matchAll(CAMEL_SYMBOL_RE)) {
if (match[0].length >= 4) {
const negated = isEntityNegated(normalized, match.index, match.index + match[0].length)
if (!add(match[0], 'symbol', negated)) return entities
}
}
return entities
}