dsh-memu-memory 1.2.8 → 1.2.9

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +472 -0
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/lib/backup.js +154 -25
  5. package/lib/binding-diagnostics.js +1 -2
  6. package/lib/budget.js +0 -9
  7. package/lib/client.js +221 -128
  8. package/lib/commitment.js +3 -3
  9. package/lib/consolidation-ledger.js +5 -2
  10. package/lib/curator-policy.js +23 -0
  11. package/lib/cycle.js +8 -4
  12. package/lib/embedding-download.js +168 -28
  13. package/lib/embedding-runtime.js +76 -17
  14. package/lib/engine.js +0 -6
  15. package/lib/freshness.js +2 -2
  16. package/lib/graph.js +139 -11
  17. package/lib/index.js +71 -20
  18. package/lib/inject.js +50 -7
  19. package/lib/lexicon.js +61 -16
  20. package/lib/local-vector-service.js +21 -1
  21. package/lib/media.js +49 -12
  22. package/lib/memory.js +662 -116
  23. package/lib/paths.js +0 -7
  24. package/lib/preset-scope.js +6 -1
  25. package/lib/private.js +45 -7
  26. package/lib/prompts.js +0 -7
  27. package/lib/rpc.js +95 -17
  28. package/lib/snippet.js +18 -2
  29. package/lib/state.js +109 -30
  30. package/lib/stats.js +2 -2
  31. package/lib/temporal.js +19 -0
  32. package/lib/text-retrieval.js +120 -44
  33. package/lib/text-similarity.js +205 -24
  34. package/lib/tokenizer-v2.js +0 -24
  35. package/lib/vector-migration.js +15 -0
  36. package/lib/vector-profile.js +81 -8
  37. package/lib/visibility.js +0 -4
  38. package/lib/webui/standalone.css +17 -22
  39. package/lib/webui/standalone.js +27 -9
  40. package/lib/webui.js +4 -4
  41. package/package.json +3 -2
  42. package/scripts/acceptance-local.mjs +2 -2
  43. package/scripts/check-all.mjs +3 -1
  44. package/scripts/check-i18n.mjs +35 -1
  45. package/scripts/migrate-visibility.mjs +3 -3
  46. package/scripts/prune-sessions.mjs +34 -0
  47. package/scripts/prune-vectors.mjs +24 -0
  48. package/tests/appendix-b.test.mjs +5 -4
  49. package/tests/audit-batch3.test.mjs +247 -0
  50. package/tests/audit-regression.test.mjs +2 -2
  51. package/tests/backup.test.mjs +83 -83
  52. package/tests/browser.test.mjs +6 -1
  53. package/tests/client-render.test.mjs +2 -2
  54. package/tests/curator-clusters.test.mjs +18 -0
  55. package/tests/curator-pairing.test.mjs +59 -16
  56. package/tests/dynamic-rrf.test.mjs +22 -19
  57. package/tests/dynamic-threshold.test.mjs +52 -0
  58. package/tests/fact-version.test.mjs +18 -0
  59. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  60. package/tests/graph-cascade.test.mjs +29 -0
  61. package/tests/graph.test.mjs +45 -0
  62. package/tests/inject-conflict.test.mjs +18 -0
  63. package/tests/lexical-bm25.test.mjs +171 -0
  64. package/tests/lexicon-frequency.test.mjs +16 -0
  65. package/tests/lexicon-inject.test.mjs +21 -0
  66. package/tests/lexicon-perf.test.mjs +37 -9
  67. package/tests/lexicon-scope.test.mjs +2 -2
  68. package/tests/lexicon-ui.test.mjs +1 -1
  69. package/tests/managed-memory.test.mjs +19 -0
  70. package/tests/ops-hardening.test.mjs +209 -0
  71. package/tests/package-shipping.test.mjs +4 -0
  72. package/tests/recall-intent.test.mjs +23 -0
  73. package/tests/slot-similarity.test.mjs +153 -0
  74. package/tests/state-gc.test.mjs +34 -0
  75. package/tests/state.test.mjs +2 -2
  76. package/tests/tokenizer-v2.test.mjs +1 -1
  77. package/tests/vector-gc.test.mjs +37 -0
  78. package/tests/webui.test.mjs +27 -0
package/lib/stats.js CHANGED
@@ -8,6 +8,7 @@
8
8
  import fs from 'node:fs'
9
9
  import path from 'node:path'
10
10
  import { indexDir, readJsonStrict, writeJson, withFileLock, warn, isSafeId } from './paths.js'
11
+ import { localCalendarDay } from './temporal.js'
11
12
 
12
13
  export const STATS_KEPT_DAYS = 90
13
14
  export const STATS_KINDS = ['written', 'injected', 'recalled', 'archived']
@@ -56,8 +57,7 @@ export function loadStats(libraryId) {
56
57
  }
57
58
 
58
59
  function dayKey(now) {
59
- const date = new Date(now)
60
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
60
+ return localCalendarDay(now)
61
61
  }
62
62
 
63
63
  function keepWindow(days, keptDays) {
package/lib/temporal.js CHANGED
@@ -326,4 +326,23 @@ export function localDateKeyInZone(value = new Date(), timeZone = DEFAULT_TIME_Z
326
326
  return formatDate(zonedCalendar(instantOf(value), timeZone))
327
327
  }
328
328
 
329
+ /**
330
+ * 宿主本地的日历日(YYYY-MM-DD)。
331
+ *
332
+ * 这一行原来在 state / stats / freshness / commitment / salient-wake / inject /
333
+ * memory 里各写了一遍(8 处,padStart 与 pad2 两种风格混用,其中一处漏了补零)。
334
+ * 它们算的是同一件事,只是各写各的;统一到这里以后,「本地日历日」只有一种写法。
335
+ *
336
+ * 与 localDateKeyInZone 的分工是**有意的**,不是重复实现:那个按指定时区算,用于
337
+ * 解析记忆文本里的相对日期(默认 Asia/Shanghai,见 DEFAULT_TIME_ZONE);这个按宿主
338
+ * 时区算,用于「今天 / 连续多少天 / 统计桶」这类必须跟着用户本地时钟走的口径。两者
339
+ * 在 UTC+8 上一致,在别的时区会相差一天——这条口径差目前是已知未收敛项,改动它等于
340
+ * 改产品语义,不在这次清理范围内。
341
+ */
342
+ export function localCalendarDay(value = new Date()) {
343
+ const date = value instanceof Date ? value : new Date(value)
344
+ const at = Number.isFinite(date.getTime()) ? date : new Date()
345
+ return `${at.getFullYear()}-${pad2(at.getMonth() + 1)}-${pad2(at.getDate())}`
346
+ }
347
+
329
348
  export { DEFAULT_TIME_ZONE, DAY_MS }
@@ -15,12 +15,15 @@
15
15
  import {
16
16
  bigrams,
17
17
  dice,
18
+ jaccard,
18
19
  lengthGap,
19
20
  similarityDetail,
20
21
  similarTexts,
21
22
  } from './text-similarity.js'
22
23
  import {
23
24
  BM25_B,
25
+ BM25_DF_MIN_POOL,
26
+ BM25_DF_RATIO,
24
27
  BM25_K1,
25
28
  BM25_MAX_QUERY_TERMS,
26
29
  BLOCK_DF_RATIO,
@@ -28,6 +31,7 @@ import {
28
31
  CLUSTER_EXACT_PAIR_LIMIT,
29
32
  CLUSTER_MAX,
30
33
  CLUSTER_MAX_MEMBERS,
34
+ CLUSTER_MAX_PAIRS,
31
35
  CLUSTER_MIN_PAIR,
32
36
  CLUSTER_RECENT_LIMIT,
33
37
  CROSS_DOMAIN_LINK_MIN,
@@ -162,41 +166,57 @@ function idfOf(corpus, term) {
162
166
  }
163
167
 
164
168
  /**
165
- * Verbatim §4.1 formula. Queries wider than BM25_MAX_QUERY_TERMS keep only the
166
- * 64 highest-IDF terms — measured among terms the corpus actually knows
167
- * (df > 0): an absent term scores 0 no matter its nominal IDF, so letting it
168
- * occupy the quota would only shrink the effective query. Ties break by term.
169
+ * §4.1 BM25 formula with the query-side frequency gate (A-2)。
170
+ *
171
+ * 每个 query term 独立判定,df 超过 dfCap 就整条不参与打分,其中
172
+ * dfCap = max(BM25_DF_MIN_POOL, ceil(BM25_DF_RATIO × N))。
173
+ * 只看占比会在极小语料上把查询词剔光(12 条记忆都含「会议」→ 占比 100% → 召回
174
+ * 0 条,实测回归),所以下限取「一次召回至少会看的候选数」;只看绝对数又会把
175
+ * 「20000 条里 100 条」这种真正有区分度的词误杀。V2 的 CJK unigram 让「的」「了」
176
+ * 在小库和大库上都会撞线。
177
+ * 剔除的是整个 term,不是把它的分数清零后继续保留条目:后者只换来一个恒定 0
178
+ * 分的候选,候选池照样是全库。
179
+ *
180
+ * qtf(A-12):query 侧保留重复 term 的频率并乘进分数。qtf=1 时与旧口径逐位
181
+ * 相同,所以既有的精确数值断言不受影响;重复查询词只会放大它自己的贡献,不会
182
+ * 倒挂 IDF——真正的高频词在闸门处已经被剔除。
183
+ *
184
+ * Queries wider than BM25_MAX_QUERY_TERMS keep only the 64 highest-IDF terms —
185
+ * measured among terms the corpus actually knows (df > 0): an absent term scores
186
+ * 0 no matter its nominal IDF, so letting it occupy the quota would only shrink
187
+ * the effective query. Ties break by term.
169
188
  */
170
189
  export function bm25(queryTokens, doc, corpus, { k1 = BM25_K1, b = BM25_B } = {}) {
171
190
  if (!queryTokens?.length || !doc || !corpus || corpus.size === 0) return 0
172
- let terms = [...new Set(queryTokens)].filter((term) => corpus.df.has(term))
191
+ const qtf = new Map()
192
+ for (const term of queryTokens) {
193
+ if (!corpus.df.has(term)) continue
194
+ qtf.set(term, (qtf.get(term) || 0) + 1)
195
+ }
196
+ if (qtf.size === 0) return 0
197
+ const dfCap = Math.max(BM25_DF_MIN_POOL, Math.ceil(BM25_DF_RATIO * corpus.size))
198
+ let terms = []
199
+ for (const [term, count] of qtf) {
200
+ if ((corpus.df.get(term) || 0) > dfCap) continue
201
+ terms.push({ term, qtf: count, idf: idfOf(corpus, term) })
202
+ }
173
203
  if (terms.length === 0) return 0
174
204
  if (terms.length > BM25_MAX_QUERY_TERMS) {
175
205
  terms = terms
176
- .map((term) => ({ term, idf: idfOf(corpus, term) }))
177
206
  .sort((a, b2) => b2.idf - a.idf || (a.term < b2.term ? -1 : 1))
178
207
  .slice(0, BM25_MAX_QUERY_TERMS)
179
- .map((item) => item.term)
180
208
  }
181
209
  let score = 0
182
- for (const term of terms) {
210
+ for (const { term, qtf: count, idf } of terms) {
183
211
  const tf = doc.tf.get(term) || 0
184
212
  if (!tf) continue
185
- const idf = idfOf(corpus, term)
186
- score += idf * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * doc.len / corpus.avgdl))
213
+ score += idf * count * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * doc.len / corpus.avgdl))
187
214
  }
188
215
  return score
189
216
  }
190
217
 
191
218
  // —— §4.2 成对特征 ——
192
219
 
193
- function jaccard(a, b) {
194
- if (a.size === 0 || b.size === 0) return 0
195
- let shared = 0
196
- for (const item of a) if (b.has(item)) shared += 1
197
- return shared / (a.size + b.size - shared)
198
- }
199
-
200
220
  function entitySet(appliesTo) {
201
221
  const out = new Set()
202
222
  for (const item of Array.isArray(appliesTo) ? appliesTo : []) {
@@ -390,7 +410,7 @@ export function numericSetsDiffer(a, b) {
390
410
  * 子串包含关系(clause.includes(anchor))——锚点本身就是文本的子串,CJK
391
411
  * unigram/bigram 与 latin 词都覆盖。无共享词返回 ''(调用方回退整文本口径)。
392
412
  */
393
- function longestSharedToken(aBody, bBody) {
413
+ export function longestSharedToken(aBody, bBody) {
394
414
  const bTokens = new Set(tokenize(bBody))
395
415
  let anchor = ''
396
416
  for (const token of new Set(tokenize(aBody))) {
@@ -440,6 +460,37 @@ function idAsc(a, b) {
440
460
  return String(a.id).localeCompare(String(b.id))
441
461
  }
442
462
 
463
+ /**
464
+ * 标准竞赛排名(1,2,2,4):并列分数共享同一名次,后续名次跳号。
465
+ * metricOf 返回参与并列判定的值(数组按值拼成键)——排序里的 id/键 tiebreak
466
+ * 只负责让输出完全确定,不再把同分文档强行排成不同名次。RRF 是按名次加权
467
+ * 融合的,给并列者不同名次等于凭空制造分差。
468
+ */
469
+ function competitionRanks(sorted, metricOf) {
470
+ const ranks = new Map()
471
+ let previous = null
472
+ let rank = 0
473
+ sorted.forEach((item, index) => {
474
+ const metric = metricOf(item)
475
+ const key = Array.isArray(metric) ? metric.join('\u0000') : String(metric)
476
+ if (key !== previous) {
477
+ rank = index + 1
478
+ previous = key
479
+ }
480
+ ranks.set(item.id ?? item.key, rank)
481
+ })
482
+ return ranks
483
+ }
484
+
485
+ /** 两个 token 集的交集大小(不构造第三个集合):blocking 的便宜预筛。 */
486
+ function sharedTokenCount(a, b) {
487
+ if (!a || !b || a.size === 0 || b.size === 0) return 0
488
+ const [small, large] = a.size <= b.size ? [a, b] : [b, a]
489
+ let shared = 0
490
+ for (const token of small) if (large.has(token)) shared += 1
491
+ return shared
492
+ }
493
+
443
494
  /**
444
495
  * §4.3 rankPairCandidates({ corpus, proposal, limit })。
445
496
  *
@@ -514,8 +565,7 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
514
565
  const ids = [...candidates.keys()]
515
566
  const bm25Scores = ids.map((id) => ({ id, s: bm25(queryTokens, corpus.docs.get(id), corpus) }))
516
567
  bm25Scores.sort((a, b) => b.s - a.s || idAsc(a, b))
517
- const rankBm25 = new Map()
518
- bm25Scores.forEach((item, index) => rankBm25.set(item.id, index + 1))
568
+ const rankBm25 = competitionRanks(bm25Scores, (item) => item.s)
519
569
 
520
570
  const probes = ids.map((id) => {
521
571
  const doc = corpus.docs.get(id)
@@ -523,8 +573,9 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
523
573
  return { id, diceScore: detail.dice, containment: detail.containment, lexical: Math.max(detail.dice, detail.containment) }
524
574
  })
525
575
  const diceRankOrder = [...probes].sort((a, b) => b.diceScore - a.diceScore || b.containment - a.containment || idAsc(a, b))
526
- const rankDice = new Map()
527
- diceRankOrder.forEach((item, index) => rankDice.set(item.id, index + 1))
576
+ // 并列按 (diceScore, containment) 判定:两个分量都相同才算同分,id 只是
577
+ // 输出顺序的确定性 tiebreak。
578
+ const rankDice = competitionRanks(diceRankOrder, (item) => [item.diceScore, item.containment])
528
579
 
529
580
  const entityOrder = ids.map((id) => {
530
581
  const doc = corpus.docs.get(id)
@@ -534,8 +585,7 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
534
585
  containment: containmentOf(proposal, doc.entry),
535
586
  }
536
587
  }).sort((a, b) => b.entity - a.entity || b.containment - a.containment || idAsc(a, b))
537
- const rankEntity = new Map()
538
- entityOrder.forEach((item, index) => rankEntity.set(item.id, index + 1))
588
+ const rankEntity = competitionRanks(entityOrder, (item) => [item.entity, item.containment])
539
589
 
540
590
  // 3) weighted RRF。开关关 → 静态三路原式(字节级回退路径);开 → 权重来自
541
591
  // computeRRFWeights,含 recency 键时加第四路 updatedAt 降序排名。
@@ -556,7 +606,8 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
556
606
  const recencyOrder = ids
557
607
  .map((id) => ({ id, entry: corpus.docs.get(id).entry }))
558
608
  .sort((a, b) => updatedDesc(a.entry, b.entry) || idAsc(a, b))
559
- recencyOrder.forEach((item, index) => rankRecency.set(item.id, index + 1))
609
+ const ranked = competitionRanks(recencyOrder, (item) => String(item.entry?.updatedAt || ''))
610
+ for (const [id, rank] of ranked) rankRecency.set(id, rank)
560
611
  }
561
612
  rrf = new Map()
562
613
  for (const id of ids) {
@@ -638,9 +689,11 @@ function round2(value) {
638
689
  * §4.4 buildCandidateClusters(index, options)。
639
690
  *
640
691
  * 1) active 条目按 updatedAt 降序取最近 recentLimit(2000) 条,按 track 分组。
641
- * 2) 同 track 内:N ≤ exactPairLimit(300) 全对;否则倒排 blocking(共享
642
- * ≥ blockMinShared(2) token)。
643
- * 3) 候选对算 pairFeatures/pairScore,保留 ≥ minPairScore(0.55) 的边。
692
+ * 2) 同 track 内:N ≤ exactPairLimit(300) 全对;否则倒排 blocking(df ≤
693
+ * 30%N 的 posting、共享 ≥ blockMinShared(2) token,收集总量 ≤
694
+ * CLUSTER_MAX_PAIRS 的硬上限)。
695
+ * 3) 共享 token 为 0 的对先被预筛,其余算 pairFeatures/pairScore,保留
696
+ * ≥ minPairScore(0.55) 的边。
644
697
  * 4) 边排序用三路 RRF(同 §4.3:bm25 双向和 / charDice / entityJaccard)。
645
698
  * 5) 贪心成簇:边按 RRF 降序;种子=边两端;新成员必须与簇内**所有**成员
646
699
  * pairScore ≥ 0.55(全对约束,禁传递闭包);每簇 ≤6;每条目只进一个簇。
@@ -679,13 +732,18 @@ export function buildCandidateClusters(index, options = {}) {
679
732
  const n = items.length
680
733
  if (n < 2) continue
681
734
  const tokenSets = new Map()
735
+ const streams = new Map()
682
736
  const inverted = new Map()
683
737
  for (const item of items) {
684
738
  // blocking 倒排固定 V1 口径(idf 盲集合运算):unigram 会把高频单字灌大
685
739
  // 倒排与两两共享计数(N=500 簇延迟 +60% 的根因),对成簇质量无收益。
686
740
  // 边打分的 BM25 路由(下方 bm25Route/buildCorpus)仍走 V2 流。
687
- const tokens = tokenizeV1(`${item.entry?.title || ''} ${item.entry?.content || ''}`)
741
+ const text = `${item.entry?.title || ''} ${item.entry?.content || ''}`
742
+ const tokens = tokenizeV1(text)
688
743
  tokenSets.set(item.id, new Set(tokens))
744
+ // BM25 流只算一次:pairList 里同一条目会出现在许多对中,逐对重算
745
+ // tokenStream 是另一份 O(N²) 的浪费。
746
+ streams.set(item.id, tokenStream(text))
689
747
  for (const term of tokens) {
690
748
  if (!inverted.has(term)) inverted.set(term, [])
691
749
  inverted.get(term).push(item.id)
@@ -698,13 +756,28 @@ export function buildCandidateClusters(index, options = {}) {
698
756
  for (let j = i + 1; j < n; j++) pairSet.add(pairKey(items[i].id, items[j].id))
699
757
  }
700
758
  } else {
759
+ // 倒排层剪枝(A-1):与 rankPairCandidates 同口径的 dfCap。中文常用字
760
+ // bigram 的 posting 几乎覆盖全库,不剪枝时每个 posting 都展开成 N²/2 个
761
+ // 对——这才是 N=500 要 5.8s 的根因,不是 similarityDetail 本身慢。
762
+ // 被跳过的是整条 posting(倒排表层面的剪枝),不涉及候选门槛。
763
+ const dfCap = Math.ceil(BLOCK_DF_RATIO * n)
701
764
  const shared = new Map()
702
- for (const posting of inverted.values()) {
703
- if (posting.length < 2) continue
765
+ // 硬上限(CLUSTER_MAX_PAIRS)是防御性的:df 剪枝之后仍可能有大量中等
766
+ // 频率词留下 O(N²) 的对,超过上限就停止收集**新**对(已收集的计数继续
767
+ // 累加)。倒排按条目插入序遍历,截断位置确定 → 输出仍可复现。上限必须在
768
+ // 内层检查:单个 posting(≤dfCap 条)自身就可能超过它。
769
+ collectPairs: for (const posting of inverted.values()) {
770
+ if (posting.length < 2 || posting.length > dfCap) continue
704
771
  for (let i = 0; i < posting.length; i++) {
705
772
  for (let j = i + 1; j < posting.length; j++) {
706
773
  const key = pairKey(posting[i], posting[j])
707
- shared.set(key, (shared.get(key) || 0) + 1)
774
+ const count = shared.get(key)
775
+ if (count === undefined) {
776
+ if (shared.size >= CLUSTER_MAX_PAIRS) break collectPairs
777
+ shared.set(key, 1)
778
+ } else {
779
+ shared.set(key, count + 1)
780
+ }
708
781
  }
709
782
  }
710
783
  }
@@ -715,36 +788,39 @@ export function buildCandidateClusters(index, options = {}) {
715
788
  if (pairSet.size === 0) continue
716
789
 
717
790
  const corpus = buildCorpus(items.map((item) => ({ id: item.id, title: item.entry?.title || '', content: item.entry?.content || '', entry: item.entry })))
718
- const pairList = [...pairSet].map((key) => {
791
+ // 便宜预筛:共享 token 为 0 的对直接跳过,连 similarityDetail(bigram 集
792
+ // 构建 + 长度探针)都不进。它只剔除没有任何共享词元(V1 口径)的候选,
793
+ // 不降低最终 pairScore 门槛。
794
+ const pairList = []
795
+ for (const key of pairSet) {
719
796
  const [aId, bId] = key.split('\u0000')
720
797
  const aItem = byId.get(aId)
721
798
  const bItem = byId.get(bId)
799
+ if (sharedTokenCount(tokenSets.get(aId), tokenSets.get(bId)) === 0) continue
722
800
  const features = pairFeatures(aItem.entry, bItem.entry)
723
801
  const score = pairScore(features)
724
- return { key, aId, bId, aItem, bItem, features, score }
725
- }).filter((pair) => pair.score >= minPair)
802
+ if (score < minPair) continue
803
+ pairList.push({ key, aId, bId, aItem, bItem, features, score })
804
+ }
726
805
  if (pairList.length === 0) continue
727
806
 
728
807
  // three route rankings for edge order only。
729
808
  // 刻意不做动态权重(P0-2 只落在 rankPairCandidates):buildCandidateClusters
730
809
  // 没有 proposal/查询上下文——它是无监督的全库成簇,三路 RRF 只决定贪心
731
810
  // 长簇的边访问顺序;引入「查询类型」没有语义落点,静态三路保证簇构建
732
- // 与查询无关、完全可复现。
811
+ // 与查询无关、完全可复现。并列分数共享同一名次(A-12)。
733
812
  const bm25Route = pairList.map((pair) => ({
734
813
  key: pair.key,
735
- s: bm25(tokenStream(`${pair.aItem.entry?.title || ''} ${pair.aItem.entry?.content || ''}`), corpus.docs.get(pair.bId), corpus)
736
- + bm25(tokenStream(`${pair.bItem.entry?.title || ''} ${pair.bItem.entry?.content || ''}`), corpus.docs.get(pair.aId), corpus),
814
+ s: bm25(streams.get(pair.aId), corpus.docs.get(pair.bId), corpus)
815
+ + bm25(streams.get(pair.bId), corpus.docs.get(pair.aId), corpus),
737
816
  })).sort((a, b) => b.s - a.s || (a.key < b.key ? -1 : 1))
738
- const rankBm25 = new Map()
739
- bm25Route.forEach((item, i) => rankBm25.set(item.key, i + 1))
817
+ const rankBm25 = competitionRanks(bm25Route, (item) => item.s)
740
818
  const diceRoute = [...pairList].sort((a, b) => b.features.charDice - a.features.charDice
741
819
  || b.features.containment - a.features.containment || (a.key < b.key ? -1 : 1))
742
- const rankDice = new Map()
743
- diceRoute.forEach((item, i) => rankDice.set(item.key, i + 1))
820
+ const rankDice = competitionRanks(diceRoute, (item) => [item.features.charDice, item.features.containment])
744
821
  const entityRoute = [...pairList].sort((a, b) => b.features.entityJaccard - a.features.entityJaccard
745
822
  || b.features.containment - a.features.containment || (a.key < b.key ? -1 : 1))
746
- const rankEntity = new Map()
747
- entityRoute.forEach((item, i) => rankEntity.set(item.key, i + 1))
823
+ const rankEntity = competitionRanks(entityRoute, (item) => [item.features.entityJaccard, item.features.containment])
748
824
  for (const pair of pairList) {
749
825
  pair.rrf = RRF_W_BM25 / (RRF_K + rankBm25.get(pair.key))
750
826
  + RRF_W_DICE / (RRF_K + rankDice.get(pair.key))
@@ -8,16 +8,37 @@
8
8
  // whitespace/punctuation/symbols), so findConflict's behaviour is unchanged by
9
9
  // this extraction.
10
10
 
11
+ // —— 相似度阈值的唯一表(A-10)——
12
+ // 本文件是「相似度尺度」阈值的唯一来源:Dice 分带、长度剪枝比、包含探针的下限与
13
+ // 窗口都在 SIMILARITY_THRESHOLDS 里。curator-policy.js 只消费这些常量来组成策展
14
+ // 策略(absorb/link/duplicate 的落点),不自己内联相似度数字。
15
+ // 下面的具名常量是兼容导出:调用点全部按名字 import,数值与语义保持不变。
16
+ export const SIMILARITY_THRESHOLDS = Object.freeze({
17
+ // 同一事实:召回簇只留一条候选,MMR 硬跳过其余。
18
+ duplicateDice: 0.82,
19
+ // 写入侧拒绝:新记忆与已有记忆近到这个程度直接拒绝。
20
+ rejectDice: 0.90,
21
+ // 同主题不同事实:召回侧软惩罚带,写入侧打 duplicateOf 标签。
22
+ topicDice: 0.55,
23
+ // 写入侧剪枝:长度差超过较长者这个比例就跳过 bigram 全套计算。
24
+ lengthPruneRatio: 0.5,
25
+ // 长度悬殊时的包含探针下限(逐字包含)。
26
+ containmentFloor: 0.92,
27
+ // 探针窗口:短文本清洗后低于 MIN 信号不足,高于 MAX 超出探针预算。
28
+ probeMinChars: 6,
29
+ probeMaxChars: 240,
30
+ })
31
+
11
32
  // Same fact: a recall cluster keeps one candidate, MMR hard-skips the rest.
12
- export const DUP_DICE = 0.82
33
+ export const DUP_DICE = SIMILARITY_THRESHOLDS.duplicateDice
13
34
  // Write-side reject: a new memory this close to an existing one is refused.
14
- export const DUP_REJECT_DICE = 0.90
35
+ export const DUP_REJECT_DICE = SIMILARITY_THRESHOLDS.rejectDice
15
36
  // Same topic, different fact: soft-penalty band on recall, duplicateOf tag on write.
16
- export const TOPIC_DICE = 0.55
37
+ export const TOPIC_DICE = SIMILARITY_THRESHOLDS.topicDice
17
38
  // Write-side pruning: skip the bigram pass when two texts differ in length by more
18
39
  // than this fraction of the longer one. At this ratio Dice cannot reach the reject
19
40
  // band even with zero unique bigrams on the short side.
20
- export const LENGTH_PRUNE_RATIO = 0.5
41
+ export const LENGTH_PRUNE_RATIO = SIMILARITY_THRESHOLDS.lengthPruneRatio
21
42
 
22
43
  // Length-disparate pairs (gap > LENGTH_PRUNE_RATIO) do not go through Dice — the
23
44
  // ratio math makes a reject-band Dice impossible, which is exactly the hole a
@@ -34,15 +55,15 @@ export const LENGTH_PRUNE_RATIO = 0.5
34
55
  // reports 0: with a >0.5 length gap there is no honest way to say "same topic",
35
56
  // and a false reject on the write side is worse than a rare paraphrase bypass —
36
57
  // the residual risk (heavily reworded padding) is documented in
37
- export const CONTAINMENT_FLOOR = 0.92
38
- export const CORE_COVER_FLOOR = DUP_REJECT_DICE
58
+ export const CONTAINMENT_FLOOR = SIMILARITY_THRESHOLDS.containmentFloor
59
+ export const CORE_COVER_FLOOR = SIMILARITY_THRESHOLDS.rejectDice
39
60
  // Below this many cleaned characters the probe has too little signal (a 4-char
40
61
  // string and its bigrams occur in unrelated texts all the time); above the max the
41
62
  // probe budget is exceeded and both sides are substantial enough to trust the
42
63
  // length prune again. Bounds keep the write-side gate O(|short|·|long|) native
43
64
  // scans per pruned pair instead of O(N²) bigram-set construction.
44
- const PROBE_MIN_CHARS = 6
45
- const PROBE_MAX_CHARS = 240
65
+ export const PROBE_MIN_CHARS = SIMILARITY_THRESHOLDS.probeMinChars
66
+ export const PROBE_MAX_CHARS = SIMILARITY_THRESHOLDS.probeMaxChars
46
67
 
47
68
  /** The one text preprocessing every measurement here shares. */
48
69
  export function clean(text) {
@@ -57,6 +78,137 @@ export function bigrams(text) {
57
78
  return out
58
79
  }
59
80
 
81
+ // —— Slot guard ——
82
+ //
83
+ // Dice over character bigrams cannot tell "五本" from "七本", "11-08" from
84
+ // "11-15", or "喜欢" from "不喜欢": the sentences are otherwise identical, so a
85
+ // revised fact looks like a paraphrased duplicate and gets refused/folded. The
86
+ // slot signature compares only the parts that change the claim: numbers, dates,
87
+ // times, weekdays and quoted names. If both sides carry the same slot type and
88
+ // disagree, the pair is a different fact; the score is capped below the topic
89
+ // band so it cannot be rejected, tagged duplicateOf, or folded in recall.
90
+ // Unquoted Chinese personal names still need NER; quoted/@ names are covered.
91
+ // Predicate negation stays with findConflict, whose clause-level check already
92
+ // decides "likes" vs "doesn't like" without mistaking "免费" / "不用付费" for a
93
+ // contradiction.
94
+
95
+ const SLOT_DATE_RE = /(?:\d{4}[-/]\d{1,2}[-/]\d{1,2})|(?:\d{1,2}月\d{1,2}[日号]?)/g
96
+ const SLOT_TIME_RE = /(?:\d{1,2}[::]\d{2})|(?:\d{1,2}点(?:\d{1,2}分|半)?)/g
97
+ const SLOT_WEEKDAY_RE = /(?:周|星期|礼拜)[一二三四五六日天1-7]/g
98
+ const SLOT_NUMBER_RE = /\d+(?:\.\d+)?/g
99
+ const SLOT_CN_NUMBER_RE = /[零一二三四五六七八九十百千万亿两]+(?=本|个|次|天|月|日|号|岁|年|点|分|元|块|张|条|人|位|小时|分钟|周|份|杯|瓶|只|家|件|场|门|层|楼|页)/g
100
+ const SLOT_QUOTED_RE = /["“”「」『』]([^"“”「」『』]{2,30})["“”「」『』]/g
101
+ const SLOT_AT_RE = /@([\w\u4e00-\u9fff-]{2,30})/g
102
+
103
+ const CN_DIGITS = { 零: 0, 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 }
104
+ const CN_UNITS = { 十: 10, 百: 100, 千: 1000, 万: 10000, 亿: 100000000 }
105
+ const WEEKDAY_NUMBER = { 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 日: 7, 天: 7, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7 }
106
+
107
+ function pad2(value) {
108
+ return String(value).padStart(2, '0')
109
+ }
110
+
111
+ function chineseNumber(text) {
112
+ let total = 0
113
+ let section = 0
114
+ let number = 0
115
+ for (const char of String(text || '')) {
116
+ if (CN_DIGITS[char] !== undefined) {
117
+ number = CN_DIGITS[char]
118
+ continue
119
+ }
120
+ const unit = CN_UNITS[char]
121
+ if (unit === undefined) return null
122
+ if (unit >= 10000) {
123
+ section = (section + number) * unit
124
+ total += section
125
+ section = 0
126
+ number = 0
127
+ } else {
128
+ section += (number || 1) * unit
129
+ number = 0
130
+ }
131
+ }
132
+ return total + section + number
133
+ }
134
+
135
+ function normalizeNumber(raw) {
136
+ if (/^\d+(?:\.\d+)?$/.test(raw)) {
137
+ const value = Number(raw)
138
+ return Number.isFinite(value) ? String(value) : raw
139
+ }
140
+ const value = chineseNumber(raw)
141
+ return value === null ? raw : String(value)
142
+ }
143
+
144
+ function normalizeDate(raw) {
145
+ const absolute = /^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/.exec(raw)
146
+ if (absolute) return `${absolute[1]}-${pad2(absolute[2])}-${pad2(absolute[3])}`
147
+ const monthDay = /^(\d{1,2})月(\d{1,2})[日号]?$/.exec(raw)
148
+ if (monthDay) return `${pad2(monthDay[1])}-${pad2(monthDay[2])}`
149
+ return raw
150
+ }
151
+
152
+ function normalizeTime(raw) {
153
+ const colon = /^(\d{1,2})[::](\d{2})$/.exec(raw)
154
+ if (colon) return `${pad2(colon[1])}:${colon[2]}`
155
+ const dot = /^(\d{1,2})点(?:(\d{1,2})分|半)?$/.exec(raw)
156
+ if (!dot) return raw
157
+ const minute = dot[2] !== undefined ? pad2(dot[2]) : (raw.endsWith('半') ? '30' : '00')
158
+ return `${pad2(dot[1])}:${minute}`
159
+ }
160
+
161
+ function normalizeWeekday(raw) {
162
+ const char = raw.slice(-1)
163
+ const day = WEEKDAY_NUMBER[char]
164
+ return day === undefined ? raw : `weekday:${day}`
165
+ }
166
+
167
+ function unique(values) {
168
+ return [...new Set(values.filter(Boolean))]
169
+ }
170
+
171
+ /** The slots that can change what a sentence claims, without changing its shape. */
172
+ export function slotSignature(text) {
173
+ const value = String(text || '')
174
+ const numbers = []
175
+ for (const match of value.matchAll(SLOT_NUMBER_RE)) numbers.push(normalizeNumber(match[0]))
176
+ for (const match of value.matchAll(SLOT_CN_NUMBER_RE)) numbers.push(normalizeNumber(match[0]))
177
+ const dates = [...value.matchAll(SLOT_DATE_RE)].map((match) => normalizeDate(match[0]))
178
+ const times = [...value.matchAll(SLOT_TIME_RE)].map((match) => normalizeTime(match[0]))
179
+ const weekdays = [...value.matchAll(SLOT_WEEKDAY_RE)].map((match) => normalizeWeekday(match[0]))
180
+ const quoted = []
181
+ for (const match of value.matchAll(SLOT_QUOTED_RE)) quoted.push(match[1].trim().toLowerCase())
182
+ for (const match of value.matchAll(SLOT_AT_RE)) quoted.push(match[1].trim().toLowerCase())
183
+ return {
184
+ numbers: unique(numbers),
185
+ dates: unique(dates),
186
+ times: unique(times),
187
+ weekdays: unique(weekdays),
188
+ quoted: unique(quoted),
189
+ }
190
+ }
191
+
192
+ function setDiffers(a, b) {
193
+ if (a.length === 0 || b.length === 0) return false
194
+ // An added number/date is an enrichment, not a contradiction: {2,4} vs
195
+ // {1,2,4} must not be capped. A replacement or a disjoint set is a different
196
+ // claim: {5} vs {7}, {2,4} vs {2,5}.
197
+ const aContainsB = b.every((value) => a.includes(value))
198
+ const bContainsA = a.every((value) => b.includes(value))
199
+ return !aContainsB && !bContainsA
200
+ }
201
+
202
+ /** True only when both sides carry a slot type and the values disagree. */
203
+ export function slotsConflict(a, b) {
204
+ if (!a || !b) return false
205
+ return setDiffers(a.numbers, b.numbers)
206
+ || setDiffers(a.dates, b.dates)
207
+ || setDiffers(a.times, b.times)
208
+ || setDiffers(a.weekdays, b.weekdays)
209
+ || setDiffers(a.quoted, b.quoted)
210
+ }
211
+
60
212
  /** Dice coefficient over two bigram sets; 0 when either side is empty. */
61
213
  export function dice(a, b) {
62
214
  if (a.size === 0 || b.size === 0) return 0
@@ -65,6 +217,17 @@ export function dice(a, b) {
65
217
  return (2 * shared) / (a.size + b.size)
66
218
  }
67
219
 
220
+ /**
221
+ * Set Jaccard;任一侧为空返回 0。与 text-retrieval 的 pairFeatures 同口径——
222
+ * 这里只提供一份实现,避免两处逐字重复后悄悄漂移。
223
+ */
224
+ export function jaccard(a, b) {
225
+ if (a.size === 0 || b.size === 0) return 0
226
+ let shared = 0
227
+ for (const item of a) if (b.has(item)) shared += 1
228
+ return shared / (a.size + b.size - shared)
229
+ }
230
+
68
231
  /** |len(A)-len(B)| / max(len); 0 when both sides are empty. */
69
232
  export function lengthGap(aText, bText) {
70
233
  const a = String(aText || '').length
@@ -88,26 +251,39 @@ export function similarityDetail(aText, bText) {
88
251
  const a = String(aText || '')
89
252
  const b = String(bText || '')
90
253
  const gap = lengthGap(a, b)
254
+ let diceScore = 0
255
+ let containment = 0
91
256
  if (gap > LENGTH_PRUNE_RATIO) {
92
257
  const aClean = clean(a)
93
258
  const bClean = clean(b)
94
- if (!aClean || !bClean) return { dice: 0, containment: 0, lengthGap: gap }
95
- const shortClean = aClean.length <= bClean.length ? aClean : bClean
96
- const longClean = aClean.length <= bClean.length ? bClean : aClean
97
- if (shortClean.length < PROBE_MIN_CHARS || shortClean.length > PROBE_MAX_CHARS) {
98
- return { dice: 0, containment: 0, lengthGap: gap }
259
+ if (aClean && bClean) {
260
+ const shortClean = aClean.length <= bClean.length ? aClean : bClean
261
+ const longClean = aClean.length <= bClean.length ? bClean : aClean
262
+ if (shortClean.length >= PROBE_MIN_CHARS && shortClean.length <= PROBE_MAX_CHARS) {
263
+ // Probe 1: verbatim containment of the short text inside the long one.
264
+ if (longClean.includes(shortClean)) {
265
+ containment = CONTAINMENT_FLOOR
266
+ } else {
267
+ // Probe 2: core coverage — every character bigram of the short text occurs
268
+ // somewhere in the long one. A miss fails fast on the first absent gram.
269
+ containment = CORE_COVER_FLOOR
270
+ for (let i = 0; i < shortClean.length - 1; i += 1) {
271
+ if (!longClean.includes(shortClean.slice(i, i + 2))) { containment = 0; break }
272
+ }
273
+ }
274
+ }
99
275
  }
100
- // Probe 1: verbatim containment of the short text inside the long one.
101
- if (longClean.includes(shortClean)) return { dice: 0, containment: CONTAINMENT_FLOOR, lengthGap: gap }
102
- // Probe 2: core coverage — every bigram of the short text occurs in the long
103
- // one; includes() over the cleaned long text is exactly long-bigram-set
104
- // membership, so no long-side set is ever built.
105
- for (let i = 0; i < shortClean.length - 1; i += 1) {
106
- if (!longClean.includes(shortClean.slice(i, i + 2))) return { dice: 0, containment: 0, lengthGap: gap }
107
- }
108
- return { dice: 0, containment: CORE_COVER_FLOOR, lengthGap: gap }
276
+ } else {
277
+ diceScore = dice(bigrams(a), bigrams(b))
109
278
  }
110
- return { dice: dice(bigrams(a), bigrams(b)), containment: 0, lengthGap: gap }
279
+ const raw = Math.max(diceScore, containment)
280
+ // Slot extraction is only paid for pairs that could actually be folded or
281
+ // rejected; the write gate scans a whole library on every write.
282
+ const slotConflict = raw >= TOPIC_DICE && slotsConflict(slotSignature(a), slotSignature(b))
283
+ // `raw` is the similarity on the shared ruler: max(dice, containment). Callers that
284
+ // only reason about "how similar are these two" must use it instead of `dice`,
285
+ // which reads 0 for every length-disparate pair by design.
286
+ return { dice: diceScore, containment, raw, lengthGap: gap, slotConflict }
111
287
  }
112
288
 
113
289
  /**
@@ -117,8 +293,13 @@ export function similarityDetail(aText, bText) {
117
293
  * max-similarity scan, so pruned pairs simply never become the best match —
118
294
  * unless they hit one of the two containment probes below, which are the only
119
295
  * way a length-disparate pair reaches the reject band.
296
+ *
297
+ * A hard slot disagreement caps the result below TOPIC_DICE: the pair is a
298
+ * different fact (five books vs seven, 11-08 vs 11-15, likes vs doesn't), so it
299
+ * must not be refused, tagged duplicateOf, or folded into one recall seat.
120
300
  */
121
301
  export function similarTexts(aText, bText) {
122
302
  const detail = similarityDetail(aText, bText)
123
- return Math.max(detail.dice, detail.containment)
303
+ const raw = Math.max(detail.dice, detail.containment)
304
+ return detail.slotConflict ? Math.min(raw, TOPIC_DICE - 1e-6) : raw
124
305
  }
@@ -269,27 +269,3 @@ export function tokenizeStats(text) {
269
269
  byType: Object.fromEntries(byType),
270
270
  }
271
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
- ]