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
@@ -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
+ })
@@ -1,4 +1,4 @@
1
- // 词典频率先验(施工稿 §6.3 包 C):Wilson 下界、effective 因子进入 stableRank、
1
+ // 词典频率先验:Wilson 下界、effective 因子进入 stableRank、
2
2
  // hitCounts 写入 clamp、以及生命周期(active/archived)对频率证据的影响。所有断言
3
3
  // 只依赖落盘数据,不依赖当前时间——排序的确定性在这里与 lexicon-inject 各钉一遍。
4
4
  // 面板/卡片流(§2.4)的 UI 断言在 tests/lexicon-ui.test.mjs(G2b 重写),本文件只管
@@ -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
@@ -280,7 +280,10 @@ function naiveBucketKeysOf(entry) {
280
280
  return [...keys]
281
281
  }
282
282
 
283
- function naiveTextBuckets(normalizedText, maxBuckets = LEXICON_MAX_BUCKETS) {
283
+ // 窗口顺序与 lib 的 textBuckets 同口径:按桶命中词条数降序(A-8),而不是
284
+ // 按出现顺序取前 16 个。bucketSizeOf 用全量词条桶(含不可见词条)计算,与
285
+ // 索引里的 prefixBuckets.size 一致。
286
+ function naiveTextBuckets(normalizedText, bucketSizeOf, maxBuckets = LEXICON_MAX_BUCKETS) {
284
287
  const keys = []
285
288
  const seen = new Set()
286
289
  for (let i = 0; i + BUCKET_WIDTH <= normalizedText.length; i++) {
@@ -288,9 +291,12 @@ function naiveTextBuckets(normalizedText, maxBuckets = LEXICON_MAX_BUCKETS) {
288
291
  if (seen.has(key)) continue
289
292
  seen.add(key)
290
293
  keys.push(key)
291
- if (keys.length >= maxBuckets) break
292
294
  }
293
295
  return keys
296
+ .map((key, order) => ({ key, order, hits: bucketSizeOf(key) }))
297
+ .sort((a, b) => b.hits - a.hits || a.order - b.order)
298
+ .slice(0, maxBuckets)
299
+ .map(item => item.key)
294
300
  }
295
301
 
296
302
  function naiveDiceFallback(normalizedText, candidates, { threshold = LEXICON_DICE_THRESHOLD, maxCandidates = LEXICON_MAX_CANDIDATES, maxTerms = LEXICON_MAX_TERMS } = {}) {
@@ -383,7 +389,11 @@ function naiveMatch(terms, userText, memoryContext) {
383
389
  if (!normalizedText) return []
384
390
  const visibleIds = []
385
391
  const byBucket = new Map()
392
+ const allBucketSizes = new Map()
386
393
  for (const [termId, entry] of Object.entries(terms)) {
394
+ for (const key of naiveBucketKeysOf(entry)) {
395
+ allBucketSizes.set(key, (allBucketSizes.get(key) || 0) + 1)
396
+ }
387
397
  if ((entry.status || 'active') !== 'active') continue
388
398
  if (!contextVisible(entry.context, memoryContext)) continue
389
399
  visibleIds.push(termId)
@@ -394,15 +404,33 @@ function naiveMatch(terms, userText, memoryContext) {
394
404
  }
395
405
  const exact = naiveExactHits(terms, normalizedText, visibleIds)
396
406
  const exactIds = new Set(exact.map(hit => hit.termId))
397
- const candidateIds = []
398
- for (const key of naiveTextBuckets(normalizedText)) {
399
- for (const termId of byBucket.get(key) || []) {
400
- if (!exactIds.has(termId) && !candidateIds.includes(termId)) candidateIds.push(termId)
407
+ // 候选按「与 query 共享的 gram 数」降序(A-8);strength 与 termId 只做
408
+ // 确定性 tiebreak。共享 gram 按整段 query 与每个词面计算(与 lib 同口径)。
409
+ const candidateIds = new Set()
410
+ for (const key of naiveTextBuckets(normalizedText, k => allBucketSizes.get(k) || 0)) {
411
+ for (const termId of new Set(byBucket.get(key) || [])) {
412
+ if (exactIds.has(termId)) continue
413
+ candidateIds.add(termId)
414
+ }
415
+ }
416
+ const textGrams = bigrams(normalizedText)
417
+ const sharedGramCount = termId => {
418
+ let best = 0
419
+ for (const surface of [terms[termId].normalizedTerm, ...(terms[termId].normalizedAliases || [])]) {
420
+ if (!surface) continue
421
+ let shared = 0
422
+ for (const gram of bigrams(surface)) if (textGrams.has(gram)) shared += 1
423
+ if (shared > best) best = shared
401
424
  }
425
+ return best
402
426
  }
403
- const candidates = candidateIds
404
- .map(termId => naiveHitOf(terms[termId], termId, 'dice', 0))
405
- .sort((a, b) => (Number(b.strength) || 0) * (Number(b.confidence) || 0) - (Number(a.strength) || 0) * (Number(a.strength) || 0))
427
+ const weightOf = termId => (Number(terms[termId].strength) || 0) * (Number(terms[termId].confidence) || 0)
428
+ const candidates = [...candidateIds]
429
+ .map(termId => ({ termId, shared: sharedGramCount(termId) }))
430
+ .sort((a, b) => b.shared - a.shared
431
+ || weightOf(b.termId) - weightOf(a.termId)
432
+ || String(a.termId).localeCompare(String(b.termId)))
433
+ .map(({ termId }) => naiveHitOf(terms[termId], termId, 'dice', 0))
406
434
  const fuzzy = naiveDiceFallback(normalizedText, candidates)
407
435
  return naiveStableRank([...exact, ...fuzzy])
408
436
  }
@@ -230,9 +230,9 @@ test('lexiconAdd 带会话时给私有词条打领域戳', async () => {
230
230
  assert.equal(entryOf(libs.current.id, '面板词').domain, 'coding')
231
231
  })
232
232
 
233
- test('全局词典与私有词典同权进自动备份清单', () => {
233
+ test('全局词典与私有词典同权进自动备份清单', async () => {
234
234
  world()
235
- const created = backup.createBackup({ label: 'lexicon-scope-global' })
235
+ const created = await backup.createBackup({ label: 'lexicon-scope-global' })
236
236
  const manifest = JSON.parse(fs.readFileSync(path.join(created.dir, 'manifest.json'), 'utf8'))
237
237
  assert.ok(manifest.files[`lexicon/${GLOBAL_ID}.json`], 'global.json 是词典数据,必须在备份里')
238
238
  })
@@ -359,7 +359,7 @@ test('backup manifest carries the lexicon store and skips unsafe names', async (
359
359
  const junk = path.join(dataDir(), 'lexicon', 'bad id.json')
360
360
  fs.mkdirSync(path.dirname(junk), { recursive: true })
361
361
  fs.writeFileSync(junk, '{}')
362
- const created = backup.createBackup({ label: 'lexicon-ui' })
362
+ const created = await backup.createBackup({ label: 'lexicon-ui' })
363
363
  const manifest = JSON.parse(fs.readFileSync(path.join(created.dir, 'manifest.json'), 'utf8'))
364
364
  const rel = `lexicon/${lib.id}.json`
365
365
  assert.ok(manifest.files[rel], `manifest lists ${rel}`)
@@ -400,6 +400,25 @@ test('library queue spans compensation across routes and releases after failure'
400
400
  assert.equal(backendRows.size, 1)
401
401
  })
402
402
 
403
+ test('managed vector commit failure defers to index-only instead of losing the write', async () => {
404
+ const f = fixture()
405
+ activate([f.libraryId])
406
+ failCommit = true
407
+ const written = await memory.privateRemember({ exec: f.exec, content: 'deferred write survives', title: 'deferred' })
408
+ let entry = state.loadPrivateIndex(f.libraryId).entries[written.id]
409
+ assert.equal(entry.content, 'deferred write survives')
410
+ assert.equal(entry.vectorPending, true)
411
+ assert.equal(entry.vector, undefined)
412
+ assert.equal(backendRows.size, 0, 'nothing was falsely recorded as committed')
413
+ assert.ok(warnings.some(message => /deferred/.test(message)), 'the degradation must be observable')
414
+
415
+ failCommit = false
416
+ await memory.privateUpdate({ exec: f.exec, id: written.id, content: 'deferred write now committed' })
417
+ entry = state.loadPrivateIndex(f.libraryId).entries[written.id]
418
+ assert.equal(entry.vectorPending, undefined, 'a later successful commit clears the pending flag')
419
+ assert.equal(entry.vector.route, 'managed-local')
420
+ })
421
+
403
422
  test('managed import failure rejects without index-first false success', async () => {
404
423
  const f = fixture()
405
424
  activate([f.libraryId])
@@ -0,0 +1,140 @@
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-chain-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const { registerTools } = await import('../lib/tools.js')
11
+ const state = await import('../lib/state.js')
12
+ const inject = await import('../lib/inject.js')
13
+ const { dispatch } = await import('../lib/rpc.js')
14
+
15
+ test.after(() => {
16
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
17
+ })
18
+
19
+ function registeredTools() {
20
+ const tools = new Map()
21
+ registerTools({
22
+ tools: { register(tool) { tools.set(tool.name, tool); return () => {} } },
23
+ logger: { warn() {} },
24
+ })
25
+ return tools
26
+ }
27
+
28
+ function idsIn(text) {
29
+ return [...String(text || '').matchAll(/mem-[a-z0-9]+-[a-z0-9]+/gi)].map((match) => match[0])
30
+ }
31
+
32
+ test('the real tool → recall → injection chain is reachable and carries S1–S6 fields', async () => {
33
+ const tools = registeredTools()
34
+ for (const name of ['memu_private_remember', 'memu_private_recall', 'memu_private_update', 'memu_status']) {
35
+ assert.ok(tools.has(name), `missing tool ${name}`)
36
+ }
37
+
38
+ state.updateSettings({ randomCueChance: 0, habitsInjection: false, dedupeTurns: 0 })
39
+ const cwd = path.join(home, 'project-chain')
40
+ const sessionId = 'chain-session'
41
+ state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
42
+ state.setSessionBinding(sessionId, { sceneTime: '2026-11-06T04:00:00.000Z' })
43
+ const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } }
44
+
45
+ // 1. A user fact written through the actual model-facing tool.
46
+ const userReply = await tools.get('memu_private_remember').execute({
47
+ content: '明天下午三点在码头见面,别迟到。',
48
+ title: '明天码头见面',
49
+ source: 'user_said',
50
+ speaker_id: 'user',
51
+ }, exec)
52
+ const [userFactId] = idsIn(userReply)
53
+ assert.ok(userFactId, userReply)
54
+ const userEntry = state.loadPrivateIndex(state.getSessionBinding(sessionId).libraryId).entries[userFactId]
55
+ assert.equal(userEntry.absolute_date, '2026-11-07')
56
+ assert.equal(userEntry.speaker_id, 'user')
57
+ assert.equal(userEntry.source_kind, 'user_said')
58
+
59
+ // 2. An assistant promise, written as assistant_said with a commitment.
60
+ const promiseReply = await tools.get('memu_private_remember').execute({
61
+ content: '我答应明天提前去码头占位置。',
62
+ title: '答应提前去码头占位',
63
+ source_kind: 'assistant_said',
64
+ commitment: { counterparty: 'user', action: '提前去码头占位', due_at: '2026-11-07', status: 'open' },
65
+ }, exec)
66
+ const [promiseId] = idsIn(promiseReply)
67
+ assert.ok(promiseId, promiseReply)
68
+ const promiseEntry = state.loadPrivateIndex(state.getSessionBinding(sessionId).libraryId).entries[promiseId]
69
+ assert.equal(promiseEntry.source_kind, 'assistant_said')
70
+ assert.equal(promiseEntry.speaker_id, 'assistant')
71
+ assert.equal(promiseEntry.commitment.status, 'open')
72
+ assert.equal(promiseEntry.openLoop, true)
73
+
74
+ // 3. Two conflicting versions of one fact, then a conflict card in the real recall.
75
+ const floorA = idsIn(await tools.get('memu_private_remember').execute({
76
+ content: '客厅地板是木色的。', title: '客厅地板木色', fact_key: 'home:living_floor_color',
77
+ }, exec))[0]
78
+ const floorB = idsIn(await tools.get('memu_private_remember').execute({
79
+ content: '客厅地板不是木色,是灰色瓷砖。', title: '客厅地板灰色', fact_key: 'home:living_floor_color',
80
+ }, exec))[0]
81
+ assert.ok(floorA && floorB)
82
+
83
+ // 4. The explicit recall tool sees both the dated fact and the conflict pair.
84
+ const recallReply = await tools.get('memu_private_recall').execute({ query: '明天码头', topK: 10 }, exec)
85
+ assert.ok(recallReply.includes(userFactId), recallReply)
86
+ assert.ok(recallReply.includes(promiseId))
87
+ const floorReply = await tools.get('memu_private_recall').execute({ query: '客厅地板颜色', topK: 10 }, exec)
88
+ assert.ok(floorReply.includes(floorA) && floorReply.includes(floorB), floorReply)
89
+
90
+ // 5. The real pre-step injection path emits one plugin message carrying the fields
91
+ // the model needs to answer: resolved date, speaker and the conflict card.
92
+ const agent = { session: { header: { id: sessionId, cwd, agentPreset: 'rp', origin: 'user' } } }
93
+ const dateUser = {
94
+ id: 'chain-u1', role: 'user', source: { kind: 'user' },
95
+ content: [{ type: 'text', text: '明天下午我们在码头几点见面?' }],
96
+ }
97
+ const dated = await inject.injectForStep({
98
+ agent,
99
+ decision: { kind: 'enter', messages: [dateUser] },
100
+ turn: 1,
101
+ step: 1,
102
+ signal: { aborted: false },
103
+ })
104
+ const datedText = dated.messages
105
+ .filter((message) => message?.source?.kind === 'plugin:dsh-memu-memory')
106
+ .map((message) => String(message?.content?.[0]?.text || ''))
107
+ .join('\n')
108
+ assert.ok(datedText.includes(userFactId), datedText)
109
+ assert.match(datedText, /date=2026-11-07/, 'the resolved absolute date reaches the prompt')
110
+ assert.match(datedText, /source=assistant_said/)
111
+ assert.match(datedText, /speaker=assistant/)
112
+ // The user message is untouched and the plugin message comes before it.
113
+ assert.equal(dated.messages.at(-1).source.kind, 'user')
114
+ assert.equal(dated.messages.at(-1).content[0].text, dateUser.content[0].text)
115
+
116
+ const floorUser = {
117
+ id: 'chain-u2', role: 'user', source: { kind: 'user' },
118
+ content: [{ type: 'text', text: '客厅地板到底是什么颜色,前后说法不一样。' }],
119
+ }
120
+ const conflicted = await inject.injectForStep({
121
+ agent,
122
+ decision: { kind: 'enter', messages: [floorUser] },
123
+ turn: 2,
124
+ step: 1,
125
+ signal: { aborted: false },
126
+ })
127
+ const conflictText = conflicted.messages
128
+ .filter((message) => message?.source?.kind === 'plugin:dsh-memu-memory')
129
+ .map((message) => String(message?.content?.[0]?.text || ''))
130
+ .join('\n')
131
+ assert.match(conflictText, /冲突 · home:living_floor_color/, conflictText)
132
+ assert.ok(conflictText.includes(floorA) && conflictText.includes(floorB))
133
+
134
+ // 6. Observability: getState exposes the recall cache counters, including staleSkipped.
135
+ const view = await dispatch({}, 'getState', { sessionId })
136
+ assert.equal(typeof view.recallCache, 'object')
137
+ for (const key of ['hits', 'misses', 'evictions', 'errors', 'staleSkipped']) {
138
+ assert.equal(typeof view.recallCache[key], 'number', key)
139
+ }
140
+ })
@@ -0,0 +1,134 @@
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-temporal-fields-'))
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
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
15
+ })
16
+
17
+ let seq = 0
18
+ function session(name, sceneTime = '2026-11-06T04:00:00.000Z') {
19
+ seq += 1
20
+ const cwd = path.join(home, 'ws', `${name}-${seq}`)
21
+ const sessionId = `${name}-${seq}`
22
+ state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
23
+ state.setSessionBinding(sessionId, { sceneTime })
24
+ return {
25
+ sessionId,
26
+ cwd,
27
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
28
+ }
29
+ }
30
+
31
+ function index(sessionId) {
32
+ const binding = state.getSessionBinding(sessionId)
33
+ return state.loadPrivateIndex(binding.libraryId)
34
+ }
35
+
36
+ test('a relative date is resolved against sceneTime and stored as fields', async () => {
37
+ const { exec, sessionId } = session('fields-relative')
38
+ const { id, entry } = await memory.privateRemember({
39
+ exec, title: '明天出门带伞', content: '她说 明天 去学校门口见面。',
40
+ })
41
+ assert.equal(entry.absolute_date, '2026-11-07')
42
+ assert.equal(entry.date_precision, 'day')
43
+ assert.equal(entry.date_source, 'relative')
44
+ assert.equal(entry.event_time, '2026-11-06T04:00:00.000Z')
45
+ assert.equal(entry.observed_at, '2026-11-06T04:00:00.000Z')
46
+ assert.equal(entry.content, '她说 明天 去学校门口见面。', 'the original wording is kept verbatim')
47
+ const onDisk = index(sessionId).entries[id]
48
+ assert.equal(onDisk.absolute_date, '2026-11-07', 'fields survive the index round trip')
49
+ })
50
+
51
+ test('context.occurredAt overrides sceneTime for the same write', async () => {
52
+ const { exec } = session('fields-occurred')
53
+ const { entry } = await memory.privateRemember({
54
+ exec, title: '后天交材料', content: '后天把材料交到教务处。',
55
+ context: { occurredAt: '2026-12-30T12:00:00+08:00' },
56
+ })
57
+ assert.equal(entry.absolute_date, '2027-01-01', 'crosses the year boundary in the scene time zone')
58
+ assert.equal(entry.observed_at, '2026-12-30T04:00:00.000Z')
59
+ })
60
+
61
+ test('month-end and unresolved relative wording are marked, not guessed', async () => {
62
+ const { exec } = session('fields-precision')
63
+ const monthEnd = await memory.privateRemember({ exec, title: '月底对账', content: '月底前把账对完。' })
64
+ assert.equal(monthEnd.entry.absolute_date, '2026-11-30')
65
+ assert.equal(monthEnd.entry.date_precision, 'month')
66
+
67
+ const fuzzy = await memory.privateRemember({ exec, title: '下周再说', content: '下周再讨论排期。' })
68
+ assert.equal(fuzzy.entry.absolute_date, undefined)
69
+ assert.equal(fuzzy.entry.date_precision, 'unknown')
70
+ assert.equal(fuzzy.entry.date_source, 'relative')
71
+
72
+ const none = await memory.privateRemember({ exec, title: '窗户开着', content: '窗外的雨停了。' })
73
+ assert.equal(none.entry.absolute_date, undefined)
74
+ assert.equal(none.entry.date_precision, undefined)
75
+ })
76
+
77
+ test('an explicit absolute_date overrides prose and an impossible date is refused', async () => {
78
+ const { exec } = session('fields-explicit')
79
+ const { entry } = await memory.privateRemember({
80
+ exec, title: '聚会', content: '她说 明天 见。', absoluteDate: '2026-11-20',
81
+ })
82
+ assert.equal(entry.absolute_date, '2026-11-20')
83
+ assert.equal(entry.date_source, 'explicit')
84
+ await assert.rejects(
85
+ () => memory.privateRemember({ exec, title: '错日期', content: '测试。', absoluteDate: '2026-02-30' }),
86
+ /absolute_date must be YYYY-MM-DD/,
87
+ )
88
+ })
89
+
90
+ test('valid_from / valid_to hide an entry outside its window and never hide old entries without them', async () => {
91
+ const { exec, sessionId } = session('fields-validity')
92
+ const expired = await memory.privateRemember({
93
+ exec, title: '旧地址', content: '她住在旧公寓。', absoluteDate: '2026-10-01', validTo: '2026-10-31',
94
+ })
95
+ const upcoming = await memory.privateRemember({
96
+ exec, title: '新地址', content: '她下个月搬去新公寓。', absoluteDate: '2026-12-01', validFrom: '2026-12-01',
97
+ })
98
+ const current = await memory.privateRemember({
99
+ exec, title: '当前住处', content: '她现在住在河边的房子。', absoluteDate: '2026-11-01', validFrom: '2026-11-01', validTo: '2026-11-30',
100
+ })
101
+ const legacy = await memory.privateRemember({ exec, title: '没有日期的旧条目', content: '窗户是朝东的。' })
102
+ assert.equal(expired.entry.valid_to, '2026-10-31')
103
+ assert.equal(upcoming.entry.valid_from, '2026-12-01')
104
+
105
+ const currentEligible = memory.isMemoryEligible(current.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') })
106
+ assert.equal(currentEligible, true)
107
+ assert.equal(memory.isMemoryEligible(expired.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') }), false)
108
+ assert.equal(memory.isMemoryEligible(upcoming.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') }), false)
109
+ assert.equal(memory.isMemoryEligible(legacy.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') }), true)
110
+
111
+ const recalled = await memory.privateRecall({ exec, query: '公寓 住处 窗户', topK: 10, relevanceThreshold: 0 })
112
+ const ids = recalled.files.map((file) => file.name)
113
+ assert.ok(ids.includes(current.id), 'a valid entry is recalled')
114
+ assert.ok(ids.includes(legacy.id), 'an entry without a window is not filtered')
115
+ assert.ok(!ids.includes(expired.id), 'a past valid_to is filtered')
116
+ assert.ok(!ids.includes(upcoming.id), 'a future valid_from is filtered')
117
+ assert.equal(index(sessionId).entries[expired.id].valid_to, '2026-10-31', 'filtering is read-only')
118
+ })
119
+
120
+ test('rewriting the text re-derives the date; the query resolves relative words too', async () => {
121
+ const { exec } = session('fields-query')
122
+ const dated = await memory.privateRemember({
123
+ exec, title: '带伞', content: '出门要带伞,午后有雨。', absoluteDate: '2026-11-07',
124
+ })
125
+ // The body never says "明天"; only the resolved date can connect the query to it.
126
+ const recalled = await memory.privateRecall({ exec, query: '明天天气怎么样', topK: 10, relevanceThreshold: 0 })
127
+ assert.ok(recalled.files.some((file) => file.name === dated.id), 'the query resolves 明天 to 2026-11-07')
128
+
129
+ const updated = await memory.privateUpdate({
130
+ exec, id: dated.id, content: '后天出门要带伞,午后有雨。',
131
+ })
132
+ assert.equal(updated.entry.absolute_date, '2026-11-08', 'a rewrite re-resolves the date')
133
+ assert.equal(updated.entry.content, '后天出门要带伞,午后有雨。')
134
+ })