dsh-memu-memory 1.2.6 → 1.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,8 +8,9 @@
8
8
  // duplicate/conflict gate — one ruler from blocking to commit.
9
9
  //
10
10
  // Dependency discipline: this module imports only lib/text-similarity.js (the
11
- // shared similarity ruler) and lib/curator-policy.js (the single constant
12
- // table). No state, no IO, no clock — same input, same output, always.
11
+ // shared similarity ruler), lib/curator-policy.js (the single constant table)
12
+ // and lib/tokenizer-v2.js (the V2 tokenizer delegated to by the TOKENIZER_V2
13
+ // switch). No state, no IO, no clock — same input, same output, always.
13
14
 
14
15
  import {
15
16
  bigrams,
@@ -38,21 +39,32 @@ import {
38
39
  PAIR_W_LEXICAL,
39
40
  PAIR_W_TITLE,
40
41
  PAIR_W_TOKEN,
42
+ RRF_DYNAMIC,
41
43
  RRF_K,
44
+ RRF_SLICE_BAND,
45
+ RRF_SLICE_BAND_CAP,
42
46
  RRF_W_BM25,
43
47
  RRF_W_DICE,
44
48
  RRF_W_ENTITY,
49
+ TOKENIZER_V2,
50
+ computeRRFWeights,
45
51
  } from './curator-policy.js'
52
+ import {
53
+ tokenStreamV2,
54
+ tokenize as tokenizeV2,
55
+ } from './tokenizer-v2.js'
46
56
 
47
57
  // —— §4.1 分词 ——
48
58
 
49
59
  /**
50
- * Verbatim §4.1: NFKC + lowercase; latin runs of ≥2 chars keep `._-` joins as
51
- * one token; CJK runs become single chars when isolated, otherwise overlapping
52
- * bigrams; the result is deduplicated (a set — Jaccard/blocking only care
53
- * about presence). Build tf from tokenStream below, never from this.
60
+ * V1 分词原实现(双角色):TOKENIZER_V2 关时的回退路径;开时是本模块内
61
+ * **idf 盲集合运算**(blocking 共享计数、tokenJaccard)的固定口径。
62
+ * NFKC + lowercase; latin runs of ≥2 chars keep `._-` joins as one token; CJK
63
+ * runs become single chars when isolated, otherwise overlapping bigrams; the
64
+ * result is deduplicated (a set — Jaccard/blocking only care about presence).
65
+ * Build tf from tokenStream below, never from this.
54
66
  */
55
- export function tokenize(text) {
67
+ function tokenizeV1(text) {
56
68
  const s = String(text || '').normalize('NFKC').toLowerCase()
57
69
  const out = []
58
70
  for (const m of s.matchAll(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g)) {
@@ -66,8 +78,8 @@ export function tokenize(text) {
66
78
  return [...new Set(out)]
67
79
  }
68
80
 
69
- /** Raw token stream (no dedupe) — the frequency source for BM25's tf. */
70
- function tokenStream(text) {
81
+ /** V1 token stream 原实现(无去重)——BM25 tf 的频率来源(回退路径)。 */
82
+ function tokenStreamV1(text) {
71
83
  const s = String(text || '').normalize('NFKC').toLowerCase()
72
84
  const out = []
73
85
  for (const m of s.matchAll(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g)) {
@@ -81,6 +93,33 @@ function tokenStream(text) {
81
93
  return out
82
94
  }
83
95
 
96
+ /**
97
+ * 对外分词入口(双轨制,P0-1):TOKENIZER_V2 开 → 委托 lib/tokenizer-v2.js
98
+ * (CJK unigram+bigram+trigram 三层 + 实体保护,Set 插入序数组);关 → V1
99
+ * 原路径。签名与语义兼容,返回去重 token 数组(插入序)。
100
+ *
101
+ * 消费口径分层(P0 基准回归修复):V2 的增量 token **只进 BM25 流**(idf
102
+ * 加权通道,unigram 的低 idf 由权重自然压掉,子词命中是纯收益);idf 盲的
103
+ * 集合运算——blocking 共享计数、tokenJaccard——固定 tokenizeV1(bigram+latin)。
104
+ * unigram 同时喂给集合运算会把高频单字灌进倒排/共享计数(候选池被灌爆、
105
+ * 集合重叠被拉平,Recall@10 0.7675→0.6375 的定量根因)。开关关时本入口
106
+ * 本来就是 V1,关闭路径字节级不变。
107
+ */
108
+ export function tokenize(text) {
109
+ if (TOKENIZER_V2) return tokenizeV2(text)
110
+ return tokenizeV1(text)
111
+ }
112
+
113
+ /**
114
+ * Raw token stream (no dedupe) — the frequency source for BM25's tf.
115
+ * 与 tokenize 同一开关:V2 → tokenStreamV2(与 tokenizeV2 同一生成器);V1 →
116
+ * tokenStreamV1。
117
+ */
118
+ function tokenStream(text) {
119
+ if (TOKENIZER_V2) return tokenStreamV2(text)
120
+ return tokenStreamV1(text)
121
+ }
122
+
84
123
  // —— §4.1 语料与 BM25 ——
85
124
 
86
125
  /**
@@ -176,7 +215,8 @@ function normalizedTitle(entry) {
176
215
  * charDice — similarTexts(title+\n+content):length-prune + containment floor
177
216
  * containment — the probe floor when the length prune fired, else 0
178
217
  * lexical — max(charDice, containment)
179
- * tokenJaccard — tokenize() set Jaccard over title+content
218
+ * tokenJaccard — V1 口径 tokenize set Jaccard over title+content(idf 盲集合
219
+ * 运算固定 V1;V2 三层只服务 BM25,见 tokenize 的 JSDoc)
180
220
  * titleDice — bigram Dice over the raw titles
181
221
  * titleExact — trimmed/lowercase title equality (non-empty)
182
222
  * entityJaccard — appliesTo set Jaccard; both empty → 0.5 neutral
@@ -189,7 +229,9 @@ export function pairFeatures(a, b) {
189
229
  charDice: detail.dice,
190
230
  containment: detail.containment,
191
231
  lexical: Math.max(detail.dice, detail.containment),
192
- tokenJaccard: jaccard(new Set(tokenize(aText)), new Set(tokenize(bText))),
232
+ // idf 盲集合运算固定 V1 口径:unigram 会把跨主题的高频单字重叠拉平
233
+ // tokenJaccard 的区分度。开关关时 tokenize 本就返回 V1,两种写法等价。
234
+ tokenJaccard: jaccard(new Set(tokenizeV1(aText)), new Set(tokenizeV1(bText))),
193
235
  titleDice: dice(bigrams(a?.title || ''), bigrams(b?.title || '')),
194
236
  titleExact: normalizedTitle(a) !== '' && normalizedTitle(a) === normalizedTitle(b),
195
237
  entityJaccard: entityScore(a?.appliesTo, b?.appliesTo),
@@ -250,7 +292,8 @@ export function pairDecision(a, b, features = pairFeatures(a, b)) {
250
292
  // —— §4.8 全局冲突预筛 ——
251
293
 
252
294
  // Same pattern as memory.js's NEGATION_RE (not exported there; lib/memory.js is
253
- // outside this package's edit scope). One ruler for "opposite claim".
295
+ // outside this package's edit scope). One ruler for "opposite claim". 整文本
296
+ // 口径保持原样(P0 前的既有行为,也是无锚点时的回退路径),词典不在此扩。
254
297
  const NEGATION_RE = /不|没|别|无|never|not|no longer|doesn't|don't/i
255
298
 
256
299
  /** True when the text carries a negation marker (memory.js findConflict 口径). */
@@ -258,6 +301,68 @@ export function negationPolarity(text) {
258
301
  return NEGATION_RE.test(String(text || ''))
259
302
  }
260
303
 
304
+ // —— 子句级否定作用域(P1-2)——
305
+ //
306
+ // 整文本 negationPolarity 有两类误报:无关子句的否定污染(「截止日期是 5 月
307
+ // 1 日,别忘了」整条算否定侧)和双重否定(「不是不喜欢香菜」仍算否定侧)。
308
+ // polarityAt 把判定范围缩到锚点所在的子句,用标记计数 mod 2 近似否定作用域,
309
+ // 不做句法分析——同输入同输出,无 clock。
310
+
311
+ // 子句切分:中西标点一视同仁(连续标点算一次切分)。
312
+ const CLAUSE_SPLIT_RE = /[。!?;,、,.!?;:]+/
313
+
314
+ // 对比结构:「不是 A 而是 B」的 B、「不用 A 改成/换成 B」的 B 都是肯定侧,
315
+ // 前文标记的否定作用到对比词为止。
316
+ const CONTRAST_RE = /而不是|而是|改成|换成/g
317
+
318
+ // 否定标记词典。CJK 没有词边界(\b 对中文无效),靠最长优先的 alternation
319
+ // 保证「不再」「没有」只数一次而不是拆成「不」+「再」;「非常/未来/别的」
320
+ // 与否定标记同形但不是否定(高频词),用 lookahead 排除。英文统一用 \b 包住
321
+ // (缩写以 't 结尾,\b 仍成立;不 \b 的话 'not' 会命中 another/desktop)。
322
+ const NEG_MARKER_RE = /禁止|不得|无法|不能|不再|从不|从未|并不|并非|没有|拒绝|反对|不|没|别(?!的)|无|未(?!来)|勿|莫|非(?!常)|\b(?:not|never|no longer|cannot|without|avoid|refuse|stop|doesn't|don't|won't|can't)\b/gi
323
+
324
+ /**
325
+ * 一个子句内、锚点所在片段是否为否定侧。对比词把子句切成片段,逐片段判定:
326
+ * 片段自带标记计数(奇数 → 否定);「而不是」引出的片段额外继承 1 个否定
327
+ * (「而不是队列」的队列仍是否定侧,等价于标记紧邻锚点前不被对比词隔断的
328
+ * 场景),「而是/改成/换成」引出的片段从 0 起算。锚点在同片段多次出现只按
329
+ * 片段判定一次,锚点落在多个片段时任一片段否定即为否定(保守)。
330
+ */
331
+ function segmentNegated(clause, needle) {
332
+ const segments = []
333
+ let last = 0
334
+ let inherit = false
335
+ for (const m of clause.matchAll(CONTRAST_RE)) {
336
+ segments.push({ text: clause.slice(last, m.index), inherit })
337
+ inherit = m[0] === '而不是'
338
+ last = m.index + m[0].length
339
+ }
340
+ segments.push({ text: clause.slice(last), inherit })
341
+ for (const segment of segments) {
342
+ if (!segment.text.includes(needle)) continue
343
+ let markers = 0
344
+ for (const _ of segment.text.matchAll(NEG_MARKER_RE)) markers += 1
345
+ if ((markers + (segment.inherit ? 1 : 0)) % 2 === 1) return true
346
+ }
347
+ return false
348
+ }
349
+
350
+ /**
351
+ * 子句级否定极性(P1-2):text 里 anchor 所在的每个子句,任一为否定即算否定
352
+ * 侧(锚点多次出现取保守口径)。子句切分与标记匹配都在 NFKC + lowercase 之后
353
+ * 进行——锚点来自 tokenize(同一规范化),latin 大小写/全角差异不会漏匹配。
354
+ * 锚点为空或不在 text 中出现 → false(没有可判定的作用域就不是否定侧)。
355
+ */
356
+ export function polarityAt(text, anchor) {
357
+ const needle = String(anchor || '').normalize('NFKC').toLowerCase()
358
+ if (!needle) return false
359
+ const s = String(text || '').normalize('NFKC').toLowerCase()
360
+ for (const clause of s.split(CLAUSE_SPLIT_RE)) {
361
+ if (clause.includes(needle) && segmentNegated(clause, needle)) return true
362
+ }
363
+ return false
364
+ }
365
+
261
366
  /** 数字、周X/星期X、YYYY-MM-DD、M月D日 —— 抽出来比集合(§4.8 numericSetsDiffer)。 */
262
367
  export function numericSet(text) {
263
368
  const s = String(text || '')
@@ -278,17 +383,43 @@ export function numericSetsDiffer(a, b) {
278
383
  return false
279
384
  }
280
385
 
386
+ /**
387
+ * 冲突锚点:双方 body 的共享 token 里最长者(长度相同取字典序最小,完全确定,
388
+ * 与遍历序无关)。token 来自当前生效的 tokenize(双轨开关自动生效),只要求
389
+ * 子串包含关系(clause.includes(anchor))——锚点本身就是文本的子串,CJK
390
+ * unigram/bigram 与 latin 词都覆盖。无共享词返回 ''(调用方回退整文本口径)。
391
+ */
392
+ function longestSharedToken(aBody, bBody) {
393
+ const bTokens = new Set(tokenize(bBody))
394
+ let anchor = ''
395
+ for (const token of new Set(tokenize(aBody))) {
396
+ if (!bTokens.has(token)) continue
397
+ if (token.length > anchor.length || (token.length === anchor.length && token < anchor)) anchor = token
398
+ }
399
+ return anchor
400
+ }
401
+
281
402
  /**
282
403
  * §4.8 全局冲突预筛(同 domain/track 前提由调用方保证)。返回 'same_title' |
283
404
  * 'negation' | 'value' 或 null。containment ≥0.92 或 charDice ≥0.95 一票豁免
284
405
  * (重复/细化,不是冲突)。预筛只决定“送不送人审”,最终由 LLM + 人审裁决。
406
+ *
407
+ * negation 分支(P1-2):有共享锚点 → 双方 polarityAt(body, anchor) 不同才算
408
+ * 否定冲突(子句级作用域,修掉「无关子句否定污染」与「双重否定」两类误报);
409
+ * 无共享锚点 → 回退整文本 negationPolarity 对比(原口径,行为不变)。
285
410
  */
286
411
  export function globalConflictCheck(a, b, features = pairFeatures(a, b)) {
287
412
  if (features.containment >= 0.92 || features.charDice >= 0.95) return null
288
413
  if (features.titleExact && features.charDice < 0.95) return 'same_title'
289
414
  const aBody = String(a?.content || '')
290
415
  const bBody = String(b?.content || '')
291
- if (features.charDice >= 0.55 && negationPolarity(aBody) !== negationPolarity(bBody)) return 'negation'
416
+ if (features.charDice >= 0.55) {
417
+ const anchor = longestSharedToken(aBody, bBody)
418
+ const differs = anchor
419
+ ? polarityAt(aBody, anchor) !== polarityAt(bBody, anchor)
420
+ : negationPolarity(aBody) !== negationPolarity(bBody)
421
+ if (differs) return 'negation'
422
+ }
292
423
  if (features.titleDice >= 0.8 && features.charDice >= 0.55
293
424
  && numericSetsDiffer(`${a?.title || ''} ${aBody}`, `${b?.title || ''} ${bBody}`)) return 'value'
294
425
  return null
@@ -314,12 +445,19 @@ function idAsc(a, b) {
314
445
  * 1) blocking:同 track;N ≤ exactPairLimit 时精确两两,否则查询 token 中
315
446
  * df ≤ 30%N 的稀有词、共享 ≥2 token,或 exact title。
316
447
  * 2) 三路排名 bm25 / charDice / entityJaccard(tiebreak containment)。
317
- * 3) 加权 RRF(k=60):0.5/(60+rankBm25) + 0.3/(60+rankDice) + 0.2/(60+rankEntity)。
318
- * 4) 取前 limit 算完整 pairFeatures/pairScore/pairDecision,按 pairScore 降序。
448
+ * 3) 加权 RRF(k=60)。RRF_DYNAMIC 开 → 权重来自 computeRRFWeights(proposal,
449
+ * corpus):普通查询退化为静态 0.5/0.3/0.2,近期查询加第四路 recency
450
+ * (候选按 updatedAt 降序排名),coding 域 entity 提权;关 → 恒用静态
451
+ * 0.5/(60+rankBm25) + 0.3/(60+rankDice) + 0.2/(60+rankEntity)。
452
+ * 4) RRF 代理切分 + 边界带 → pairScore 真尺终选:前 max 名进评分集,与切点
453
+ * rrf 之差 ≤ RRF_SLICE_BAND 的候选并入(总量 ≤ max×RRF_SLICE_BAND_CAP),
454
+ * 全部算 pairFeatures/pairScore,按 pairScore 降序截取前 max——近重复簇里
455
+ * rrf 平刀锋时 len 归一噪声不再决定准入。
319
456
  * 5) 不足 limit 用同域最近条目补齐(“多看几眼”,不降低门槛)。
320
457
  *
321
458
  * 返回 [{ id, entry, score, decision, features, rrf, fallback }],score 降序,
322
- * 平手 rrf 降序 → id 升序——完全确定。
459
+ * 平手 rrf 降序 → id 升序——完全确定(动态路径的 recency 排名同样带
460
+ * idAsc tiebreak,不引入任何 clock/随机性)。
323
461
  */
324
462
  export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }) {
325
463
  const max = Number(limit) > 0 ? Math.floor(Number(limit)) : PAIR_SCAN_LIMIT
@@ -330,7 +468,10 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
330
468
  const proposalDomain = proposal?.domain || 'unknown'
331
469
  const proposalTitle = normalizedTitle(proposal)
332
470
  const proposalId = proposal?.id ?? null
333
- const queryTokens = tokenize(`${proposal.title || ''} ${proposal.content || ''}`)
471
+ const queryText = `${proposal.title || ''} ${proposal.content || ''}`
472
+ // BM25 查询词用当前生效分词(V2 三层在这里是收益);blocking 是 idf 盲的
473
+ // 共享计数,走下面的 V1 口径。
474
+ const queryTokens = tokenize(queryText)
334
475
 
335
476
  // 1) blocking
336
477
  const candidates = new Map()
@@ -343,7 +484,11 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
343
484
  } else {
344
485
  const dfCap = Math.ceil(BLOCK_DF_RATIO * n)
345
486
  const shared = new Map()
346
- for (const term of queryTokens) {
487
+ // blocking 固定 V1 口径(bigram+latin):V1 token ⊆ V2 token,V2 建的
488
+ // corpus.inverted 照样命中,bigram 的 posting/df 也不受 unigram 膨胀影响;
489
+ // 若用 V2 查询,高频单字会让无关条目凑满 ≥2 共享词,候选池被灌爆、
490
+ // target 被挤出 RRF 前 limit 切片(基准 Recall 池命中 0.985→0.8625 的主因)。
491
+ for (const term of tokenizeV1(queryText)) {
347
492
  const posting = corpus.inverted.get(term)
348
493
  if (!posting || posting.size === 0 || posting.size > dfCap) continue
349
494
  for (const id of posting) {
@@ -391,18 +536,57 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
391
536
  const rankEntity = new Map()
392
537
  entityOrder.forEach((item, index) => rankEntity.set(item.id, index + 1))
393
538
 
394
- // 3) weighted RRF
395
- const rrf = new Map()
396
- for (const id of ids) {
397
- rrf.set(id, RRF_W_BM25 / (RRF_K + rankBm25.get(id))
398
- + RRF_W_DICE / (RRF_K + rankDice.get(id))
399
- + RRF_W_ENTITY / (RRF_K + rankEntity.get(id)))
539
+ // 3) weighted RRF。开关关 → 静态三路原式(字节级回退路径);开 → 权重来自
540
+ // computeRRFWeights,含 recency 键时加第四路 updatedAt 降序排名。
541
+ let rrf
542
+ if (!RRF_DYNAMIC) {
543
+ rrf = new Map()
544
+ for (const id of ids) {
545
+ rrf.set(id, RRF_W_BM25 / (RRF_K + rankBm25.get(id))
546
+ + RRF_W_DICE / (RRF_K + rankDice.get(id))
547
+ + RRF_W_ENTITY / (RRF_K + rankEntity.get(id)))
548
+ }
549
+ } else {
550
+ const weights = computeRRFWeights(proposal, corpus)
551
+ const rankRecency = new Map()
552
+ if (weights.recency != null) {
553
+ // 第四路:updatedAt 字符串降序(updatedDesc + idAsc tiebreak,与 backfill
554
+ // 同一确定性口径);rank 为 1 起的稠密序,只覆盖 blocking 后的候选集。
555
+ const recencyOrder = ids
556
+ .map((id) => ({ id, entry: corpus.docs.get(id).entry }))
557
+ .sort((a, b) => updatedDesc(a.entry, b.entry) || idAsc(a, b))
558
+ recencyOrder.forEach((item, index) => rankRecency.set(item.id, index + 1))
559
+ }
560
+ rrf = new Map()
561
+ for (const id of ids) {
562
+ let value = weights.bm25 / (RRF_K + rankBm25.get(id))
563
+ + weights.dice / (RRF_K + rankDice.get(id))
564
+ + weights.entity / (RRF_K + rankEntity.get(id))
565
+ if (weights.recency != null) value += weights.recency / (RRF_K + rankRecency.get(id))
566
+ rrf.set(id, value)
567
+ }
400
568
  }
401
569
  ids.sort((a, b) => rrf.get(b) - rrf.get(a) || idAsc(a, b))
402
570
 
403
- // 4) features for the top slice only
571
+ // 4) features for the scored slice(P0-1 回归修复:准入从 RRF 代理换成
572
+ // pairScore 真尺)。pre-cut 用 RRF 代理决定谁进入完整 pairFeatures/pairScore
573
+ // 评分;近重复簇里 rrf 平刀锋时(bench 实测缝 3.6e-5),len 归一噪声决定
574
+ // 准入,pairScore 更准的候选反而落榜。修法:与切点 rrf 之差 ≤
575
+ // RRF_SLICE_BAND 的候选并入评分集(总量 ≤ max×RRF_SLICE_BAND_CAP,防病态
576
+ // 全带,超限按 rrf 降序 + idAsc 截断),评分集全部评分后按 pairScore 降序
577
+ // 截取前 max——准入决策从代理换真尺,返回数量语义不变(≤max)。开关关/开
578
+ // 同轨生效(这是准入结构的改进,不分轨)。
579
+ const cutIndex = Math.min(max, ids.length) - 1
580
+ const bandFloor = rrf.get(ids[cutIndex]) - RRF_SLICE_BAND
581
+ let scoredIds = []
582
+ for (const id of ids) {
583
+ if (rrf.get(id) < bandFloor) break // ids 已按 (rrf desc, idAsc) 排序,后面只会更低
584
+ scoredIds.push(id)
585
+ }
586
+ const bandCap = max * RRF_SLICE_BAND_CAP
587
+ if (scoredIds.length > bandCap) scoredIds = scoredIds.slice(0, bandCap)
404
588
  const taken = new Set()
405
- for (const id of ids.slice(0, max)) {
589
+ for (const id of scoredIds) {
406
590
  const doc = corpus.docs.get(id)
407
591
  const features = pairFeatures(proposal, doc.entry)
408
592
  const score = pairScore(features)
@@ -410,6 +594,8 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
410
594
  out.push({ id, entry: doc.entry, score, decision: pairDecision(proposal, doc.entry, features), features, rrf: rrf.get(id), fallback: false })
411
595
  }
412
596
  out.sort((a, b) => b.score - a.score || b.rrf - a.rrf || idAsc(a, b))
597
+ // 真尺终选:评分集可能因边界带超过 max,按 pairScore 降序截取前 max
598
+ if (out.length > max) out.length = max
413
599
  // 5) same-domain recent backfill — extra eyes, never a lower bar
414
600
  return backfill({ corpus, proposal, proposalDomain, proposalId, max, out, taken, queryTokens })
415
601
  }
@@ -494,7 +680,10 @@ export function buildCandidateClusters(index, options = {}) {
494
680
  const tokenSets = new Map()
495
681
  const inverted = new Map()
496
682
  for (const item of items) {
497
- const tokens = tokenize(`${item.entry?.title || ''} ${item.entry?.content || ''}`)
683
+ // blocking 倒排固定 V1 口径(idf 盲集合运算):unigram 会把高频单字灌大
684
+ // 倒排与两两共享计数(N=500 簇延迟 +60% 的根因),对成簇质量无收益。
685
+ // 边打分的 BM25 路由(下方 bm25Route/buildCorpus)仍走 V2 流。
686
+ const tokens = tokenizeV1(`${item.entry?.title || ''} ${item.entry?.content || ''}`)
498
687
  tokenSets.set(item.id, new Set(tokens))
499
688
  for (const term of tokens) {
500
689
  if (!inverted.has(term)) inverted.set(term, [])
@@ -535,7 +724,11 @@ export function buildCandidateClusters(index, options = {}) {
535
724
  }).filter((pair) => pair.score >= minPair)
536
725
  if (pairList.length === 0) continue
537
726
 
538
- // three route rankings for edge order only
727
+ // three route rankings for edge order only。
728
+ // 刻意不做动态权重(P0-2 只落在 rankPairCandidates):buildCandidateClusters
729
+ // 没有 proposal/查询上下文——它是无监督的全库成簇,三路 RRF 只决定贪心
730
+ // 长簇的边访问顺序;引入「查询类型」没有语义落点,静态三路保证簇构建
731
+ // 与查询无关、完全可复现。
539
732
  const bm25Route = pairList.map((pair) => ({
540
733
  key: pair.key,
541
734
  s: bm25(tokenStream(`${pair.aItem.entry?.title || ''} ${pair.aItem.entry?.content || ''}`), corpus.docs.get(pair.bId), corpus)
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Tokenizer V2 — 智能分层分词器(召回升级 P0-1)。
3
+ *
4
+ * 相对 lib/text-retrieval.js 的 V1 口径(CJK 只出 bigram),V2 解决:
5
+ * - R-01:CJK 只有 bigram,缺 unigram/trigram 层级,短查询命中不了子词;
6
+ * - R-03:无实体保护,日期/周几/数字/邮箱/URL 被拆散。
7
+ *
8
+ * 设计原则:
9
+ * 1. 英文与 latin 口径与 V1 完全一致([a-z0-9]+(?:[._-][a-z0-9]+)*,≥2 字符);
10
+ * 2. CJK 输出 unigram + bigram + trigram 三层;完整 run 只在长度 ≤4 时保留,
11
+ * 长句 run 的完整串是噪声且会抬高 BM25 文档长度,不收;
12
+ * 3. 实体(日期/周几/数字/百分比/邮箱/URL)整体成 token,不被 n-gram 拆散;
13
+ * 日期/周几正则与 text-retrieval.js 的 numericSet 同口径(周X/星期X 无空格);
14
+ * 4. 纯函数:No state, no IO, no clock——同输入同输出;去重用 Set 的插入序
15
+ * (先实体、后英文、后 CJK run,保留首次出现),不做任何排序。
16
+ *
17
+ * 集成方式(双轨制):lib/text-retrieval.js 的 tokenize/tokenStream 按
18
+ * lib/curator-policy.js 的 TOKENIZER_V2 开关委托到这里;开关关闭走 V1 原路径。
19
+ */
20
+
21
+ // —— 规范化与清理——
22
+
23
+ /** NFKC 归一化 + 小写化(与 V1 的预处理一致)。 */
24
+ export function normalizeAndLower(text) {
25
+ return String(text || '').normalize('NFKC').toLowerCase()
26
+ }
27
+
28
+ // —— 英文 tokenization(保持 V1 逻辑)——
29
+
30
+ /**
31
+ * 英文与 latin:与 V1 完全同口径——[a-z0-9]+(?:[._-][a-z0-9]+)*,
32
+ * 连接符词(dsh-memu-memory_v2.today)保持整 token,单字符丢弃(≥2 才收)。
33
+ */
34
+ function tokenizeEnglishTokens(s) {
35
+ const out = []
36
+ for (const m of s.matchAll(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g)) {
37
+ if (m[0].length >= 2) out.push(m[0])
38
+ }
39
+ return out
40
+ }
41
+
42
+ // —— CJK tokenization(三层 n-gram + 完整 run 上限)——
43
+
44
+ /**
45
+ * CJK 统一表意文字
46
+ * \u3400-\u9fff: CJK Unified Ideographs
47
+ * \uf900-\ufaff: CJK Compatibility Ideographs
48
+ */
49
+ const CJK_RANGE = /[\u3400-\u9fff\uf900-\ufaff]+/g
50
+
51
+ // 完整 run token 的保留上限:run 恰为 4 字时补收完整串(≤3 字时完整串已经是
52
+ // unigram/bigram/trigram 之一,≥5 字的长 run 完整串是噪声,都不另收)。
53
+ const CJK_RUN_KEEP_MAX = 4
54
+
55
+ /**
56
+ * CJK 字符序列的多层级 tokenization。
57
+ *
58
+ * - 单字 run → 只保留 unigram;
59
+ * - 长度 2~3 的 run → unigram + bigram(+trigram),完整串即其中之一;
60
+ * - 长度恰为 4 的 run → unigram + bigram + trigram + 完整 run token;
61
+ * - 长度 >4 的 run → 只输出 unigram + bigram + trigram(长句完整串不收,
62
+ * 避免噪声 token 抬高 BM25 文档长度)。
63
+ *
64
+ * 每层里同一个串只进流一次(无重复),tokenStreamV2 的 tf 不虚高。
65
+ *
66
+ * @param {string} run - CJK 字符序列
67
+ * @returns {string[]} 分层 token 列表(含重复语义由调用方决定,本函数不重复收串)
68
+ */
69
+ function tokenizeCJKRun(run) {
70
+ const out = []
71
+ if (run.length === 1) {
72
+ out.push(run)
73
+ return out
74
+ }
75
+ // Level 1: Unigram(每个字)
76
+ for (let i = 0; i < run.length; i++) out.push(run[i])
77
+ // Level 2: Bigram(相邻两个字)
78
+ for (let i = 0; i < run.length - 1; i++) out.push(run.slice(i, i + 2))
79
+ // Level 3: Trigram(相邻三个字)
80
+ if (run.length >= 3) {
81
+ for (let i = 0; i < run.length - 2; i++) out.push(run.slice(i, i + 3))
82
+ }
83
+ // Level 0: 完整 run——只在 4 字时是「额外」的一层(≤3 字已被上面覆盖)
84
+ if (run.length === CJK_RUN_KEEP_MAX) out.push(run)
85
+ return out
86
+ }
87
+
88
+ // —— 实体提取与保护——
89
+
90
+ // 数字边界:紧邻标识符连接字符的数字是标识符/日期的一部分,不作为独立数字
91
+ // 实体——'v2.today' 不拆出噪声 token '2','2026-11-05' 由完整日期实体覆盖而
92
+ // 不再拆出 '2026'/'11'/'05'。prev 看 [a-z0-9._-](标识符内部),next 看
93
+ // [a-z0-9_-](连字/日期连接;'.': 句点不拦,'85%.' 仍收 '85%')。
94
+ const IDENT_PREV_BOUNDARY = /[a-z0-9._-]/
95
+ const IDENT_NEXT_BOUNDARY = /[a-z0-9_-]/
96
+
97
+ function numberStandalone(text, index, length) {
98
+ const prev = index > 0 ? text[index - 1] : ''
99
+ const next = index + length < text.length ? text[index + length] : ''
100
+ if (IDENT_PREV_BOUNDARY.test(prev)) return false
101
+ if (IDENT_NEXT_BOUNDARY.test(next)) return false
102
+ return true
103
+ }
104
+
105
+ /**
106
+ * 提取需要保护的实体模式(口径对齐 text-retrieval.js numericSet:
107
+ * 周X/星期X 无空格、M月D日/号;在此之上保留完整 YYYY年M月D日):
108
+ * - 时间:YYYY-MM-DD、YYYY 年 M 月 D 日、M 月 D 日/号、周 X、星期 X
109
+ * - 数字/数值:整数、小数、百分比(只收独立数字——标识符/日期内部的数字不算)
110
+ * - 邮箱地址
111
+ * - URL(简化版——仅协议开头;去掉句尾标点,避免把「。」带进索引)
112
+ *
113
+ * @param {string} text - 已规范化的文本
114
+ * @returns {string[]} 提取的实体列表(按模式顺序,含重复)
115
+ */
116
+ function extractEntities(text) {
117
+ const entities = []
118
+
119
+ // 1. 日期时间
120
+ const datePatterns = [
121
+ /\d{4}-\d{1,2}-\d{1,2}/g, // YYYY-MM-DD
122
+ /\d{4}年\d{1,2}月\d{1,2}日/g, // YYYY 年 M 月 D 日
123
+ /\d{1,2}月\d{1,2}[日号]/g, // M 月 D 日/号(numericSet 同口径)
124
+ /周[一二三四五六日天]/g, // 周X(无空格——与 numericSet 对齐)
125
+ /星期[一二三四五六日天]/g, // 星期X(无空格——与 numericSet 对齐)
126
+ ]
127
+ for (const pattern of datePatterns) {
128
+ for (const match of text.matchAll(pattern)) {
129
+ entities.push(match[0])
130
+ }
131
+ }
132
+
133
+ // 2. 数字(整数、小数)——独立数字才收
134
+ const numberPattern = /\d+(?:\.\d+)?/g
135
+ for (const match of text.matchAll(numberPattern)) {
136
+ if (numberStandalone(text, match.index, match[0].length)) entities.push(match[0])
137
+ }
138
+
139
+ // 3. 百分比——同样要求独立('v2%' 不拆出 '2%')
140
+ const percentPattern = /\d+(?:\.\d+)?%/g
141
+ for (const match of text.matchAll(percentPattern)) {
142
+ if (numberStandalone(text, match.index, match[0].length)) entities.push(match[0])
143
+ }
144
+
145
+ // 4. 邮箱地址(简化版)
146
+ const emailPattern = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/g
147
+ for (const match of text.matchAll(emailPattern)) {
148
+ entities.push(match[0])
149
+ }
150
+
151
+ // 5. URL(简化版——仅协议开头;剥掉句尾标点)
152
+ const urlPattern = /https?:\/\/[^\s]+/g
153
+ for (const match of text.matchAll(urlPattern)) {
154
+ entities.push(match[0].replace(/[)\]}.,;:!?'"]*[。,、;:!?)》」』…]+$/, ''))
155
+ }
156
+
157
+ return entities
158
+ }
159
+
160
+ // —— 主接口——
161
+
162
+ /**
163
+ * Tokenizer V2 — 主入口函数。
164
+ *
165
+ * 完整的 tokenization 流程:
166
+ * 1. 规范化文本 (NFKC + lowercase)
167
+ * 2. 提取并保护特殊实体(先占位——Set 插入序让实体 token 排在最前)
168
+ * 3. 英文部分与 V1 同口径
169
+ * 4. CJK 部分按 unigram+bigram+trigram 三层(4 字 run 另收完整串)
170
+ * 5. Set 按插入序去重(保留首次出现,不排序——同输入同输出)
171
+ *
172
+ * @param {string} text - 输入文本
173
+ * @returns {Set<string>} 去重后的 token 集合(插入序)
174
+ *
175
+ * @example
176
+ * tokenizeV2('人工智能是一种技术')
177
+ * // run '人工智能是一种技术' 长度 9 > 4:不出完整 run,只出三层 n-gram——
178
+ * // 9 个 unigram(人/工/智/…)+ 8 个 bigram(人工/工智/智能/…)
179
+ * // + 7 个 trigram(人工智/工智能/…),共 24 个 token,无重复。
180
+ *
181
+ * @example
182
+ * tokenizeV2('2026-11-05 AI 技术很火,比如 Qwen3-Embedding')
183
+ * // 输出包含:'2026-11-05'(实体,不被拆散)、'ai'、'qwen3-embedding'、
184
+ * // '技'/'技术'/'技术很' 等 CJK 三层 token。
185
+ */
186
+ export function tokenizeV2(text) {
187
+ const normalized = normalizeAndLower(text)
188
+ const out = []
189
+
190
+ // Step 1: 提取并保护实体(先占位)
191
+ out.push(...extractEntities(normalized))
192
+
193
+ // Step 2: 英文部分 tokenization(与 V1 同口径)
194
+ out.push(...tokenizeEnglishTokens(normalized))
195
+
196
+ // Step 3: CJK 部分 tokenization(三层)
197
+ for (const match of normalized.matchAll(CJK_RANGE)) {
198
+ out.push(...tokenizeCJKRun(match[0]))
199
+ }
200
+
201
+ // Step 4: 去重——Set 保留插入序(首次出现),不做任何排序
202
+ return new Set(out)
203
+ }
204
+
205
+ /**
206
+ * Tokenize V2 的流式版本(用于 BM25 的 tf 计算)。
207
+ * 不对 token 去重,保持频率信息;生成器与 tokenizeV2 完全一致,因此
208
+ * tokenStreamV2 的去重集合恒等于 tokenizeV2 的集合(⊂ 语义上的同一性)。
209
+ *
210
+ * @param {string} text - 输入文本
211
+ * @returns {string[]} 所有 token(含重复)
212
+ */
213
+ export function tokenStreamV2(text) {
214
+ const normalized = normalizeAndLower(text)
215
+ const out = []
216
+
217
+ // 提取实体(重复出现会多次记录)
218
+ out.push(...extractEntities(normalized))
219
+
220
+ // 英文部分(重复会出现多次)
221
+ out.push(...tokenizeEnglishTokens(normalized))
222
+
223
+ // CJK 部分(多层级 + 重复)
224
+ for (const match of normalized.matchAll(CJK_RANGE)) {
225
+ out.push(...tokenizeCJKRun(match[0]))
226
+ }
227
+
228
+ return out
229
+ }
230
+
231
+ // —— 向后兼容——
232
+
233
+ /**
234
+ * 提供与 V1 调用点兼容的 tokenize 接口:
235
+ * 内部调用 V2 实现并展开为数组(Set 的插入序)。
236
+ */
237
+ export function tokenize(text) {
238
+ return [...tokenizeV2(text)]
239
+ }
240
+
241
+ // —— 测试用工具函数——
242
+
243
+ /**
244
+ * Token 统计信息:total 用数组 length 计(tokenize 返回数组),
245
+ * byType 覆盖全部 token(unknown 兜底),两项之和恒相等。
246
+ */
247
+ export function tokenizeStats(text) {
248
+ const tokens = tokenize(text)
249
+ const byType = new Map()
250
+
251
+ for (const token of tokens) {
252
+ let type = 'unknown'
253
+ if (/^\d+$/.test(token)) type = 'number'
254
+ else if (/^\d{4}-\d{1,2}-\d{1,2}$/.test(token)) type = 'date_iso'
255
+ else if (/^\d+(?:\.\d+)?%$/.test(token)) type = 'percent'
256
+ else if (/^[0-9a-z._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i.test(token)) type = 'email'
257
+ else if (/^https?:\/\//i.test(token)) type = 'url'
258
+ else if (/^[\u3400-\u9fff\uf900-\ufaff]$/.test(token)) type = 'cjk_unigram'
259
+ else if (/^[\u3400-\u9fff\uf900-\ufaff]{2}$/.test(token)) type = 'cjk_bigram'
260
+ else if (/^[\u3400-\u9fff\uf900-\ufaff]{3}$/.test(token)) type = 'cjk_trigram'
261
+ else if (/^[\u3400-\u9fff\uf900-\ufaff]{4,}$/.test(token)) type = 'cjk_run'
262
+ else if (/^[a-z0-9]+$/i.test(token)) type = 'english'
263
+
264
+ byType.set(type, (byType.get(type) || 0) + 1)
265
+ }
266
+
267
+ return {
268
+ total: tokens.length,
269
+ byType: Object.fromEntries(byType),
270
+ }
271
+ }
272
+
273
+ // —— 测试场景清单(tests/tokenizer-v2.test.mjs 引用)——
274
+
275
+ /**
276
+ * Test cases for different scenarios
277
+ */
278
+ export const TEST_CASES = [
279
+ {
280
+ input: '人工智能是一种技术',
281
+ description: '纯中文短句',
282
+ },
283
+ {
284
+ input: '2026-11-05 AI 技术在快速发展',
285
+ description: '混合日期、英文缩写和中文',
286
+ },
287
+ {
288
+ input: 'Qwen3-Embedding 在 2026 年发布',
289
+ description: '混合产品名、年份和中文',
290
+ },
291
+ {
292
+ input: 'user@example.com 访问 https://example.com',
293
+ description: '邮箱和 URL',
294
+ },
295
+ ]