dsh-memu-memory 1.2.6 → 1.2.8

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 (68) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +10 -15
  3. package/README.zh.md +10 -15
  4. package/docs/contributing.md +1 -1
  5. package/docs/host-adaptation.md +1 -1
  6. package/docs/memory-semantics.md +26 -4
  7. package/docs/troubleshooting.md +3 -1
  8. package/lib/backup.js +1 -1
  9. package/lib/binding-diagnostics.js +2 -2
  10. package/lib/budget.js +31 -0
  11. package/lib/client.js +276 -28
  12. package/lib/commitment.js +138 -0
  13. package/lib/consolidation-receipt.js +2 -0
  14. package/lib/consolidation-worker.js +3 -0
  15. package/lib/curator-policy.js +98 -0
  16. package/lib/fork-model.js +312 -0
  17. package/lib/freshness.js +24 -0
  18. package/lib/inject.js +117 -10
  19. package/lib/lexicon.js +1 -1
  20. package/lib/local-vector-service.js +4 -1
  21. package/lib/memory.js +600 -43
  22. package/lib/memu.js +4 -0
  23. package/lib/private.js +49 -8
  24. package/lib/prompts/private-consolidation.mixed.md +3 -2
  25. package/lib/prompts/private-consolidation.rp.md +7 -1
  26. package/lib/prompts/private-policy.mixed.md +1 -0
  27. package/lib/prompts/private-policy.rp.md +5 -1
  28. package/lib/prompts/system-guide.rp.md +3 -0
  29. package/lib/recall-cache.js +212 -0
  30. package/lib/rpc.js +44 -6
  31. package/lib/snippet.js +25 -0
  32. package/lib/state.js +43 -1
  33. package/lib/temporal.js +329 -0
  34. package/lib/text-retrieval.js +292 -28
  35. package/lib/tokenizer-v2.js +295 -0
  36. package/lib/tools.js +81 -4
  37. package/lib/webui/standalone.css +17 -1
  38. package/package.json +1 -1
  39. package/scripts/bench-recall.mjs +142 -0
  40. package/scripts/check-seed-compat.mjs +118 -0
  41. package/tests/backup.test.mjs +2 -2
  42. package/tests/commitment.test.mjs +144 -0
  43. package/tests/consolidation-fork.test.mjs +122 -5
  44. package/tests/curator-clusters.test.mjs +7 -1
  45. package/tests/curator-pairing.test.mjs +52 -8
  46. package/tests/disclosure.test.mjs +34 -17
  47. package/tests/dynamic-rrf.test.mjs +179 -0
  48. package/tests/fact-version.test.mjs +128 -0
  49. package/tests/fork-model.test.mjs +345 -0
  50. package/tests/help-page.test.mjs +1 -1
  51. package/tests/inject-conflict.test.mjs +94 -0
  52. package/tests/inject-guide.test.mjs +5 -3
  53. package/tests/inject.test.mjs +2 -2
  54. package/tests/injection-intent-budget.test.mjs +92 -0
  55. package/tests/lexicon-frequency.test.mjs +1 -1
  56. package/tests/loader.mjs +3 -0
  57. package/tests/memory-chain.test.mjs +140 -0
  58. package/tests/memory-fields.test.mjs +134 -0
  59. package/tests/memu-resident.test.mjs +33 -0
  60. package/tests/negation-polarity.test.mjs +135 -0
  61. package/tests/prompt-semantics.test.mjs +51 -0
  62. package/tests/query-decompose.test.mjs +62 -0
  63. package/tests/recall-cache.test.mjs +292 -0
  64. package/tests/recall-intent.test.mjs +100 -0
  65. package/tests/speaker-provenance.test.mjs +120 -0
  66. package/tests/stubs/dsh-llm-pi-ai.js +13 -0
  67. package/tests/temporal.test.mjs +124 -0
  68. package/tests/tokenizer-v2.test.mjs +142 -0
@@ -34,25 +34,35 @@ function seedGlobal(id, patch) {
34
34
  state.saveGlobalIndex(index)
35
35
  }
36
36
 
37
- test('disclosure changes the wording of the injected line, not whether it arrives', async () => {
37
+ test('disclosure decides when a memory may surface, not just how it is worded', async () => {
38
38
  const cwd = path.join(home, 'proj-tone')
39
39
  const sessionId = 'tone-suffix'
40
40
  state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
41
41
  const exec = execFor(sessionId, cwd)
42
42
  const settings = { ...state.getSettings(), relevanceThreshold: 0, privateTopK: 5 }
43
43
 
44
- await memory.privateRemember({ exec, content: 'The ledger file lives in docs/ledger.md.', title: 'ledger file', disclosure: 'can_tell' })
45
- await memory.privateRemember({ exec, content: 'The ledger file is generated by the old importer.', title: 'ledger importer', disclosure: 'only_if_asked' })
46
- await memory.privateRemember({ exec, content: 'The ledger file was named after his father.', title: 'ledger name', disclosure: 'never_say' })
44
+ const open = await memory.privateRemember({ exec, content: 'The ledger file lives in docs/ledger.md.', title: 'ledger file', disclosure: 'can_tell' })
45
+ const ask = await memory.privateRemember({ exec, content: 'The ledger file is generated by the old importer.', title: 'ledger importer', disclosure: 'only_if_asked' })
46
+ const never = await memory.privateRemember({ exec, content: 'The ledger file was named after his father.', title: 'ledger name', disclosure: 'never_say' })
47
47
 
48
- const recall = await inject.buildRecall(state.getSessionBinding(sessionId), 'ledger file', 1, settings, exec, sessionId)
49
- assert.deepEqual(recall.errors, [])
50
- assert.ok(recall.text.includes('ledger file'), 'a can_tell memory arrives as before')
51
- assert.equal(recall.text.split('对方不问就别主动提').length - 1, 1, 'only_if_asked carries its suffix')
52
- assert.equal(recall.text.split('记得,但别直接说出口').length - 1, 1, 'never_say carries its suffix')
48
+ const automatic = await inject.buildRecall(state.getSessionBinding(sessionId), 'ledger file', 1, settings, exec, sessionId)
49
+ assert.deepEqual(automatic.errors, [])
50
+ assert.ok(automatic.text.includes('ledger file'), 'a can_tell memory arrives as before')
51
+ assert.equal(automatic.text.includes(ask.id), false, 'only_if_asked waits for a direct question')
52
+ assert.equal(automatic.text.includes(never.id), false)
53
53
  // The default case must stay silent: adding a suffix to every line would be noise.
54
- const canTellLine = recall.text.split('\n').find((line) => line.includes('ledger file ·') || line.includes('ledger file'))
54
+ const canTellLine = automatic.text.split('\n').find((line) => line.includes('ledger file ·') || line.includes('ledger file'))
55
55
  assert.ok(canTellLine && !canTellLine.includes('对方不问') && !canTellLine.includes('别直接说出口'))
56
+
57
+ const explicit = await memory.privateRecall({ exec, query: 'ledger file', topK: 10, relevanceThreshold: 0 })
58
+ const explicitIds = explicit.files.map((file) => file.name)
59
+ assert.ok(explicitIds.includes(ask.id) && explicitIds.includes(never.id), 'an explicit recall can still read both')
60
+
61
+ const boundary = await inject.buildRecall(state.getSessionBinding(sessionId), 'ledger 的秘密是什么', 2, settings, exec, sessionId)
62
+ assert.deepEqual(boundary.errors, [])
63
+ assert.ok(boundary.text.includes(ask.id), 'a direct boundary question releases only_if_asked')
64
+ assert.equal(boundary.text.split('对方不问就别主动提').length - 1, 1, 'only_if_asked carries its suffix when released')
65
+ assert.equal(boundary.text.includes(never.id), false, 'never_say never auto-surfaces, even when asked')
56
66
  })
57
67
 
58
68
  test('a secret stays out of the anchor but is still reachable through recall', async () => {
@@ -98,25 +108,32 @@ test('a secret stays out of the anchor but is still reachable through recall', a
98
108
  assert.ok(recalled.files.some((file) => file.name === sharedId))
99
109
  })
100
110
 
101
- test('the short-term pointer card carries the disclosure suffix too', async () => {
111
+ test('an unsayable short-term draft stays out of the anchor pointer', async () => {
102
112
  const cwd = path.join(home, 'proj-pointer')
103
113
  const sessionId = 'tone-pointer'
104
114
  const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
105
115
  const exec = execFor(sessionId, cwd)
106
116
 
107
- const { id } = await memory.privateRemember({
117
+ const never = await memory.privateRemember({
108
118
  exec,
109
- content: 'BODY he was still deciding about the surgery.',
119
+ content: 'BODY-NEVER he was still deciding about the surgery.',
110
120
  title: 'the surgery question',
111
121
  layer: 'short_term',
112
122
  disclosure: 'never_say',
113
123
  })
124
+ const open = await memory.privateRemember({
125
+ exec,
126
+ content: 'BODY-OPEN the follow-up appointment is on Thursday.',
127
+ title: 'the follow-up',
128
+ layer: 'short_term',
129
+ })
114
130
  const anchor = inject.buildAnchor(binding, { ...state.getSettings(), anchorTokens: 700 })
115
- const line = anchor.text.split('\n').find((row) => row.includes(id))
116
- assert.ok(line, 'the pointer row exists')
131
+ assert.equal(anchor.text.includes(never.id), false, 'never_say does not enter the automatic pointer list')
132
+ const line = anchor.text.split('\n').find((row) => row.includes(open.id))
133
+ assert.ok(line, 'an ordinary draft still gets a pointer')
117
134
  assert.ok(line.includes('小时后过期'))
118
- assert.ok(line.includes('记得,但别直接说出口'), 'a draft can be just as unsayable as a durable memory')
119
- assert.equal(anchor.text.includes('BODY he was still'), false)
135
+ assert.equal(anchor.text.includes('BODY-NEVER'), false)
136
+ assert.equal(anchor.text.includes('BODY-OPEN'), false)
120
137
  })
121
138
 
122
139
  test('owner prefixes only about_user, and the prefix is cheap', async () => {
@@ -0,0 +1,179 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import {
4
+ RRF_DYNAMIC,
5
+ RRF_K,
6
+ RRF_W_BM25,
7
+ RRF_W_DICE,
8
+ RRF_W_ENTITY,
9
+ RECENCY_TERMS,
10
+ computeRRFWeights,
11
+ } from '../lib/curator-policy.js'
12
+ import { buildCorpus, rankPairCandidates } from '../lib/text-retrieval.js'
13
+
14
+ // —— 召回升级 P0-2:动态 RRF 权重 ——
15
+ // 权重数字单一来源 lib/curator-policy.js;开关 RRF_DYNAMIC 恒为 const,
16
+ // ESM 不可运行时翻转,因此「开关关闭 = 静态路径」的等效性用两条证据覆盖:
17
+ // (1) computeRRFWeights 对普通查询精确返回静态表常量(动态路径退化为静态);
18
+ // (2) rankPairCandidates 在普通查询下产出的 rrf 与静态三路公式逐位相等。
19
+
20
+ const STATIC_WEIGHTS = { bm25: RRF_W_BM25, dice: RRF_W_DICE, entity: RRF_W_ENTITY }
21
+
22
+ function sumOf(weights) {
23
+ return Object.values(weights).reduce((a, b) => a + b, 0)
24
+ }
25
+
26
+ // —— computeRRFWeights:权重形状 ——
27
+
28
+ test('近期查询返回含 recency 的权重组且和为 1(设计稿 §4.2 数值)', () => {
29
+ const weights = computeRRFWeights({ title: '最近的部署', content: '昨天更新了缓存策略' }, { size: 3 })
30
+ assert.deepEqual(weights, { bm25: 0.3, dice: 0.3, entity: 0.2, recency: 0.2 })
31
+ assert.ok(Math.abs(sumOf(weights) - 1) < 1e-9)
32
+ })
33
+
34
+ test('近期词典(中英)逐词都能触发 recency 通道,且不依赖分词开关口径', () => {
35
+ for (const term of RECENCY_TERMS) {
36
+ const weights = computeRRFWeights({ title: term, content: '其他内容' }, { size: 3 })
37
+ assert.ok(weights.recency != null, `词条 ${term} 必须触发 recency`)
38
+ assert.ok(Math.abs(sumOf(weights) - 1) < 1e-9, `词条 ${term} 权重和必须为 1`)
39
+ }
40
+ })
41
+
42
+ test('coding 域 entity 提权:×1.5 后归一化,entity 追平 dice、bm25 降权', () => {
43
+ const weights = computeRRFWeights({ title: '部署脚本', content: 'redis 配置调整', domain: 'coding' }, { size: 3 })
44
+ assert.ok(weights.entity > 0.25, `entity 应从 0.2 提到 ~0.2727,got ${weights.entity}`)
45
+ assert.ok(Math.abs(weights.entity - weights.dice) < 1e-9, 'entity 与 dice 同为 0.3/1.1')
46
+ assert.ok(weights.bm25 < RRF_W_BM25, '归一化后 bm25 低于静态值')
47
+ assert.ok(weights.recency == null, '非近期查询不加第四路')
48
+ assert.ok(Math.abs(sumOf(weights) - 1) < 1e-9)
49
+ })
50
+
51
+ test('近期 + coding 叠加:四路权重 clamp/归一化后和仍为 1', () => {
52
+ const weights = computeRRFWeights({ title: '最近的部署脚本', content: '昨天改了配置', domain: 'coding' }, { size: 3 })
53
+ assert.ok(weights.recency != null)
54
+ for (const value of Object.values(weights)) {
55
+ assert.ok(value >= 0.05 - 1e-12 && value <= 0.6 + 1e-12, `每个权重落在 [0.05, 0.6],got ${value}`)
56
+ }
57
+ assert.ok(Math.abs(sumOf(weights) - 1) < 1e-9)
58
+ })
59
+
60
+ test('普通查询回退静态权重:精确等于常量表三路,无 recency 键', () => {
61
+ const weights = computeRRFWeights({ title: '缓存策略', content: 'Redis 缓存统一 30 秒过期' }, { size: 3 })
62
+ assert.deepEqual(weights, STATIC_WEIGHTS)
63
+ })
64
+
65
+ // —— computeRRFWeights:异常输入 fallback(风险表:权重边界 + fallback)——
66
+
67
+ test('异常输入 fallback:proposal/corpus 非对象或字段不可分词都回静态', () => {
68
+ const corpus = { size: 3 }
69
+ assert.deepEqual(computeRRFWeights(null, corpus), STATIC_WEIGHTS)
70
+ assert.deepEqual(computeRRFWeights(undefined, corpus), STATIC_WEIGHTS)
71
+ assert.deepEqual(computeRRFWeights(42, corpus), STATIC_WEIGHTS)
72
+ assert.deepEqual(computeRRFWeights('x', corpus), STATIC_WEIGHTS)
73
+ assert.deepEqual(computeRRFWeights({ title: '缓存' }, null), STATIC_WEIGHTS)
74
+ assert.deepEqual(computeRRFWeights({ title: '缓存' }, undefined), STATIC_WEIGHTS)
75
+ // 读取字段时抛错(getter 异常)也不往上传,按 fallback 处理
76
+ assert.deepEqual(computeRRFWeights({ get title() { throw new Error('bad') } }, corpus), STATIC_WEIGHTS)
77
+ // 近期词在 content 里同样能触发,但异常 proposal 压过一切
78
+ assert.deepEqual(computeRRFWeights(null, { title: '最近的部署' }), STATIC_WEIGHTS)
79
+ })
80
+
81
+ test('纯函数:同输入同输出,返回对象是独立副本(改写不影响下次调用)', () => {
82
+ const proposal = { title: '最近的部署', content: '昨天更新了缓存策略' }
83
+ const corpus = { size: 3 }
84
+ const a = computeRRFWeights(proposal, corpus)
85
+ const b = computeRRFWeights(proposal, corpus)
86
+ assert.deepEqual(a, b)
87
+ a.bm25 = 999
88
+ a.recency = 999
89
+ assert.deepEqual(computeRRFWeights(proposal, corpus), b)
90
+ })
91
+
92
+ // —— rankPairCandidates:动态路径与静态路径的等效与提升 ——
93
+
94
+ function equivalenceCorpus() {
95
+ return buildCorpus([
96
+ { id: 'doc-1', track: 'memory', domain: 'general', title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回。', appliesTo: ['deploy'], updatedAt: '2026-01-01T00:00:00.000Z' },
97
+ { id: 'doc-2', track: 'memory', domain: 'general', title: '咖啡拿铁', content: '用户下午只喝美式咖啡。', appliesTo: ['coffee'], updatedAt: '2026-01-02T00:00:00.000Z' },
98
+ ])
99
+ }
100
+
101
+ test('开关关闭等效:普通查询下 rrf 与静态三路公式逐位相等(权重无 recency 时动态路径退化为静态)', () => {
102
+ const corpus = equivalenceCorpus()
103
+ const proposal = { id: 'p', track: 'memory', domain: 'general', title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回。', appliesTo: ['deploy'] }
104
+ const found = rankPairCandidates({ corpus, proposal, limit: 20 })
105
+ assert.equal(found.length, 2)
106
+ // doc-1 文本与 proposal 全同 → 三路都是 rank 1;doc-2 全不相干 → 三路都是 rank 2
107
+ assert.equal(found[0].id, 'doc-1')
108
+ assert.equal(found[1].id, 'doc-2')
109
+ // 与「开关关」分支同一表达式、同一权重常量 → 严格相等
110
+ assert.equal(found[0].rrf, RRF_W_BM25 / (RRF_K + 1) + RRF_W_DICE / (RRF_K + 1) + RRF_W_ENTITY / (RRF_K + 1))
111
+ assert.equal(found[1].rrf, RRF_W_BM25 / (RRF_K + 2) + RRF_W_DICE / (RRF_K + 2) + RRF_W_ENTITY / (RRF_K + 2))
112
+ assert.equal(RRF_DYNAMIC, true, '本测试锚定开关当前默认值:开 + 静态权重 ≡ 关')
113
+ })
114
+
115
+ function recentCorpus() {
116
+ return buildCorpus([
117
+ { id: 'a-old', track: 'memory', domain: 'general', title: '缓存过期', content: '缓存过期提醒每日检查', appliesTo: [], updatedAt: '2026-01-01T00:00:00.000Z' },
118
+ { id: 'b-new', track: 'memory', domain: 'general', title: '缓存过期', content: '缓存过期提醒每日检查', appliesTo: [], updatedAt: '2026-06-01T00:00:00.000Z' },
119
+ ])
120
+ }
121
+
122
+ test('recency 查询下 updatedAt 更新的候选相对提升:rrf 差距收窄、新者增益为正、旧者为负', () => {
123
+ const corpus = recentCorpus()
124
+ const proposal = { track: 'memory', domain: 'general', title: '缓存过期', content: '昨天 缓存过期提醒每日检查' }
125
+ const found = rankPairCandidates({ corpus, proposal, limit: 20 })
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')
142
+ })
143
+
144
+ test('非近期查询下同一 corpus 不受 recency 影响:rrf 与静态公式逐位相等', () => {
145
+ const corpus = recentCorpus()
146
+ const proposal = { track: 'memory', domain: 'general', title: '缓存过期', content: '缓存过期提醒每日检查' }
147
+ 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))
150
+ })
151
+
152
+ test('结果确定性:同输入两次 rankPairCandidates / computeRRFWeights 完全一致', () => {
153
+ const corpus = recentCorpus()
154
+ const proposal = { track: 'memory', domain: 'general', title: '缓存过期', content: '昨天 缓存过期提醒每日检查' }
155
+ assert.deepEqual(rankPairCandidates({ corpus, proposal, limit: 20 }), rankPairCandidates({ corpus, proposal, limit: 20 }))
156
+ const big = equivalenceCorpus()
157
+ const bigProposal = { id: 'p', track: 'memory', domain: 'general', title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回。', appliesTo: ['deploy'] }
158
+ assert.deepEqual(rankPairCandidates({ corpus: big, proposal: bigProposal, limit: 20 }), rankPairCandidates({ corpus: big, proposal: bigProposal, limit: 20 }))
159
+ })
160
+
161
+ test('结果确定性(边界带开启):切点附近有带内候选时同输入两次 run 完全一致', () => {
162
+ // 与 tests/curator-pairing.test.mjs 的边界带守卫同一 fixture:cand-a/cand-b
163
+ // rrf 差 5.78e-5,limit=1 时 band 把 cand-b 并入评分集——这个新增分支同样
164
+ // 必须完全确定。
165
+ const twin = 'Redis 缓存统一设置 30 秒过期,命中直接返回。Redis 缓存统一设置 30 秒过期,命中直接返回。'
166
+ const tail = '。另有运维值班轮换表与告警升级路径的完整说明,这里补足长度让长度剪枝生效并保持逐字包含。'
167
+ const proposal = { title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回。', appliesTo: ['deploy'], track: 'memory', domain: 'general' }
168
+ const corpus = buildCorpus([
169
+ { id: 'cand-a', title: '缓存过期', content: twin, appliesTo: [], track: 'memory', domain: 'general' },
170
+ { id: 'cand-b', title: '缓存过期', content: twin, appliesTo: ['deploy'], track: 'memory', domain: 'general' },
171
+ { id: 'cand-c', title: '缓存过期', content: proposal.content + tail, appliesTo: [], track: 'memory', domain: 'general' },
172
+ { id: 'cand-d', title: '缓存过期', content: proposal.content + tail, appliesTo: [], track: 'memory', domain: 'general' },
173
+ ])
174
+ const run1 = rankPairCandidates({ corpus, proposal, limit: 1 })
175
+ const run2 = rankPairCandidates({ corpus, proposal, limit: 1 })
176
+ assert.deepEqual(run1, run2)
177
+ assert.equal(run1.length, 1)
178
+ assert.equal(run1[0].id, 'cand-b')
179
+ })
@@ -0,0 +1,128 @@
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-fact-version-'))
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
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
27
+ }
28
+ }
29
+
30
+ function entries(sessionId) {
31
+ const binding = state.getSessionBinding(sessionId)
32
+ return state.loadPrivateIndex(binding.libraryId).entries
33
+ }
34
+
35
+ test('two statements about one fact coexist, cross-linked, with both bodies intact', async () => {
36
+ const { exec, sessionId } = session('fact-conflict')
37
+ const first = await memory.privateRemember({
38
+ exec, title: '客厅地板颜色', content: '客厅地板是木色的,去年刚铺的。',
39
+ factKey: 'home:living_floor_color',
40
+ })
41
+ assert.equal(first.entry.fact_key, 'home:living_floor_color')
42
+ assert.equal(first.entry.version, 1)
43
+
44
+ const second = await memory.privateRemember({
45
+ exec, title: '客厅地板颜色改口', content: '客厅地板不是木色,是灰色瓷砖。',
46
+ factKey: 'home:living_floor_color',
47
+ })
48
+ assert.equal(second.entry.status, 'active', 'a conflict pair is not held for review')
49
+ assert.equal(second.entry.version, 2)
50
+ assert.equal(second.entry.conflicts_with, first.id)
51
+ assert.equal(second.conflictsWith, first.id)
52
+
53
+ const stored = entries(sessionId)
54
+ assert.equal(stored[first.id].status, 'active')
55
+ assert.equal(stored[first.id].conflicts_with, second.id, 'the pair points both ways')
56
+ assert.equal(stored[first.id].content, '客厅地板是木色的,去年刚铺的。', 'the old claim keeps its exact wording')
57
+ assert.equal(stored[second.id].content, '客厅地板不是木色,是灰色瓷砖。')
58
+ })
59
+
60
+ test('explicit supersede retires the old row without deleting its text', async () => {
61
+ const { exec, sessionId } = session('fact-supersede')
62
+ const first = await memory.privateRemember({
63
+ exec, title: '缴费日', content: '物业费每月5号缴。', factKey: 'home:fee_day',
64
+ })
65
+ const second = await memory.privateRemember({
66
+ exec, title: '缴费日补充', content: '物业费每月5号缴,遇节假日顺延。', factKey: 'home:fee_day',
67
+ })
68
+ // The second statement conflicting with the first creates v2; then an explicit
69
+ // correction supersedes v2.
70
+ const third = await memory.privateRemember({
71
+ exec, title: '缴费日最终确认', content: '物业费改成每月10号缴。',
72
+ factKey: 'home:fee_day', supersedes: second.id,
73
+ })
74
+ assert.equal(third.entry.status, 'active')
75
+ assert.equal(third.entry.version, 3)
76
+ assert.equal(third.entry.supersedes, second.id)
77
+ assert.equal(third.supersedes, second.id)
78
+
79
+ const stored = entries(sessionId)
80
+ assert.equal(stored[second.id].status, 'superseded')
81
+ assert.equal(stored[second.id].content, '物业费每月5号缴,遇节假日顺延。', 'the superseded body is still there')
82
+ assert.equal(stored[second.id].valid_to, '2026-11-06')
83
+ assert.equal(stored[second.id].supersededBy, third.id)
84
+ assert.equal(stored[first.id].content, '物业费每月5号缴。')
85
+
86
+ const recalled = await memory.privateRecall({ exec, query: '物业费缴费日', topK: 10, relevanceThreshold: 0 })
87
+ const ids = recalled.files.map((file) => file.name)
88
+ assert.ok(ids.includes(third.id), 'the current version is recallable')
89
+ assert.ok(!ids.includes(second.id), 'the superseded version is not recalled as current truth')
90
+ assert.ok(ids.includes(first.id), 'the earliest version is kept unless it was superseded too')
91
+ })
92
+
93
+ test('a compatible supplement updates the same id and does not create a version', async () => {
94
+ const { exec } = session('fact-supplement')
95
+ const first = await memory.privateRemember({
96
+ exec, title: '咖啡口味', content: '他只喝黑咖啡。', factKey: 'user:coffee',
97
+ })
98
+ const before = entries(exec.agent.session.header.id)[first.id]
99
+ const updated = await memory.privateUpdate({
100
+ exec, id: first.id, content: '他只喝黑咖啡,不加糖也不加奶。',
101
+ })
102
+ assert.equal(updated.id, first.id)
103
+ assert.equal(updated.entry.version, before.version, 'a compatible supplement is not a new version')
104
+ assert.equal(updated.entry.fact_key, 'user:coffee')
105
+ })
106
+
107
+ test('relation targets must exist, be active and share the scope', async () => {
108
+ const { exec, sessionId } = session('fact-targets')
109
+ const active = await memory.privateRemember({ exec, title: '在用的条目', content: '这条还在用。' })
110
+ await assert.rejects(
111
+ () => memory.privateRemember({ exec, title: '坏目标', content: '测试。', conflictsWith: 'mem-nope' }),
112
+ /unknown memory/,
113
+ )
114
+ await memory.privateUpdate({ exec, id: active.id, status: 'archived' })
115
+ await assert.rejects(
116
+ () => memory.privateRemember({ exec, title: '归档目标', content: '测试。', conflictsWith: active.id }),
117
+ /only an active memory/,
118
+ )
119
+ const stored = entries(sessionId)
120
+ assert.ok(!Object.values(stored).some((entry) => entry.title === '坏目标'), 'nothing is written when the target is invalid')
121
+ })
122
+
123
+ test('a derived fact_key is stored even without an explicit key', async () => {
124
+ const { exec } = session('fact-derived')
125
+ const { entry } = await memory.privateRemember({ exec, title: '窗台的绿萝', content: '窗台有一盆绿萝。' })
126
+ assert.match(entry.fact_key, /^me:窗台的绿萝$/)
127
+ assert.equal(entry.version, 1)
128
+ })