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
@@ -13,6 +13,7 @@ import {
13
13
  tokenize,
14
14
  } from '../lib/text-retrieval.js'
15
15
  import { similarityDetail, similarTexts, bigrams, dice } from '../lib/text-similarity.js'
16
+ import { RRF_K, RRF_W_BM25, RRF_W_DICE, RRF_W_ENTITY } from '../lib/curator-policy.js'
16
17
 
17
18
  // —— §4.1 tokenize ——
18
19
 
@@ -82,6 +83,34 @@ test('bm25: queries wider than 64 terms keep the matching terms (junk never evic
82
83
  assert.equal(bm25(query, corpus.docs.get('b'), corpus), bm25(hits, corpus.docs.get('b'), corpus))
83
84
  assert.ok(bm25(hits, corpus.docs.get('b'), corpus) > 0)
84
85
  })
86
+ test('bm25: a corpus-wide high-frequency character is dropped from the query instead of pulling the whole library in', () => {
87
+ const entries = []
88
+ for (let i = 1; i <= 40; i += 1) {
89
+ entries.push({
90
+ id: `freq-${i}`,
91
+ title: `记录 ${i}`,
92
+ content: `第 ${i} 条记录的内容里都带着这个高频字:的。${i === 1 ? '另外还有一个独角兽专属词。' : ''}`,
93
+ })
94
+ }
95
+ const corpus = buildCorpus(entries)
96
+ assert.ok(corpus.df.get('的') >= 40, 'the fixture must make 的 a corpus-wide term')
97
+ const doc = corpus.docs.get('freq-1')
98
+ // A-2:df > dfCap 的 term 整条不参与打分。旧实现给出一个很小的正数,于是
99
+ // 查「的」能把全库都拉进候选池;现在它不产生任何分数。
100
+ assert.equal(bm25(tokenize('的'), doc, corpus), 0)
101
+ // 真正的稀有 term 不受影响——闸门只剔高频词,不改正常词的分值口径。
102
+ assert.ok(bm25(tokenize('独角兽'), doc, corpus) > 0)
103
+ })
104
+
105
+ test('bm25: query term frequency is preserved (qtf multiplies that term\'s contribution)', () => {
106
+ const corpus = corpusFor()
107
+ const doc = corpus.docs.get('b')
108
+ const once = bm25(['缓存'], doc, corpus)
109
+ const twice = bm25(['缓存', '缓存'], doc, corpus)
110
+ assert.ok(once > 0)
111
+ assert.ok(Math.abs(twice - 2 * once) < 1e-12, `qtf=2 must double the contribution: ${once} -> ${twice}`)
112
+ })
113
+
85
114
  // —— §4.2 similarityDetail / pairFeatures / pairScore ——
86
115
 
87
116
  test('similarityDetail: length-comparable pairs report dice, pruned pairs report the containment floor', () => {
@@ -240,37 +269,51 @@ test('rankPairCandidates: deterministic — same input, same output', () => {
240
269
 
241
270
  // —— §4.3 边界带(P0-1 回归修复的守卫):代理切分 → pairScore 真尺终选 ——
242
271
  //
243
- // 手算秩结构(可复现 fixture,文本两两相同造成 bm25/dice 精确并列,en 路由的
244
- // containment tiebreak 由 cand-c/d 的逐字包含 0.92 垫高):
245
- // cand-a: bm1, di1, en4 → rrf = 0.5/61 + 0.3/61 + 0.2/64 = 1.6240e-2(rank 1,切点)
246
- // cand-b: bm2, di2, en1 → rrf = 0.5/62 + 0.3/62 + 0.2/61 = 1.6183e-2(rank 2,带内:
247
- // 与切点差 (0.5+0.3)×(1/61−1/62) − 0.2×(1/61−1/64) = 5.78e-5 ≤ RRF_SLICE_BAND)
248
- // cand-c/d: rrf 更低,带外(仅作 en 路由 containment 垫脚)。
249
- // pairScore:cand-b 0.9894(entity 匹配)≫ cand-a 0.8394(appliesTo 不相交)。
250
- // 修复前 pre-cut=limit=1 只评分 cand-a,返回 ['cand-a'];边界带把 cand-b 并入
251
- // 评分集,真尺终选翻到 cand-b——准入从 RRF 代理换成 pairScore 真尺的直接证据。
272
+ // 手算秩结构(A-12 之后并列共享名次,fixture 不再靠 id tiebreak 制造分差):
273
+ // cand-a: 与 proposal 文本全同、appliesTo 不相交 → bm1, di1, en2
274
+ // rrf = 0.5/61 + 0.3/61 + 0.2/62(切点)
275
+ // cand-b: 文本只多一个词、appliesTo 相同 → bm2, di2, en1
276
+ // rrf = 0.5/62 + 0.3/62 + 0.2/61
277
+ // 差值 = 0.6×(1/61−1/62) = 1.58e-4 ≤ RRF_SLICE_BAND(2.5e-4),所以 b 落在带内。
278
+ // pairScore:b(entity 1.0)明显高于 a(entity 0)——pre-cut=limit=1 只评分 a,
279
+ // 边界带把 b 并入评分集后真尺终选翻到 b:准入从 RRF 代理换成 pairScore 真尺。
252
280
  test('rankPairCandidates: the slice boundary band admits a better-pairScore candidate the RRF proxy dropped', () => {
253
- const twin = 'Redis 缓存统一设置 30 秒过期,命中直接返回。Redis 缓存统一设置 30 秒过期,命中直接返回。'
254
- const tail = '。另有运维值班轮换表与告警升级路径的完整说明,这里补足长度让长度剪枝生效并保持逐字包含。'
255
281
  const proposal = { title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回。', appliesTo: ['deploy'], track: 'memory', domain: 'general' }
256
282
  const corpus = buildCorpus([
257
- { id: 'cand-a', title: '缓存过期', content: twin, appliesTo: [], track: 'memory', domain: 'general' },
258
- { id: 'cand-b', title: '缓存过期', content: twin, appliesTo: ['deploy'], track: 'memory', domain: 'general' },
259
- { id: 'cand-c', title: '缓存过期', content: proposal.content + tail, appliesTo: [], track: 'memory', domain: 'general' },
260
- { id: 'cand-d', title: '缓存过期', content: proposal.content + tail, appliesTo: [], track: 'memory', domain: 'general' },
283
+ { id: 'cand-a', title: '缓存过期', content: proposal.content, appliesTo: [], track: 'memory', domain: 'general' },
284
+ { id: 'cand-b', title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回数据。', appliesTo: ['deploy'], track: 'memory', domain: 'general' },
261
285
  ])
262
286
  const found = rankPairCandidates({ corpus, proposal, limit: 1 })
263
287
  // 真尺终选:数量语义不变(≤max),赢家是带内 rescue 的高 pairScore 候选
264
288
  assert.equal(found.length, 1)
265
289
  assert.equal(found[0].id, 'cand-b')
266
290
  // 赢家的 rrf 严格低于切点(cand-a 的手算 rrf)——证明它来自边界带而非 pre-cut
267
- const cutRrf = 0.5 / (60 + 1) + 0.3 / (60 + 1) + 0.2 / (60 + 4)
291
+ const cutRrf = (RRF_W_BM25 + RRF_W_DICE) / (RRF_K + 1) + RRF_W_ENTITY / (RRF_K + 2)
268
292
  assert.ok(found[0].rrf < cutRrf, `winner rrf ${found[0].rrf} must sit below the pre-cut line ${cutRrf}`)
293
+ assert.ok(cutRrf - found[0].rrf <= 2.5e-4, 'and the gap must stay inside the slice band')
269
294
  // 被切掉的 cand-a 在真尺上确实更差(低 pairScore 者按 pairScore 出局)
270
295
  const loserScore = pairScore(pairFeatures(proposal, corpus.docs.get('cand-a').entry))
271
296
  assert.ok(found[0].score > loserScore, `band winner ${found[0].score} must beat the displaced candidate ${loserScore}`)
272
297
  })
273
298
 
299
+ // —— A-12:同分文档共享名次,RRF 贡献相等 ——
300
+ test('rankPairCandidates: two tied documents contribute the same RRF (competition ranking)', () => {
301
+ const text = 'Redis 缓存统一设置 30 秒过期,命中直接返回。'
302
+ const proposal = { title: '缓存过期', content: text, appliesTo: [], track: 'memory', domain: 'general' }
303
+ const corpus = buildCorpus([
304
+ { id: 'twin-b', title: '缓存过期', content: text, appliesTo: [], track: 'memory', domain: 'general' },
305
+ { id: 'twin-a', title: '缓存过期', content: text, appliesTo: [], track: 'memory', domain: 'general' },
306
+ ])
307
+ const found = rankPairCandidates({ corpus, proposal, limit: 20 })
308
+ const a = found.find((item) => item.id === 'twin-a')
309
+ const b = found.find((item) => item.id === 'twin-b')
310
+ assert.ok(a && b)
311
+ // 三路全部并列 rank 1:rrf = (0.5+0.3+0.2)/(K+1)。旧实现给同分者 1/2 名,
312
+ // 两者的 rrf 会不相等(1/61 vs 1/62)。
313
+ assert.equal(a.rrf, b.rrf)
314
+ assert.ok(Math.abs(a.rrf - (RRF_W_BM25 + RRF_W_DICE + RRF_W_ENTITY) / (RRF_K + 1)) < 1e-15)
315
+ })
316
+
274
317
  // —— §4.8 全局冲突预筛 ——
275
318
 
276
319
  test('globalConflictCheck: same title + different body is same_title; negation flips conflict', () => {
@@ -119,34 +119,37 @@ function recentCorpus() {
119
119
  ])
120
120
  }
121
121
 
122
- test('recency 查询下 updatedAt 更新的候选相对提升:rrf 差距收窄、新者增益为正、旧者为负', () => {
122
+ test('recency 查询下同分文档共享三路名次,recency 第四路成为唯一区分信号', () => {
123
123
  const corpus = recentCorpus()
124
124
  const proposal = { track: 'memory', domain: 'general', title: '缓存过期', content: '昨天 缓存过期提醒每日检查' }
125
125
  const found = rankPairCandidates({ corpus, proposal, limit: 20 })
126
126
  assert.equal(found.length, 2)
127
- // 文本全同 → 三路 tie 由 idAsc 定序:a-old 三路 rank1、b-new rank2;
128
- // recency 通道按 updatedAt 降序:b-new rank1、a-old rank2。
129
- const rrfOld = found.find((c) => c.id === 'a-old').rrf
130
- const rrfNew = found.find((c) => c.id === 'b-new').rrf
131
- // 静态口径的期望值(同一表达式、rank 1/2)
132
- const statOld = RRF_W_BM25 / (RRF_K + 1) + RRF_W_DICE / (RRF_K + 1) + RRF_W_ENTITY / (RRF_K + 1)
133
- const statNew = RRF_W_BM25 / (RRF_K + 2) + RRF_W_DICE / (RRF_K + 2) + RRF_W_ENTITY / (RRF_K + 2)
134
- // 新者的 rrf 相对静态严格提升,旧者严格下降 → 相对排名提升
135
- assert.ok(rrfNew > statNew, `新者应增益:${rrfNew} > ${statNew}`)
136
- assert.ok(rrfOld < statOld, `旧者应减益:${rrfOld} < ${statOld}`)
137
- // 两者差距收窄(0.8δ → 0.6δ),即 recency 把新者往前拉
138
- assert.ok(rrfOld - rrfNew < statOld - statNew)
139
- // recency 权重不足以翻转文本三路的合计优势(0.6δ > 0),排序仍稳定
140
- assert.equal(found[0].id, 'a-old')
141
- assert.equal(found[1].id, 'b-new')
127
+ // A-12:文本全同 → bm25/dice/entity 三路并列,竞赛排名下都取 rank 1(旧实现
128
+ // 用 idAsc 把它们拆成 rank 1/2,凭空制造分差)。recency 是唯一区分通道:
129
+ // b-new updatedAt 更新 → rank 1,a-old rank 2。
130
+ const w = computeRRFWeights(proposal, corpus)
131
+ assert.ok(w.recency != null, 'fixture must take the recency route')
132
+ const textRoutes = w.bm25 / (RRF_K + 1) + w.dice / (RRF_K + 1) + w.entity / (RRF_K + 1)
133
+ const rrfNew = textRoutes + w.recency / (RRF_K + 1)
134
+ const rrfOld = textRoutes + w.recency / (RRF_K + 2)
135
+ assert.ok(Math.abs(found.find((c) => c.id === 'b-new').rrf - rrfNew) < 1e-15)
136
+ assert.ok(Math.abs(found.find((c) => c.id === 'a-old').rrf - rrfOld) < 1e-15)
137
+ // 文本三路不提供任何区分,recency 足以把更新的文档推到前面。
138
+ assert.ok(rrfNew > rrfOld)
139
+ assert.equal(found[0].id, 'b-new')
140
+ assert.equal(found[1].id, 'a-old')
142
141
  })
143
142
 
144
- test('非近期查询下同一 corpus 不受 recency 影响:rrf 与静态公式逐位相等', () => {
143
+ test('非近期查询下同一 corpus 不受 recency 影响:同分同 rrf,输出按 id 稳定', () => {
145
144
  const corpus = recentCorpus()
146
145
  const proposal = { track: 'memory', domain: 'general', title: '缓存过期', content: '缓存过期提醒每日检查' }
147
146
  const found = rankPairCandidates({ corpus, proposal, limit: 20 })
148
- assert.equal(found[0].rrf, RRF_W_BM25 / (RRF_K + 1) + RRF_W_DICE / (RRF_K + 1) + RRF_W_ENTITY / (RRF_K + 1))
149
- assert.equal(found[1].rrf, RRF_W_BM25 / (RRF_K + 2) + RRF_W_DICE / (RRF_K + 2) + RRF_W_ENTITY / (RRF_K + 2))
147
+ // 文本全同 → 三路并列 rank 1,A-12 后两条 rrf 相等(旧实现是 1/61 与 1/62)。
148
+ const tied = (RRF_W_BM25 + RRF_W_DICE + RRF_W_ENTITY) / (RRF_K + 1)
149
+ assert.equal(found[0].rrf, tied)
150
+ assert.equal(found[1].rrf, tied)
151
+ assert.equal(found[0].id, 'a-old', 'equal rrf falls back to idAsc')
152
+ assert.equal(found[1].id, 'b-new')
150
153
  })
151
154
 
152
155
  test('结果确定性:同输入两次 rankPairCandidates / computeRRFWeights 完全一致', () => {
@@ -0,0 +1,52 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-percentile-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+
13
+ test.after(() => {
14
+ delete process.env.DSH_MEMU_RECALL_PERCENTILE
15
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
16
+ })
17
+
18
+ function fixture() {
19
+ const sessionId = 'percentile'
20
+ const cwd = path.join(home, 'ws-percentile')
21
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
22
+ const binding = state.getSessionBinding(sessionId)
23
+ const index = state.loadPrivateIndex(binding.libraryId)
24
+ const now = new Date().toISOString()
25
+ const topics = ['预算', '排期', '招聘', '客户投诉', '机房迁移', '季度目标', '培训', '安全审计', '值班表', '产品路线']
26
+ for (const [i, topic] of topics.entries()) {
27
+ index.entries[`mem-p${i}`] = {
28
+ title: `会议记录 ${i}`,
29
+ content: `会议主要讨论${topic},结论是下周继续跟进,负责人单独确认。`,
30
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
31
+ }
32
+ }
33
+ state.savePrivateIndex(binding.libraryId, index)
34
+ return { exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } } }
35
+ }
36
+
37
+ test('percentile cut is off by default and never pads a minimum result count', async () => {
38
+ const { exec } = fixture()
39
+ delete process.env.DSH_MEMU_RECALL_PERCENTILE
40
+ const normal = await memory.privateRecall({ exec, query: '会议', topK: 10, relevanceThreshold: 0 })
41
+ assert.equal(normal.files.length, 10, 'default keeps the requested topK')
42
+
43
+ process.env.DSH_MEMU_RECALL_PERCENTILE = '1'
44
+ const narrowed = await memory.privateRecall({ exec, query: '会议', topK: 10, relevanceThreshold: 0 })
45
+ assert.ok(narrowed.files.length > 0 && narrowed.files.length < normal.files.length, 'percentile must narrow, not pad')
46
+ assert.equal(narrowed.files.length, Math.ceil(normal.files.length * 0.25))
47
+ assert.equal(narrowed.files[0].name, normal.files[0].name, 'the best hit is preserved')
48
+ delete process.env.DSH_MEMU_RECALL_PERCENTILE
49
+
50
+ const none = await memory.privateRecall({ exec, query: 'qqqqzzzz', topK: 10, relevanceThreshold: 0 })
51
+ assert.equal(none.files.length, 0, 'a no-match stays empty')
52
+ })
@@ -120,6 +120,24 @@ test('relation targets must exist, be active and share the scope', async () => {
120
120
  assert.ok(!Object.values(stored).some((entry) => entry.title === '坏目标'), 'nothing is written when the target is invalid')
121
121
  })
122
122
 
123
+ test('explicit provenance derives local authority and evidence without extra card text', async () => {
124
+ const { exec } = session('fact-authority')
125
+ const quoted = await memory.privateRemember({
126
+ exec, title: '报价确认', content: '他确认报价是三十万。',
127
+ source: 'user_said', quoteSpan: { seq: 8, turn: 2, textHash: 'abc' },
128
+ })
129
+ assert.equal(quoted.entry.fact_authority, 3)
130
+ assert.deepEqual(quoted.entry.fact_evidence, { seq: 8, turn: 2, textHash: 'abc' })
131
+
132
+ const guessed = await memory.privateRemember({
133
+ exec, title: '报价猜测', content: '我猜报价大概是三十万。',
134
+ })
135
+ assert.equal(guessed.entry.fact_authority, 1)
136
+
137
+ const corrected = await memory.privateUpdate({ exec, id: guessed.id, source: 'user_said' })
138
+ assert.equal(corrected.entry.fact_authority, 3, 'correcting provenance re-derives authority')
139
+ })
140
+
123
141
  test('a derived fact_key is stored even without an explicit key', async () => {
124
142
  const { exec } = session('fact-derived')
125
143
  const { entry } = await memory.privateRemember({ exec, title: '窗台的绿萝', content: '窗台有一盆绿萝。' })
@@ -0,0 +1,27 @@
1
+ // 分词器的测试场景清单。
2
+ //
3
+ // 这些是测试语料,不是分词器的能力,所以它们住在 tests/ 而不是 lib/:
4
+ // 生产模块导出一份永远只有测试用的常量,等于给打包产物塞了一份无人使用的
5
+ // 字符串表,也让「lib 里每个 export 都有业务调用方」这条自查失效。
6
+
7
+ /**
8
+ * Test cases for different scenarios
9
+ */
10
+ export const TEST_CASES = [
11
+ {
12
+ input: '人工智能是一种技术',
13
+ description: '纯中文短句',
14
+ },
15
+ {
16
+ input: '2026-11-05 AI 技术在快速发展',
17
+ description: '混合日期、英文缩写和中文',
18
+ },
19
+ {
20
+ input: 'Qwen3-Embedding 在 2026 年发布',
21
+ description: '混合产品名、年份和中文',
22
+ },
23
+ {
24
+ input: 'user@example.com 访问 https://example.com',
25
+ description: '邮箱和 URL',
26
+ },
27
+ ]
@@ -81,6 +81,35 @@ test('deleteEntity deletes an unreferenced entity and refuses a referenced one u
81
81
  assert.equal(readStore().entities[kept.id], undefined)
82
82
  })
83
83
 
84
+ test('deleteEntity tolerates a corrupt relationship key and never loses a readable snapshot', () => {
85
+ const target = graph.createEntity({ libraryId, name: 'CorruptTarget' })
86
+ const other = graph.createEntity({ libraryId, name: 'CorruptOther' })
87
+ const outsider = graph.createEntity({ libraryId, name: 'CorruptOutsider' })
88
+ const targetKey = JSON.stringify([target.id, other.id])
89
+ const unrelatedKey = JSON.stringify([other.id, outsider.id])
90
+ const corruptKey = 'not-json\u0000relationship'
91
+ const store = readStore()
92
+ store.relationships[targetKey] = { fromId: target.id, toId: other.id, state: { trust: 0.5 }, history: [], evidenceIds: ['mem-free'] }
93
+ store.relationships[unrelatedKey] = { fromId: other.id, toId: outsider.id, state: { trust: 0.4 }, history: [], evidenceIds: ['mem-free'] }
94
+ store.relationships[corruptKey] = { fromId: 'x', toId: 'y', state: {}, history: [], evidenceIds: [] }
95
+ fs.writeFileSync(entitiesFile, JSON.stringify(store))
96
+ // 未 force:损坏 key 只是读不懂的历史,不能把「仍被引用」的拒绝变成 SyntaxError。
97
+ assert.throws(() => graph.deleteEntity({ libraryId, entityId: target.id }), /relationship snapshot/)
98
+ // force:只删除可读且真的指向 target 的快照;损坏 key 与无关好边原样保留。
99
+ const forced = graph.deleteEntity({ libraryId, entityId: target.id, force: true })
100
+ assert.equal(forced.removedRelationships, 1)
101
+ const after = readStore()
102
+ assert.equal(after.relationships[targetKey], undefined, 'the readable edge to the target is gone')
103
+ assert.ok(after.relationships[unrelatedKey], 'an unrelated readable edge is never silently dropped')
104
+ assert.ok(after.relationships[corruptKey], 'the corrupt key is preserved, not deleted as a side effect')
105
+ // 清理,避免坏 key 影响本文件后续的 prune/list 断言。
106
+ delete after.relationships[unrelatedKey]
107
+ delete after.relationships[corruptKey]
108
+ delete after.entities[other.id]
109
+ delete after.entities[outsider.id]
110
+ fs.writeFileSync(entitiesFile, JSON.stringify(after))
111
+ })
112
+
84
113
  test('force-delete drops relationship snapshots with the entity, and the freed endpoint is collectable', () => {
85
114
  const p = graph.createEntity({ libraryId, name: 'P' })
86
115
  const q = graph.createEntity({ libraryId, name: 'Q' })
@@ -114,6 +114,51 @@ test('relationship snapshots preserve unknowns, evidence, boundaries and previou
114
114
  assert.throws(() => graph.updateRelationship({ libraryId, fromId: a.id, toId: b.id, state: {}, evidenceIds: [], reason: 'no evidence' }), /evidence/)
115
115
  })
116
116
 
117
+ test('relationship history is capped while the current snapshot and evidence stay', () => {
118
+ const a = graph.createEntity({ libraryId, name: 'History A' })
119
+ const b = graph.createEntity({ libraryId, name: 'History B' })
120
+ for (let i = 0; i < 55; i += 1) {
121
+ graph.updateRelationship({
122
+ libraryId, fromId: a.id, toId: b.id,
123
+ state: { trust: 0.5, callbacks: [`callback ${i}`] },
124
+ evidenceIds: ['mem-2'], reason: `Evidence-backed revision ${i} is explicit.`,
125
+ })
126
+ }
127
+ const relation = graph.getRelationship({ libraryId, fromId: a.id, toId: b.id }).relationship
128
+ assert.equal(relation.history.length, 50, 'old revisions are capped')
129
+ assert.equal(relation.revision, 55)
130
+ assert.deepEqual(relation.state.callbacks, ['callback 54'])
131
+ assert.deepEqual(relation.evidenceIds, ['mem-2'])
132
+ })
133
+
134
+ test('relationship retention is a pure wall-clock decay with access reinforcement', () => {
135
+ assert.equal(graph.relationshipRetentionAt(1, 24), 0.5)
136
+ assert.equal(graph.relationshipRetentionAt(1, 48), 0.25)
137
+ assert.equal(graph.relationshipRetentionAt(1, -5), 1, 'clock rollback never boosts retention')
138
+ const accessed = graph.accessRelationship(0.5, { now: 10_000_000, lastAccessAt: null })
139
+ assert.ok(accessed > 0.5 && accessed < 1)
140
+ assert.equal(graph.accessRelationship(0.5, { now: 10_000_000, lastAccessAt: new Date(10_000_000 - 1000).toISOString() }), 0.5, 'cooldown blocks a second bump')
141
+ })
142
+
143
+ test('relationship snapshots persist retention, last access and next review', () => {
144
+ const a = graph.createEntity({ libraryId, name: 'Lifecycle A' })
145
+ const b = graph.createEntity({ libraryId, name: 'Lifecycle B' })
146
+ const created = graph.updateRelationship({
147
+ libraryId, fromId: a.id, toId: b.id,
148
+ state: { trust: 0.6 }, evidenceIds: ['mem-2'], reason: 'First explicit evidence for this relation.',
149
+ }).relationship
150
+ assert.equal(created.retention_strength, 1)
151
+ assert.ok(created.last_access_at)
152
+ assert.ok(created.next_review_at)
153
+ const next = graph.updateRelationship({
154
+ libraryId, fromId: a.id, toId: b.id,
155
+ state: { trust: 0.7 }, evidenceIds: ['mem-2'], reason: 'Second explicit evidence for this relation.',
156
+ }).relationship
157
+ assert.ok(next.retention_strength > 0 && next.retention_strength <= 1)
158
+ assert.ok(next.last_access_at >= created.last_access_at)
159
+ assert.equal(next.history[0].retention_strength, 1)
160
+ })
161
+
117
162
  test('a dangling edge is reported as missing, matching the graph view placeholder', () => {
118
163
  // mem-1 was deleted from the index in an earlier test; its inbound edge from
119
164
  // mem-0 remains. getGraph renders a [deleted] placeholder for it, so recall
@@ -71,6 +71,24 @@ test('the card text stays under 200 characters even with long titles', () => {
71
71
  assert.equal(conflictCard({ left: null, right: null }), '')
72
72
  })
73
73
 
74
+ test('the card orders sides by local authority and observed time', () => {
75
+ const card = conflictCard({
76
+ factKey: 'home:living_floor_color',
77
+ left: { id: 'mem-inferred', entry: { title: '木色', source_kind: 'inferred' } },
78
+ right: { id: 'mem-user', entry: { title: '灰色', source_kind: 'user_said' } },
79
+ })
80
+ assert.match(card, /- A \[mem-user\]/, 'a direct quote is shown first')
81
+ assert.match(card, /- B \[mem-inferred\]/)
82
+ assert.ok(card.length <= 200)
83
+
84
+ const newer = conflictCard({
85
+ factKey: 'x',
86
+ left: { id: 'mem-old', entry: { title: '旧', fact_authority: 1, observed_at: '2026-11-01' } },
87
+ right: { id: 'mem-new', entry: { title: '新', fact_authority: 1, observed_at: '2026-11-05' } },
88
+ })
89
+ assert.match(newer, /- A \[mem-new\]/, 'equal authority falls back to the newer observation')
90
+ })
91
+
74
92
  test('a conflict card that cannot fit falls back to the ordinary title cards', async () => {
75
93
  const { exec, sessionId } = session('conflict-budget')
76
94
  const longTitle = '非常长的旅行目的地描述'.repeat(8)
@@ -0,0 +1,171 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-bm25-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+
13
+ test.after(() => {
14
+ delete process.env.DSH_MEMU_RECALL_LEXICAL
15
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
16
+ })
17
+
18
+ function fixture() {
19
+ const sessionId = 'bm25-session'
20
+ const cwd = path.join(home, 'ws-bm25')
21
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
22
+ const binding = state.getSessionBinding(sessionId)
23
+ const index = state.loadPrivateIndex(binding.libraryId)
24
+ const now = new Date().toISOString()
25
+ // "版本" is common across the corpus; "灰度" exists only in the target. The
26
+ // legacy includes scorer weights the title of every decoy above the target's body.
27
+ for (let i = 1; i <= 20; i += 1) {
28
+ index.entries[`mem-decoy${i}`] = {
29
+ title: `版本记录 ${i}`,
30
+ content: `这是第 ${i} 次版本记录,只记录版本号和变更人,没有别的说明。`,
31
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
32
+ }
33
+ }
34
+ index.entries['mem-target'] = {
35
+ title: '发布说明',
36
+ content: '本次版本更新包含灰度发布,灰度只允许在变更窗口内执行。',
37
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
38
+ }
39
+ state.savePrivateIndex(binding.libraryId, index)
40
+ return {
41
+ sessionId,
42
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } },
43
+ }
44
+ }
45
+
46
+ async function recall(exec, mode) {
47
+ if (mode === 'includes') process.env.DSH_MEMU_RECALL_LEXICAL = 'includes'
48
+ else delete process.env.DSH_MEMU_RECALL_LEXICAL
49
+ return memory.privateRecall({ exec, query: '版本 灰度', topK: 5, relevanceThreshold: 0 })
50
+ }
51
+
52
+ function rankOf(result, id) {
53
+ const index = result.files.findIndex((file) => file.name === id)
54
+ return index < 0 ? Infinity : index + 1
55
+ }
56
+
57
+ test('BM25 ranks the rare-term target first where includes-count does not', async () => {
58
+ const { exec } = fixture()
59
+ const legacy = await recall(exec, 'includes')
60
+ const bm25 = await recall(exec, 'bm25')
61
+
62
+ const legacyRank = rankOf(legacy, 'mem-target')
63
+ const bm25Rank = rankOf(bm25, 'mem-target')
64
+ assert.equal(bm25Rank, 1, 'BM25 must put the only 灰度 memory first')
65
+ assert.ok(legacyRank > 5, `includes-count must miss Recall@5, got rank ${legacyRank}`)
66
+ assert.ok(1 / bm25Rank > 1 / legacyRank, 'MRR must improve')
67
+
68
+ const target = bm25.files[0]
69
+ // A-2:query 里的「版本」出现在全部 21 条记忆里(df=N),按 df 闸门整条不参与
70
+ // 打分,decoys 因此拿不到任何 lexical 分数、进不了候选池。旧实现会给每个
71
+ // decoy 一个极小的正分,把全库一起拉进来——这正是要修的行为。
72
+ const decoy = bm25.files.find((file) => file.name.startsWith('mem-decoy'))
73
+ assert.equal(decoy, undefined, 'the corpus-wide term must no longer pull every decoy into the pool')
74
+ assert.ok(target.lexical > 0, 'the rare term still scores the target')
75
+ })
76
+
77
+ test('the lexical corpus cache is invalidated by a write', async () => {
78
+ const { exec } = fixture()
79
+ await recall(exec, 'bm25')
80
+ const written = await memory.privateRemember({
81
+ exec, title: '新的灰度记录',
82
+ content: '灰度发布新增了一条回滚检查,必须在变更窗口内完成。',
83
+ })
84
+ const after = await memory.privateRecall({ exec, query: '灰度', topK: 10, relevanceThreshold: 0 })
85
+ assert.ok(after.files.some((file) => file.name === written.id), 'a write must invalidate the cached corpus')
86
+ })
87
+
88
+ test('BM25 improves MRR and Recall@5 across eight rare-term queries', async () => {
89
+ const sessionId = 'bm25-multi'
90
+ const cwd = path.join(home, 'ws-bm25-multi')
91
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
92
+ const binding = state.getSessionBinding(sessionId)
93
+ const index = state.loadPrivateIndex(binding.libraryId)
94
+ const now = new Date().toISOString()
95
+ const rares = ['灰度', '熔断', '幂等', '分片', '回填', '限流', '审计', '快照']
96
+ const common = ['版本', '发布', '接口', '缓存', '部署', '回滚', '日志', '监控']
97
+ for (let group = 0; group < 8; group += 1) {
98
+ index.entries[`mem-target-${group}`] = {
99
+ title: `发布说明 ${group}`,
100
+ content: `本次${common[group]}更新包含${rares[group]}策略,${rares[group]}只允许在变更窗口内执行。`,
101
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
102
+ }
103
+ for (let i = 0; i < 20; i += 1) {
104
+ index.entries[`mem-decoy-${group}-${i}`] = {
105
+ title: `${common[group]}记录 ${group}-${i}`,
106
+ content: `这是第 ${i} 次${common[group]}记录,只记录${common[group]}号和变更人,没有别的说明。`,
107
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
108
+ }
109
+ }
110
+ }
111
+ state.savePrivateIndex(binding.libraryId, index)
112
+ const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } }
113
+
114
+ async function measure(mode) {
115
+ if (mode === 'includes') process.env.DSH_MEMU_RECALL_LEXICAL = 'includes'
116
+ else delete process.env.DSH_MEMU_RECALL_LEXICAL
117
+ let mrr = 0
118
+ let recall = 0
119
+ for (let group = 0; group < 8; group += 1) {
120
+ const result = await memory.privateRecall({
121
+ exec, query: `${common[group]} ${rares[group]}`, topK: 5, relevanceThreshold: 0,
122
+ })
123
+ const rank = result.files.findIndex((file) => file.name === `mem-target-${group}`) + 1
124
+ if (rank > 0) {
125
+ mrr += 1 / rank
126
+ if (rank <= 5) recall += 1
127
+ }
128
+ }
129
+ return { mrr: mrr / 8, recall5: recall }
130
+ }
131
+
132
+ const legacy = await measure('includes')
133
+ const bm25 = await measure('bm25')
134
+ delete process.env.DSH_MEMU_RECALL_LEXICAL
135
+ assert.ok(bm25.mrr > legacy.mrr, `MRR must improve: ${legacy.mrr} -> ${bm25.mrr}`)
136
+ assert.ok(bm25.recall5 > legacy.recall5, `Recall@5 must improve: ${legacy.recall5}/8 -> ${bm25.recall5}/8`)
137
+ assert.equal(bm25.recall5, 8, 'every rare-term target must enter the top five')
138
+ })
139
+
140
+ test('the includes fallback remains byte-for-byte available', async () => {
141
+ const { exec } = fixture()
142
+ const result = await recall(exec, 'includes')
143
+ assert.ok(result.files.length > 0)
144
+ assert.ok(result.files.every((file) => Number.isFinite(file.lexical)))
145
+ delete process.env.DSH_MEMU_RECALL_LEXICAL
146
+ })
147
+
148
+ test('tags and attachment captions still participate in the BM25 corpus', async () => {
149
+ const sessionId = 'bm25-fields'
150
+ const cwd = path.join(home, 'ws-bm25-fields')
151
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
152
+ const binding = state.getSessionBinding(sessionId)
153
+ const index = state.loadPrivateIndex(binding.libraryId)
154
+ const now = new Date().toISOString()
155
+ index.entries['mem-tagged'] = {
156
+ title: '一条普通记录', content: '正文里没有检索词。', tags: ['灰度', '发布'],
157
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
158
+ }
159
+ index.entries['mem-captioned'] = {
160
+ title: '另一条记录', content: '正文也很干净。',
161
+ attachments: [{ sha256: 'a'.repeat(64), caption: '灰度截图' }],
162
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
163
+ }
164
+ state.savePrivateIndex(binding.libraryId, index)
165
+ const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } }
166
+ delete process.env.DSH_MEMU_RECALL_LEXICAL
167
+ const tagged = await memory.privateRecall({ exec, query: '灰度', topK: 5, relevanceThreshold: 0 })
168
+ const ids = tagged.files.map((file) => file.name)
169
+ assert.ok(ids.includes('mem-tagged'), 'a query term in tags must still match')
170
+ assert.ok(ids.includes('mem-captioned'), 'a query term in an attachment caption must still match')
171
+ })
@@ -67,6 +67,22 @@ test('usageLowerBound: n=0 is 0, success is clamped to n, output stays in [0,1]'
67
67
  assert.ok(Math.abs(single - 0.207) < 0.01, `1/1 lower bound should be ~0.207, got ${single}`)
68
68
  })
69
69
 
70
+ test('usageLowerBound: priorAttempts is the same-source denominator; overflow stays bounded and monotone', () => {
71
+ const probe = (priorAttempts, injection, query = 0) => lexicon.usageLowerBound({ candidate: 100, priorAttempts, injection, query })
72
+ // 同源分母:固定 priorAttempts,同源成功数越多,下界单调不减。
73
+ const steps = [0, 1, 2, 3, 5].map(success => probe(5, success))
74
+ for (let i = 1; i < steps.length; i += 1) {
75
+ assert.ok(steps[i] >= steps[i - 1], `success ${i} must not lower the bound: ${steps[i - 1]} -> ${steps[i]}`)
76
+ }
77
+ // 分子超过分母:仍被 clamp 到 n,结果有界且等于 p=1 的下界(不会 >1)。
78
+ const overflow = probe(5, 50)
79
+ const full = probe(5, 5)
80
+ assert.equal(overflow, full)
81
+ assert.ok(overflow > 0 && overflow <= 1)
82
+ // 缺失 priorAttempts 时退回 candidate 分母:与旧近似的数值一致(文档化假设)。
83
+ assert.equal(lexicon.usageLowerBound({ candidate: 5, injection: 5 }), full)
84
+ })
85
+
70
86
  test('usageLowerBound: 10/9 ranks above 10/1 — a high miss rate is punished', () => {
71
87
  const good = lexicon.usageLowerBound({ candidate: 10, injection: 9, query: 0 })
72
88
  const bad = lexicon.usageLowerBound({ candidate: 10, injection: 1, query: 0 })
@@ -90,6 +90,27 @@ test('dice fallback: a fuzzy variant inside the prefix bucket hits with score >=
90
90
  assert.deepEqual(lexicon.matchLexiconHits(binding.libraryId, '今天天气不错', binding.memoryContext), [])
91
91
  })
92
92
 
93
+ test('dice fallback: a typo at the end of a long message still recalls the term (windows by hit count, not order)', () => {
94
+ const binding = setupSession('dice-tail', { terms: [{ term: '糖刀文学', kind: 'term', meaning: '又甜又虐的写法' }] })
95
+ // 40 字闲聊 + 末尾错字变体:旧实现按出现顺序只取前 16 个不同窗口,糖刀这个
96
+ // 前缀窗口落在第 17 个之后,模糊层收不到候选;现在窗口按命中词条数排序。
97
+ const chatter = '今晚的雾夜灯桥边茶铺霜露未散他忽然提起那些旧梗台词接得毫无痕迹我们笑作一团后来月影移过柳岸'
98
+ const text = `${chatter}糖刀文雪`
99
+ const normalized = lexicon.normalizeLexeme(text)
100
+ const windows = []
101
+ for (let i = 0; i + 2 <= normalized.length; i++) {
102
+ const key = normalized.slice(i, i + 2)
103
+ if (!windows.includes(key)) windows.push(key)
104
+ }
105
+ assert.ok(!windows.slice(0, lexicon.LEXICON_MAX_BUCKETS).includes('糖刀'),
106
+ 'fixture guard: the matching window must sit beyond the old 16-window cut')
107
+ const hits = lexicon.matchLexiconHits(binding.libraryId, text, binding.memoryContext)
108
+ assert.equal(hits.length, 1)
109
+ assert.equal(hits[0].term, '糖刀文学')
110
+ assert.equal(hits[0].kindOfHit, 'dice')
111
+ assert.ok(hits[0].score >= lexicon.LEXICON_DICE_THRESHOLD)
112
+ })
113
+
93
114
  test('active and restored terms match; archived and rejected never match or search', () => {
94
115
  const binding = setupSession('status', {})
95
116
  const lib = binding.libraryId