dsh-memu-memory 1.2.7 → 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 (106) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +472 -0
  3. package/README.md +10 -15
  4. package/README.zh.md +10 -15
  5. package/docs/memory-semantics.md +23 -3
  6. package/lib/backup.js +155 -26
  7. package/lib/binding-diagnostics.js +1 -2
  8. package/lib/budget.js +31 -9
  9. package/lib/client.js +221 -128
  10. package/lib/commitment.js +138 -0
  11. package/lib/consolidation-ledger.js +5 -2
  12. package/lib/consolidation-receipt.js +2 -0
  13. package/lib/consolidation-worker.js +3 -0
  14. package/lib/curator-policy.js +23 -0
  15. package/lib/cycle.js +8 -4
  16. package/lib/embedding-download.js +168 -28
  17. package/lib/embedding-runtime.js +76 -17
  18. package/lib/engine.js +0 -6
  19. package/lib/freshness.js +24 -0
  20. package/lib/graph.js +139 -11
  21. package/lib/index.js +71 -20
  22. package/lib/inject.js +167 -17
  23. package/lib/lexicon.js +62 -17
  24. package/lib/local-vector-service.js +25 -2
  25. package/lib/media.js +49 -12
  26. package/lib/memory.js +1202 -123
  27. package/lib/memu.js +4 -0
  28. package/lib/paths.js +0 -7
  29. package/lib/preset-scope.js +6 -1
  30. package/lib/private.js +50 -10
  31. package/lib/prompts/private-consolidation.mixed.md +2 -2
  32. package/lib/prompts/private-consolidation.rp.md +6 -1
  33. package/lib/prompts/private-policy.rp.md +4 -0
  34. package/lib/prompts/system-guide.rp.md +3 -0
  35. package/lib/prompts.js +0 -7
  36. package/lib/recall-cache.js +10 -2
  37. package/lib/rpc.js +104 -19
  38. package/lib/snippet.js +41 -0
  39. package/lib/state.js +109 -30
  40. package/lib/stats.js +2 -2
  41. package/lib/temporal.js +348 -0
  42. package/lib/text-retrieval.js +191 -44
  43. package/lib/text-similarity.js +205 -24
  44. package/lib/tokenizer-v2.js +0 -24
  45. package/lib/tools.js +81 -4
  46. package/lib/vector-migration.js +15 -0
  47. package/lib/vector-profile.js +81 -8
  48. package/lib/visibility.js +0 -4
  49. package/lib/webui/standalone.css +17 -22
  50. package/lib/webui/standalone.js +27 -9
  51. package/lib/webui.js +4 -4
  52. package/package.json +3 -2
  53. package/scripts/acceptance-local.mjs +2 -2
  54. package/scripts/bench-recall.mjs +2 -2
  55. package/scripts/check-all.mjs +3 -1
  56. package/scripts/check-i18n.mjs +35 -1
  57. package/scripts/check-seed-compat.mjs +1 -1
  58. package/scripts/migrate-visibility.mjs +3 -3
  59. package/scripts/prune-sessions.mjs +34 -0
  60. package/scripts/prune-vectors.mjs +24 -0
  61. package/tests/appendix-b.test.mjs +5 -4
  62. package/tests/audit-batch3.test.mjs +247 -0
  63. package/tests/audit-regression.test.mjs +2 -2
  64. package/tests/backup.test.mjs +85 -85
  65. package/tests/browser.test.mjs +6 -1
  66. package/tests/client-render.test.mjs +2 -2
  67. package/tests/commitment.test.mjs +144 -0
  68. package/tests/consolidation-fork.test.mjs +3 -3
  69. package/tests/curator-clusters.test.mjs +18 -0
  70. package/tests/curator-pairing.test.mjs +59 -16
  71. package/tests/disclosure.test.mjs +34 -17
  72. package/tests/dynamic-rrf.test.mjs +22 -19
  73. package/tests/dynamic-threshold.test.mjs +52 -0
  74. package/tests/fact-version.test.mjs +146 -0
  75. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  76. package/tests/graph-cascade.test.mjs +29 -0
  77. package/tests/graph.test.mjs +45 -0
  78. package/tests/help-page.test.mjs +1 -1
  79. package/tests/inject-conflict.test.mjs +112 -0
  80. package/tests/inject-guide.test.mjs +5 -3
  81. package/tests/inject.test.mjs +2 -2
  82. package/tests/injection-intent-budget.test.mjs +92 -0
  83. package/tests/lexical-bm25.test.mjs +171 -0
  84. package/tests/lexicon-frequency.test.mjs +17 -1
  85. package/tests/lexicon-inject.test.mjs +21 -0
  86. package/tests/lexicon-perf.test.mjs +37 -9
  87. package/tests/lexicon-scope.test.mjs +2 -2
  88. package/tests/lexicon-ui.test.mjs +1 -1
  89. package/tests/managed-memory.test.mjs +19 -0
  90. package/tests/memory-chain.test.mjs +140 -0
  91. package/tests/memory-fields.test.mjs +134 -0
  92. package/tests/memu-resident.test.mjs +33 -0
  93. package/tests/ops-hardening.test.mjs +209 -0
  94. package/tests/package-shipping.test.mjs +4 -0
  95. package/tests/prompt-semantics.test.mjs +51 -0
  96. package/tests/query-decompose.test.mjs +62 -0
  97. package/tests/recall-cache.test.mjs +4 -2
  98. package/tests/recall-intent.test.mjs +123 -0
  99. package/tests/slot-similarity.test.mjs +153 -0
  100. package/tests/speaker-provenance.test.mjs +120 -0
  101. package/tests/state-gc.test.mjs +34 -0
  102. package/tests/state.test.mjs +2 -2
  103. package/tests/temporal.test.mjs +124 -0
  104. package/tests/tokenizer-v2.test.mjs +1 -1
  105. package/tests/vector-gc.test.mjs +37 -0
  106. package/tests/webui.test.mjs +27 -0
@@ -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,
@@ -53,6 +57,7 @@ import {
53
57
  tokenStreamV2,
54
58
  tokenize as tokenizeV2,
55
59
  } from './tokenizer-v2.js'
60
+ import { hasTemporalHint, resolveQueryDates, DEFAULT_TIME_ZONE } from './temporal.js'
56
61
 
57
62
  // —— §4.1 分词 ——
58
63
 
@@ -161,41 +166,57 @@ function idfOf(corpus, term) {
161
166
  }
162
167
 
163
168
  /**
164
- * Verbatim §4.1 formula. Queries wider than BM25_MAX_QUERY_TERMS keep only the
165
- * 64 highest-IDF terms — measured among terms the corpus actually knows
166
- * (df > 0): an absent term scores 0 no matter its nominal IDF, so letting it
167
- * 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.
168
188
  */
169
189
  export function bm25(queryTokens, doc, corpus, { k1 = BM25_K1, b = BM25_B } = {}) {
170
190
  if (!queryTokens?.length || !doc || !corpus || corpus.size === 0) return 0
171
- 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
+ }
172
203
  if (terms.length === 0) return 0
173
204
  if (terms.length > BM25_MAX_QUERY_TERMS) {
174
205
  terms = terms
175
- .map((term) => ({ term, idf: idfOf(corpus, term) }))
176
206
  .sort((a, b2) => b2.idf - a.idf || (a.term < b2.term ? -1 : 1))
177
207
  .slice(0, BM25_MAX_QUERY_TERMS)
178
- .map((item) => item.term)
179
208
  }
180
209
  let score = 0
181
- for (const term of terms) {
210
+ for (const { term, qtf: count, idf } of terms) {
182
211
  const tf = doc.tf.get(term) || 0
183
212
  if (!tf) continue
184
- const idf = idfOf(corpus, term)
185
- 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))
186
214
  }
187
215
  return score
188
216
  }
189
217
 
190
218
  // —— §4.2 成对特征 ——
191
219
 
192
- function jaccard(a, b) {
193
- if (a.size === 0 || b.size === 0) return 0
194
- let shared = 0
195
- for (const item of a) if (b.has(item)) shared += 1
196
- return shared / (a.size + b.size - shared)
197
- }
198
-
199
220
  function entitySet(appliesTo) {
200
221
  const out = new Set()
201
222
  for (const item of Array.isArray(appliesTo) ? appliesTo : []) {
@@ -389,7 +410,7 @@ export function numericSetsDiffer(a, b) {
389
410
  * 子串包含关系(clause.includes(anchor))——锚点本身就是文本的子串,CJK
390
411
  * unigram/bigram 与 latin 词都覆盖。无共享词返回 ''(调用方回退整文本口径)。
391
412
  */
392
- function longestSharedToken(aBody, bBody) {
413
+ export function longestSharedToken(aBody, bBody) {
393
414
  const bTokens = new Set(tokenize(bBody))
394
415
  let anchor = ''
395
416
  for (const token of new Set(tokenize(aBody))) {
@@ -439,6 +460,37 @@ function idAsc(a, b) {
439
460
  return String(a.id).localeCompare(String(b.id))
440
461
  }
441
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
+
442
494
  /**
443
495
  * §4.3 rankPairCandidates({ corpus, proposal, limit })。
444
496
  *
@@ -513,8 +565,7 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
513
565
  const ids = [...candidates.keys()]
514
566
  const bm25Scores = ids.map((id) => ({ id, s: bm25(queryTokens, corpus.docs.get(id), corpus) }))
515
567
  bm25Scores.sort((a, b) => b.s - a.s || idAsc(a, b))
516
- const rankBm25 = new Map()
517
- bm25Scores.forEach((item, index) => rankBm25.set(item.id, index + 1))
568
+ const rankBm25 = competitionRanks(bm25Scores, (item) => item.s)
518
569
 
519
570
  const probes = ids.map((id) => {
520
571
  const doc = corpus.docs.get(id)
@@ -522,8 +573,9 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
522
573
  return { id, diceScore: detail.dice, containment: detail.containment, lexical: Math.max(detail.dice, detail.containment) }
523
574
  })
524
575
  const diceRankOrder = [...probes].sort((a, b) => b.diceScore - a.diceScore || b.containment - a.containment || idAsc(a, b))
525
- const rankDice = new Map()
526
- 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])
527
579
 
528
580
  const entityOrder = ids.map((id) => {
529
581
  const doc = corpus.docs.get(id)
@@ -533,8 +585,7 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
533
585
  containment: containmentOf(proposal, doc.entry),
534
586
  }
535
587
  }).sort((a, b) => b.entity - a.entity || b.containment - a.containment || idAsc(a, b))
536
- const rankEntity = new Map()
537
- entityOrder.forEach((item, index) => rankEntity.set(item.id, index + 1))
588
+ const rankEntity = competitionRanks(entityOrder, (item) => [item.entity, item.containment])
538
589
 
539
590
  // 3) weighted RRF。开关关 → 静态三路原式(字节级回退路径);开 → 权重来自
540
591
  // computeRRFWeights,含 recency 键时加第四路 updatedAt 降序排名。
@@ -555,7 +606,8 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
555
606
  const recencyOrder = ids
556
607
  .map((id) => ({ id, entry: corpus.docs.get(id).entry }))
557
608
  .sort((a, b) => updatedDesc(a.entry, b.entry) || idAsc(a, b))
558
- 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)
559
611
  }
560
612
  rrf = new Map()
561
613
  for (const id of ids) {
@@ -637,9 +689,11 @@ function round2(value) {
637
689
  * §4.4 buildCandidateClusters(index, options)。
638
690
  *
639
691
  * 1) active 条目按 updatedAt 降序取最近 recentLimit(2000) 条,按 track 分组。
640
- * 2) 同 track 内:N ≤ exactPairLimit(300) 全对;否则倒排 blocking(共享
641
- * ≥ blockMinShared(2) token)。
642
- * 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) 的边。
643
697
  * 4) 边排序用三路 RRF(同 §4.3:bm25 双向和 / charDice / entityJaccard)。
644
698
  * 5) 贪心成簇:边按 RRF 降序;种子=边两端;新成员必须与簇内**所有**成员
645
699
  * pairScore ≥ 0.55(全对约束,禁传递闭包);每簇 ≤6;每条目只进一个簇。
@@ -678,13 +732,18 @@ export function buildCandidateClusters(index, options = {}) {
678
732
  const n = items.length
679
733
  if (n < 2) continue
680
734
  const tokenSets = new Map()
735
+ const streams = new Map()
681
736
  const inverted = new Map()
682
737
  for (const item of items) {
683
738
  // blocking 倒排固定 V1 口径(idf 盲集合运算):unigram 会把高频单字灌大
684
739
  // 倒排与两两共享计数(N=500 簇延迟 +60% 的根因),对成簇质量无收益。
685
740
  // 边打分的 BM25 路由(下方 bm25Route/buildCorpus)仍走 V2 流。
686
- const tokens = tokenizeV1(`${item.entry?.title || ''} ${item.entry?.content || ''}`)
741
+ const text = `${item.entry?.title || ''} ${item.entry?.content || ''}`
742
+ const tokens = tokenizeV1(text)
687
743
  tokenSets.set(item.id, new Set(tokens))
744
+ // BM25 流只算一次:pairList 里同一条目会出现在许多对中,逐对重算
745
+ // tokenStream 是另一份 O(N²) 的浪费。
746
+ streams.set(item.id, tokenStream(text))
688
747
  for (const term of tokens) {
689
748
  if (!inverted.has(term)) inverted.set(term, [])
690
749
  inverted.get(term).push(item.id)
@@ -697,13 +756,28 @@ export function buildCandidateClusters(index, options = {}) {
697
756
  for (let j = i + 1; j < n; j++) pairSet.add(pairKey(items[i].id, items[j].id))
698
757
  }
699
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)
700
764
  const shared = new Map()
701
- for (const posting of inverted.values()) {
702
- 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
703
771
  for (let i = 0; i < posting.length; i++) {
704
772
  for (let j = i + 1; j < posting.length; j++) {
705
773
  const key = pairKey(posting[i], posting[j])
706
- 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
+ }
707
781
  }
708
782
  }
709
783
  }
@@ -714,36 +788,39 @@ export function buildCandidateClusters(index, options = {}) {
714
788
  if (pairSet.size === 0) continue
715
789
 
716
790
  const corpus = buildCorpus(items.map((item) => ({ id: item.id, title: item.entry?.title || '', content: item.entry?.content || '', entry: item.entry })))
717
- const pairList = [...pairSet].map((key) => {
791
+ // 便宜预筛:共享 token 为 0 的对直接跳过,连 similarityDetail(bigram 集
792
+ // 构建 + 长度探针)都不进。它只剔除没有任何共享词元(V1 口径)的候选,
793
+ // 不降低最终 pairScore 门槛。
794
+ const pairList = []
795
+ for (const key of pairSet) {
718
796
  const [aId, bId] = key.split('\u0000')
719
797
  const aItem = byId.get(aId)
720
798
  const bItem = byId.get(bId)
799
+ if (sharedTokenCount(tokenSets.get(aId), tokenSets.get(bId)) === 0) continue
721
800
  const features = pairFeatures(aItem.entry, bItem.entry)
722
801
  const score = pairScore(features)
723
- return { key, aId, bId, aItem, bItem, features, score }
724
- }).filter((pair) => pair.score >= minPair)
802
+ if (score < minPair) continue
803
+ pairList.push({ key, aId, bId, aItem, bItem, features, score })
804
+ }
725
805
  if (pairList.length === 0) continue
726
806
 
727
807
  // three route rankings for edge order only。
728
808
  // 刻意不做动态权重(P0-2 只落在 rankPairCandidates):buildCandidateClusters
729
809
  // 没有 proposal/查询上下文——它是无监督的全库成簇,三路 RRF 只决定贪心
730
810
  // 长簇的边访问顺序;引入「查询类型」没有语义落点,静态三路保证簇构建
731
- // 与查询无关、完全可复现。
811
+ // 与查询无关、完全可复现。并列分数共享同一名次(A-12)。
732
812
  const bm25Route = pairList.map((pair) => ({
733
813
  key: pair.key,
734
- s: bm25(tokenStream(`${pair.aItem.entry?.title || ''} ${pair.aItem.entry?.content || ''}`), corpus.docs.get(pair.bId), corpus)
735
- + 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),
736
816
  })).sort((a, b) => b.s - a.s || (a.key < b.key ? -1 : 1))
737
- const rankBm25 = new Map()
738
- bm25Route.forEach((item, i) => rankBm25.set(item.key, i + 1))
817
+ const rankBm25 = competitionRanks(bm25Route, (item) => item.s)
739
818
  const diceRoute = [...pairList].sort((a, b) => b.features.charDice - a.features.charDice
740
819
  || b.features.containment - a.features.containment || (a.key < b.key ? -1 : 1))
741
- const rankDice = new Map()
742
- diceRoute.forEach((item, i) => rankDice.set(item.key, i + 1))
820
+ const rankDice = competitionRanks(diceRoute, (item) => [item.features.charDice, item.features.containment])
743
821
  const entityRoute = [...pairList].sort((a, b) => b.features.entityJaccard - a.features.entityJaccard
744
822
  || b.features.containment - a.features.containment || (a.key < b.key ? -1 : 1))
745
- const rankEntity = new Map()
746
- entityRoute.forEach((item, i) => rankEntity.set(item.key, i + 1))
823
+ const rankEntity = competitionRanks(entityRoute, (item) => [item.features.entityJaccard, item.features.containment])
747
824
  for (const pair of pairList) {
748
825
  pair.rrf = RRF_W_BM25 / (RRF_K + rankBm25.get(pair.key))
749
826
  + RRF_W_DICE / (RRF_K + rankDice.get(pair.key))
@@ -852,3 +929,73 @@ export function buildCandidateClusters(index, options = {}) {
852
929
  for (let i = 0; i < out.length; i++) out[i].cluster_id = `cl-${i + 1}`
853
930
  return { clusters: out.slice(0, maxClusters), truncated, scanned: pool.length }
854
931
  }
932
+
933
+ // —— S5 查询意图与分解 ——
934
+ //
935
+ // 召回入口只需要知道“这句话在问哪一类事”,然后决定过滤与取数策略:
936
+ // date 时间题:先解析相对日期,按 absolute_date 过滤/排序
937
+ // entity 实体题:抽出实体名/别名,按实体索引扩展一跳
938
+ // conflict 冲突题:按 fact_key / conflicts_with 成对取
939
+ // commitment 约定题:未完成/到期承诺优先
940
+ // boundary 边界题:只有用户明确问到时才注入 only_if_asked
941
+ // general 普通题
942
+ // 纯规则,无外部模型,无网络;识别不出来就是 general,不猜。
943
+
944
+ const CONFLICT_RE = /矛盾|冲突|到底|哪一版|哪个版本|哪边|前后说法|说法不一|改口|不一致|不是说|谁对|真的吗|相反|contradict|conflict|which version/i
945
+ const COMMITMENT_RE = /答应|承诺|约定|说好|欠|兑现|到期|还没|什么时候还|做到|提醒我|promise|commitment|owe/i
946
+ const BOUNDARY_RE = /秘密|保密|别说|别告诉|不要告诉|不能说|不能提|隐私|瞒着|never[-_ ]?say|only if asked|secret/i
947
+ const DATE_QUERY_RE = /什么时候|哪天|几号|日期|时间|多久|几点|星期几|上次|之前|后来|最近|when|what time|which day/i
948
+
949
+ /**
950
+ * @returns {'date'|'entity'|'conflict'|'commitment'|'boundary'|'general'}
951
+ */
952
+ export function detectQueryIntent(query, { now = new Date(), timeZone = DEFAULT_TIME_ZONE, knownEntities = [] } = {}) {
953
+ const text = String(query || '').trim()
954
+ if (!text) return 'general'
955
+ if (CONFLICT_RE.test(text)) return 'conflict'
956
+ if (COMMITMENT_RE.test(text)) return 'commitment'
957
+ if (BOUNDARY_RE.test(text)) return 'boundary'
958
+ if (hasTemporalHint(text) || DATE_QUERY_RE.test(text) || /\d{4}[-/]\d{1,2}[-/]\d{1,2}/.test(text)) return 'date'
959
+ if (extractQueryEntities(text, { knownEntities }).length > 0) return 'entity'
960
+ return 'general'
961
+ }
962
+
963
+ const QUOTED_RE = /["“”「」『』]([^"“”「」『』]{2,30})["“”「」『』]/g
964
+ const AT_RE = /@([\w\u4e00-\u9fff-]{2,30})/g
965
+
966
+ /** 实体抽取只用“明确标注”的名字:引号、@、已知实体表。宁缺毋滥。 */
967
+ export function extractQueryEntities(query, { knownEntities = [] } = {}) {
968
+ const text = String(query || '')
969
+ const found = []
970
+ const add = (value) => {
971
+ const name = String(value || '').trim()
972
+ if (name.length < 2 || name.length > 30) return
973
+ if (!found.includes(name)) found.push(name)
974
+ }
975
+ for (const match of text.matchAll(QUOTED_RE)) add(match[1])
976
+ for (const match of text.matchAll(AT_RE)) add(match[1])
977
+ for (const name of Array.isArray(knownEntities) ? knownEntities : []) {
978
+ if (typeof name === 'string' && name.trim().length >= 2 && text.includes(name)) add(name)
979
+ }
980
+ return found.slice(0, 6)
981
+ }
982
+
983
+ /**
984
+ * 把查询拆成召回能直接用的零件。`expanded` 是拼给词法/向量检索的查询,
985
+ * `dates`/`entities` 同时供过滤与排序使用。
986
+ */
987
+ export function decomposeQuery(query, intent = null, { now = new Date(), timeZone = DEFAULT_TIME_ZONE, knownEntities = [] } = {}) {
988
+ const text = String(query || '')
989
+ const resolvedIntent = intent || detectQueryIntent(text, { now, timeZone, knownEntities })
990
+ const dates = resolveQueryDates(text, { now, timeZone })
991
+ const entities = extractQueryEntities(text, { knownEntities })
992
+ const terms = [...new Set([...dates, ...entities])]
993
+ return {
994
+ query: text,
995
+ intent: resolvedIntent,
996
+ dates,
997
+ entities,
998
+ terms,
999
+ expanded: [text, ...terms].filter(Boolean).join(' ').trim(),
1000
+ }
1001
+ }
@@ -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
  }