dsh-memu-memory 1.2.1 → 1.2.3

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 (105) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +23 -8
  3. package/README.zh.md +16 -6
  4. package/docs/client-conventions.md +1 -0
  5. package/docs/contributing.md +18 -4
  6. package/docs/emotion-model-spec.md +2 -2
  7. package/docs/env-and-commands.md +20 -0
  8. package/docs/host-api.md +22 -1
  9. package/docs/memory-semantics.md +30 -2
  10. package/docs/troubleshooting.md +76 -5
  11. package/lib/activity-log.js +1 -1
  12. package/lib/backup.js +24 -2
  13. package/lib/binding-diagnostics.js +2 -2
  14. package/lib/client.js +1511 -153
  15. package/lib/consolidation-worker.js +30 -8
  16. package/lib/curator-evidence.js +131 -0
  17. package/lib/curator-policy.js +81 -0
  18. package/lib/curator.js +1252 -91
  19. package/lib/cycle.js +12 -1
  20. package/lib/embedding-download.js +39 -4
  21. package/lib/engine.js +6 -3
  22. package/lib/freshness.js +97 -0
  23. package/lib/global-graph.js +282 -0
  24. package/lib/graph.js +295 -11
  25. package/lib/inbound.js +19 -0
  26. package/lib/inject.js +396 -25
  27. package/lib/lexicon.js +1115 -0
  28. package/lib/local-vector-service.js +8 -6
  29. package/lib/managed-runtime.js +33 -2
  30. package/lib/memory.js +365 -34
  31. package/lib/memu.js +2 -2
  32. package/lib/migrate.js +83 -2
  33. package/lib/private-links.js +587 -0
  34. package/lib/private.js +32 -3
  35. package/lib/prompts/global-curator.md +76 -19
  36. package/lib/prompts/private-consolidation.coding.md +4 -1
  37. package/lib/prompts/private-consolidation.md +3 -1
  38. package/lib/prompts/private-consolidation.mixed.md +3 -1
  39. package/lib/prompts/private-consolidation.rp.md +3 -1
  40. package/lib/prompts.js +1 -1
  41. package/lib/rpc.js +589 -10
  42. package/lib/salient-wake.js +402 -0
  43. package/lib/state.js +95 -1
  44. package/lib/text-retrieval.js +661 -0
  45. package/lib/text-similarity.js +36 -18
  46. package/lib/tools.js +168 -10
  47. package/lib/webui/standalone.css +17 -0
  48. package/lib/webui/standalone.js +2 -0
  49. package/package.json +1 -1
  50. package/scripts/acceptance-local.mjs +8 -5
  51. package/scripts/curator-pair-calibrate.mjs +259 -0
  52. package/scripts/drive-session.mjs +853 -0
  53. package/scripts/lexicon-calibrate.mjs +230 -0
  54. package/scripts/lexicon-dedupe.mjs +318 -0
  55. package/scripts/mock-llm.mjs +903 -0
  56. package/tests/absorb-review.test.mjs +353 -0
  57. package/tests/appendix-b2.test.mjs +2 -2
  58. package/tests/client-export.test.mjs +520 -0
  59. package/tests/client-render.test.mjs +32 -4
  60. package/tests/consolidation-fork.test.mjs +14 -12
  61. package/tests/consolidation-snapshot.test.mjs +39 -0
  62. package/tests/curator-absorb.test.mjs +443 -0
  63. package/tests/curator-calibrate.test.mjs +173 -0
  64. package/tests/curator-clusters.test.mjs +281 -0
  65. package/tests/curator-commit.test.mjs +52 -5
  66. package/tests/curator-evidence.test.mjs +102 -0
  67. package/tests/curator-link.test.mjs +316 -0
  68. package/tests/curator-pairing.test.mjs +252 -0
  69. package/tests/curator-probe.test.mjs +15 -6
  70. package/tests/curator-review-mode.test.mjs +314 -0
  71. package/tests/disclosure.test.mjs +2 -1
  72. package/tests/entity-merge.test.mjs +261 -0
  73. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -0
  74. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -0
  75. package/tests/fixtures/lexicon-stub.mjs +284 -0
  76. package/tests/fixtures/mock-llm/reply.txt +1 -0
  77. package/tests/freshness.test.mjs +140 -0
  78. package/tests/graph-cascade.test.mjs +35 -2
  79. package/tests/graph.test.mjs +96 -0
  80. package/tests/help-page.test.mjs +415 -0
  81. package/tests/inbound.test.mjs +6 -3
  82. package/tests/inject-guide.test.mjs +28 -0
  83. package/tests/inject.test.mjs +157 -5
  84. package/tests/injection-chain.test.mjs +176 -0
  85. package/tests/lexicon-calibrate.test.mjs +48 -0
  86. package/tests/lexicon-dedupe.test.mjs +171 -0
  87. package/tests/lexicon-frequency.test.mjs +179 -0
  88. package/tests/lexicon-inject.test.mjs +410 -0
  89. package/tests/lexicon-perf.test.mjs +436 -0
  90. package/tests/lexicon-ui.test.mjs +547 -0
  91. package/tests/lexicon.test.mjs +922 -0
  92. package/tests/managed-runtime.test.mjs +32 -0
  93. package/tests/mock-llm.test.mjs +225 -0
  94. package/tests/open-loop-date.test.mjs +406 -0
  95. package/tests/private-links.test.mjs +445 -0
  96. package/tests/prompts.test.mjs +35 -0
  97. package/tests/recall-dedup.test.mjs +33 -4
  98. package/tests/salient-wake.test.mjs +362 -0
  99. package/tests/settings-plumbing.test.mjs +76 -0
  100. package/tests/sidebar.test.mjs +5 -1
  101. package/tests/stubs/dsh-schedule.js +105 -0
  102. package/tests/tool-schema.test.mjs +1 -1
  103. package/tests/tools.test.mjs +112 -3
  104. package/tests/webui-auth.test.mjs +352 -2
  105. package/tests/webui.test.mjs +188 -0
@@ -0,0 +1,314 @@
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
+ import { registerHooks } from 'node:module'
7
+
8
+ // Package A (spec §6.1): curator review mode + risk score + input fixes.
9
+ //
10
+ // One entry of `memories` must land in exactly one of three states — active
11
+ // (committed), pending_review (index-only, held), or skipped — and the
12
+ // decision must follow §4.10: hard gates (conflict / missing evidence /
13
+ // invalid rewrite target) are pending in BOTH modes, `auto` passes clean
14
+ // creates and passes rewrites below the 0.70 risk threshold, `review-all`
15
+ // holds every content op. Unknown ops and invalid merge targets are skipped
16
+ // and never degrade into a create (the §0.2 bug).
17
+ //
18
+ // Same hermetic pattern as tests/curator-commit.test.mjs: './memu.js' is
19
+ // replaced before production modules load; everything else is the real module
20
+ // stack against a temp DSH_MEMU_HOME. Default settings keep the vector route
21
+ // lexical, so nothing here talks to an engine.
22
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-curator-review-'))
23
+ process.env.DSH_MEMU_HOME = home
24
+ process.env.DSH_MEMU_MEMORY_HOME = home
25
+
26
+ globalThis.__curatorReviewTest = {
27
+ async commit() { return { ok: true } },
28
+ async forget() { return { deleted: 1, segments: 1 } },
29
+ async retrieve() { return { files: [], segments: [], resources: [], raw: null } },
30
+ async listFiles() { return { recall_files: [], resources: [], raw: null } },
31
+ }
32
+
33
+ const memuSource = 'const bridge = globalThis.__curatorReviewTest;'
34
+ + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
35
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
36
+ const hooks = registerHooks({
37
+ resolve(specifier, context, nextResolve) {
38
+ if (specifier === './memu.js') return { url: 'data:text/javascript,' + encodeURIComponent(memuSource), shortCircuit: true }
39
+ return nextResolve(specifier, context)
40
+ },
41
+ })
42
+
43
+ const curator = await import('../lib/curator.js')
44
+ const state = await import('../lib/state.js')
45
+ const rpc = await import('../lib/rpc.js')
46
+
47
+ test.after(async () => {
48
+ try { hooks.unregister?.() } catch {}
49
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
50
+ })
51
+
52
+ const TARGET = 'gmem-target'
53
+ const TARGET_ENTRY = {
54
+ track: 'memory', domain: 'general', title: '部署窗口约定',
55
+ content: '每周四凌晨两点到四点是固定的部署窗口,窗口内只允许灰度发布。',
56
+ confidence: 0.9, status: 'active',
57
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
58
+ evidence: [{ sessionId: 'old', quote: 'old quote' }],
59
+ }
60
+
61
+ function seedGlobalIndex(entries = {}) {
62
+ state.saveGlobalIndex({ version: 1, entries: structuredClone(entries) })
63
+ }
64
+
65
+ // Every test sets the mode it means to exercise; nothing relies on leftover
66
+ // settings from a previous case.
67
+ function setMode(mode) {
68
+ state.updateSettings({ curatorReviewMode: mode })
69
+ }
70
+
71
+ const cleanCreate = (over = {}) => ({
72
+ op: 'create', domain: 'general', track: 'memory',
73
+ title: '独立的全新事实',
74
+ content: '用户倾向于在正式汇报里先给结论再给细节。',
75
+ confidence: 0.9,
76
+ evidence: [
77
+ { session_id: 's1', quote: '先说结论再说细节' },
78
+ { session_id: 's2', quote: '汇报的时候结论在前' },
79
+ ],
80
+ ...over,
81
+ })
82
+
83
+ function entryOf(index, predicate) {
84
+ return Object.values(index.entries).find(predicate) || null
85
+ }
86
+
87
+ test('auto + clean create with two evidence lands active with reviewRisk 0', async () => {
88
+ seedGlobalIndex({})
89
+ setMode('auto')
90
+ const result = await curator.commitCuratorOutput({ memories: [cleanCreate()] }, { job: { step: 'committing' } })
91
+ assert.equal(result.created, 1)
92
+ assert.equal(result.pending, 0)
93
+ assert.equal(result.files.length, 1)
94
+ // The risk summary is part of the contract: every written entry is counted.
95
+ assert.deepEqual(result.reviewRisk, { max: 0, flagged: 0, reasons: {} })
96
+ const index = state.loadGlobalIndex()
97
+ const entry = entryOf(index, (e) => e.title === '独立的全新事实')
98
+ assert.ok(entry, 'the create must land in the index')
99
+ assert.equal(entry.status, 'active')
100
+ assert.equal(entry.reviewRisk, 0)
101
+ assert.deepEqual(entry.reviewRiskReasons, [])
102
+ })
103
+
104
+ test('auto + create with needs_review still lands active; the flag only feeds the risk score', async () => {
105
+ seedGlobalIndex({})
106
+ setMode('auto')
107
+ const result = await curator.commitCuratorOutput({
108
+ memories: [cleanCreate({ needs_review: true, review_reason: '一次口误,证据偏薄' })],
109
+ }, { job: { step: 'committing' } })
110
+ assert.equal(result.created, 1, 'auto passes a flagged create by default')
111
+ const entry = entryOf(state.loadGlobalIndex(), (e) => e.title === '独立的全新事实')
112
+ assert.equal(entry.status, 'active')
113
+ // needs_review 0.70 + review_reason 0.20 + single-evidence 0.10 was avoided by
114
+ // passing two evidence items, so 0.70 + 0.20 = 0.90 exactly.
115
+ assert.equal(entry.reviewRisk, 0.9)
116
+ assert.ok(entry.reviewRiskReasons.includes('needs_review'))
117
+ assert.ok(entry.reviewRiskReasons.includes('review_reason'))
118
+ assert.equal(entry.reviewReason, undefined, 'an active entry carries no reviewReason')
119
+ assert.equal(result.reviewRisk.flagged, 1, 'the >=0.70 entry is flagged in the summary')
120
+ assert.equal(result.reviewRisk.max, 0.9)
121
+ })
122
+
123
+ test('auto + create with confidence 0.4 still lands active; low confidence only raises the risk score', async () => {
124
+ seedGlobalIndex({})
125
+ setMode('auto')
126
+ const result = await curator.commitCuratorOutput({
127
+ memories: [cleanCreate({ confidence: 0.4 })],
128
+ }, { job: { step: 'committing' } })
129
+ assert.equal(result.created, 1)
130
+ const entry = entryOf(state.loadGlobalIndex(), (e) => e.title === '独立的全新事实')
131
+ assert.equal(entry.status, 'active')
132
+ assert.equal(entry.reviewRisk, 0.7, 'confidence<0.50 is +0.70; the two evidence items avoid the single-evidence bump')
133
+ assert.ok(entry.reviewRiskReasons.includes('confidence<0.50'))
134
+ })
135
+
136
+ test('auto + merge with needs_review is held pending', async () => {
137
+ seedGlobalIndex({ [TARGET]: TARGET_ENTRY })
138
+ setMode('auto')
139
+ const result = await curator.commitCuratorOutput({
140
+ memories: [{
141
+ op: 'merge', domain: 'general', track: 'memory', target_id: TARGET,
142
+ title: '部署窗口的合并版本',
143
+ content: '每周四凌晨两点到四点是固定的部署窗口,窗口内只允许灰度发布,全量要等监控确认。',
144
+ confidence: 0.9, needs_review: true, review_reason: '模型标记待复核',
145
+ evidence: [{ session_id: 's3', quote: '部署窗口只在周四凌晨' }],
146
+ }],
147
+ }, { job: { step: 'committing' } })
148
+ assert.equal(result.merged, 0, 'a held merge is not counted as merged')
149
+ assert.equal(result.pending, 1)
150
+ assert.equal(result.files.length, 0, 'pending entries are never committed to the vector store')
151
+ const index = state.loadGlobalIndex()
152
+ const held = entryOf(index, (e) => e.status === 'pending_review')
153
+ assert.ok(held, 'the merge must be held for review')
154
+ assert.equal(held.conflictingWith, TARGET)
155
+ // non-hard pending: the model's own reason wins over the generic fallback.
156
+ assert.equal(held.reviewReason, '模型标记待复核')
157
+ assert.equal(held.reviewRisk, 1.2, 'needs_review 0.70 + merge 0.20 + review_reason 0.20 + single evidence 0.10')
158
+ assert.equal(index.entries[TARGET].status, 'active', 'a held merge never touches the target')
159
+ })
160
+
161
+ test('auto + conflict is pending in both modes with the hard reason', async () => {
162
+ seedGlobalIndex({ [TARGET]: TARGET_ENTRY })
163
+ setMode('auto')
164
+ const result = await curator.commitCuratorOutput({
165
+ memories: [{
166
+ op: 'conflict', domain: 'general', track: 'memory', target_id: TARGET,
167
+ title: '部署窗口的两个说法', content: '两个会话对部署窗口的说法不一致。',
168
+ confidence: 0.9,
169
+ evidence: [{ session_id: 's4', quote: '部署窗口是周四' }, { session_id: 's5', quote: '部署窗口是周五' }],
170
+ }],
171
+ }, { job: { step: 'committing' } })
172
+ assert.equal(result.pending, 1)
173
+ assert.equal(result.created, 0)
174
+ const held = entryOf(state.loadGlobalIndex(), (e) => e.status === 'pending_review')
175
+ assert.ok(held, 'a conflict is always held')
176
+ assert.equal(held.reviewReason, 'conflict')
177
+ assert.equal(held.reviewRisk, 2)
178
+ assert.deepEqual(held.reviewRiskReasons, ['conflict'])
179
+ assert.equal(held.conflictingWith, TARGET)
180
+ })
181
+
182
+ test('auto + missing evidence is pending with the hard reason', async () => {
183
+ seedGlobalIndex({})
184
+ setMode('auto')
185
+ const result = await curator.commitCuratorOutput({
186
+ memories: [{ op: 'create', domain: 'general', track: 'memory', title: '没有证据的说法', content: '模型没给引用。', confidence: 0.9 }],
187
+ }, { job: { step: 'committing' } })
188
+ assert.equal(result.created, 0)
189
+ assert.equal(result.pending, 1)
190
+ const held = entryOf(state.loadGlobalIndex(), (e) => e.status === 'pending_review')
191
+ assert.ok(held)
192
+ assert.equal(held.reviewReason, 'missing evidence')
193
+ assert.equal(held.reviewRisk, 2)
194
+ })
195
+
196
+ test('review-all holds even a clean create', async () => {
197
+ seedGlobalIndex({})
198
+ setMode('review-all')
199
+ const result = await curator.commitCuratorOutput({ memories: [cleanCreate()] }, { job: { step: 'committing' } })
200
+ assert.equal(result.created, 0)
201
+ assert.equal(result.pending, 1)
202
+ const held = entryOf(state.loadGlobalIndex(), (e) => e.status === 'pending_review')
203
+ assert.ok(held)
204
+ // Not a hard gate and the model gave no reason: the generic threshold note.
205
+ assert.equal(held.reviewReason, 'risk threshold')
206
+ assert.equal(held.reviewRisk, 0, 'a clean hold carries risk 0, the mode alone caused the hold')
207
+ })
208
+
209
+ test('merge with a nonexistent target is skipped and never degrades into a create', async () => {
210
+ seedGlobalIndex({ [TARGET]: TARGET_ENTRY })
211
+ setMode('auto')
212
+ const result = await curator.commitCuratorOutput({
213
+ memories: [{
214
+ op: 'merge', domain: 'general', track: 'memory', target_id: 'gmem-missing',
215
+ title: '没有落点的合并', content: '这段内容绝不能变成一条新记忆。',
216
+ confidence: 0.9,
217
+ evidence: [{ session_id: 's6', quote: '合并的目标丢了' }],
218
+ }],
219
+ }, { job: { step: 'committing' } })
220
+ assert.equal(result.created, 0, 'the §0.2 bug: a skipped merge must not continue as a create')
221
+ assert.equal(result.merged, 0)
222
+ assert.equal(result.pending, 0)
223
+ assert.equal(result.files.length, 0)
224
+ assert.equal(result.skipped.length, 1)
225
+ assert.match(result.skipped[0].reason, /target not found: gmem-missing/)
226
+ const index = state.loadGlobalIndex()
227
+ assert.equal(entryOf(index, (e) => e.title === '没有落点的合并'), null, 'no new entry was written')
228
+ assert.deepEqual(Object.keys(index.entries), [TARGET], 'the index gained nothing')
229
+ })
230
+
231
+ test('an unknown op is skipped instead of being forced into a create', async () => {
232
+ seedGlobalIndex({})
233
+ setMode('auto')
234
+ const result = await curator.commitCuratorOutput({
235
+ memories: [
236
+ { op: 'frobnicate', domain: 'general', track: 'memory', title: '未知操作', content: '模型写错了 op 名。', confidence: 0.9, evidence: [{ session_id: 's7', quote: '未知' }] },
237
+ // link 在 当前版本已进 OPS_ALLOWLIST(F1 落地),不再是 unknown op 的代表;
238
+ // 这里改用真正不在名单里的 op,测试意图不变:未知 op 不得默认 create。
239
+ { op: 'delete', domain: 'general', track: 'memory', title: '未接线的关联', content: '模型写错了另一个 op 名。', confidence: 0.9, evidence: [{ session_id: 's8', quote: '删除操作的原话记录' }] },
240
+ ],
241
+ }, { job: { step: 'committing' } })
242
+ assert.equal(result.created, 0, 'unknown ops must not default to create')
243
+ assert.equal(result.skipped.length, 2)
244
+ assert.ok(result.skipped.every((item) => /unknown op/.test(item.reason)))
245
+ assert.deepEqual(Object.keys(state.loadGlobalIndex().entries), [], 'nothing was written')
246
+ })
247
+
248
+ test('setSettings rejects a bogus curatorReviewMode and accepts review-all', async () => {
249
+ await assert.rejects(
250
+ () => rpc.dispatch({}, 'setSettings', { patch: { curatorReviewMode: 'bogus' } }),
251
+ /invalid setting/,
252
+ 'the enum gate must reject unknown modes',
253
+ )
254
+ const accepted = await rpc.dispatch({}, 'setSettings', { patch: { curatorReviewMode: 'review-all' } })
255
+ assert.equal(accepted.curatorReviewMode, 'review-all', 'the allowlisted mode persists')
256
+ setMode('auto')
257
+ })
258
+
259
+ test('entries written before this version carry no reviewRisk and still read cleanly', async () => {
260
+ seedGlobalIndex({ [TARGET]: TARGET_ENTRY })
261
+ setMode('auto')
262
+ const result = await curator.commitCuratorOutput({
263
+ memories: [{
264
+ op: 'supersede', domain: 'general', track: 'memory', target_id: TARGET,
265
+ title: '部署窗口的替代版本', content: '部署窗口调整为周四凌晨的整段灰度时段。',
266
+ confidence: 0.92,
267
+ evidence: [{ session_id: 's9', quote: '窗口改成周四凌晨' }, { session_id: 's10', quote: '整段灰度时段一次性放开' }],
268
+ }],
269
+ }, { job: { step: 'committing' } })
270
+ assert.equal(result.superseded, 1)
271
+ const index = state.loadGlobalIndex()
272
+ const oldEntry = index.entries[TARGET]
273
+ assert.ok(oldEntry, 'the old entry is still there (superseded, never deleted)')
274
+ assert.equal(Object.hasOwn(oldEntry, 'reviewRisk'), false, 'the old entry keeps its old shape')
275
+ assert.equal(Object.hasOwn(oldEntry, 'reviewRiskReasons'), false)
276
+ assert.equal(oldEntry.status, 'superseded')
277
+ // Reading the mixed index through the default-value convention must not throw.
278
+ for (const entry of Object.values(index.entries)) {
279
+ assert.equal(typeof (entry.reviewRisk ?? 0), 'number')
280
+ assert.ok(Array.isArray(entry.reviewRiskReasons ?? []))
281
+ }
282
+ const fresh = entryOf(index, (e) => e.status === 'active')
283
+ assert.ok(fresh, 'the replacement landed active (risk 0.20 < 0.70)')
284
+ assert.equal(fresh.reviewRisk, 0.2, 'supersede adds 0.20; two evidence items avoid the single-evidence bump')
285
+ })
286
+
287
+ test('reviewDecision unit: absorb risk and skip reasons follow §4.10 verbatim', () => {
288
+ const index = { entries: { 'gmem-a': { status: 'active' } } }
289
+ // absorb with >3 sources: +0.20; clean otherwise → auto passes at 0.20.
290
+ const absorb = curator.reviewDecision({
291
+ m: { confidence: 0.9, source_ids: ['a', 'b', 'c', 'd'] },
292
+ op: 'absorb', evidence: [{ session_id: 's', quote: 'q' }, { session_id: 's2', quote: 'q2' }],
293
+ targetId: 'gmem-a', index, mode: 'auto',
294
+ })
295
+ assert.equal(absorb.review, false)
296
+ assert.equal(absorb.risk, 0.2)
297
+ assert.ok(absorb.reasons.includes('absorb>3 sources'))
298
+ // absorb with a missing target is a skip, never a pending.
299
+ const noTarget = curator.reviewDecision({
300
+ m: { confidence: 0.9 }, op: 'absorb',
301
+ evidence: [{ session_id: 's', quote: 'q' }],
302
+ targetId: '', index, mode: 'auto',
303
+ })
304
+ assert.equal(noTarget.skip, true)
305
+ assert.match(noTarget.reason, /target not found: \(empty\)/)
306
+ // Hard gates cap at risk 2 regardless of mode.
307
+ const conflictReviewAll = curator.reviewDecision({
308
+ m: {}, op: 'conflict', evidence: [{ session_id: 's', quote: 'q' }],
309
+ targetId: 'gmem-a', index, mode: 'review-all',
310
+ })
311
+ assert.equal(conflictReviewAll.review, true)
312
+ assert.equal(conflictReviewAll.risk, 2)
313
+ assert.equal(conflictReviewAll.hard, true)
314
+ })
@@ -90,7 +90,8 @@ test('a secret stays out of the anchor but is still reachable through recall', a
90
90
  assert.equal(anchor.text.includes('PINNED-SECRET-BODY'), false, 'pinning does not override secrecy')
91
91
  assert.equal(anchor.text.includes(secretId), false)
92
92
  assert.equal(anchor.text.includes(pinnedSecretId), false)
93
- assert.ok(anchor.text.includes('SHARED-BODY'), 'ordinary memories still show up')
93
+ assert.ok(anchor.text.includes('deploy window'), 'ordinary memories still show up as title cards')
94
+ assert.equal(anchor.text.includes('SHARED-BODY'), false, 'the anchor never carries the body')
94
95
 
95
96
  const recalled = await memory.privateRecall({ exec, query: 'leave company diagnosis deploy window', topK: 5, relevanceThreshold: 0 })
96
97
  assert.ok(recalled.files.some((file) => file.name === secretId), 'a secret is a recall target, not a hidden row')
@@ -0,0 +1,261 @@
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
+ // 工单 F:实体主节点合并(§9)。断言针对库内实体文件与私有索引的真实落盘状态,
8
+ // 不 mock 存储层——合并的价值就在于两个文件一起收敛,且中途失败不能留下悬空边。
9
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-entity-merge-'))
10
+ process.env.DSH_MEMU_HOME = home
11
+ const state = await import('../lib/state.js')
12
+ const graph = await import('../lib/graph.js')
13
+ const { indexDir } = await import('../lib/paths.js')
14
+ const { listEvents } = await import('../lib/activity-log.js')
15
+
16
+ test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
17
+
18
+ function newLibrary(name) {
19
+ return state.ensureSession(name, { cwd: path.join(home, name), agentPreset: 'rp' }).libraryId
20
+ }
21
+ const entitiesFile = (libraryId) => path.join(indexDir(), `${libraryId}.entities.json`)
22
+ const readStore = (libraryId) => JSON.parse(fs.readFileSync(entitiesFile(libraryId), 'utf8'))
23
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
24
+
25
+ test('mergeEntities remaps every link to the target, dedupes (to, kind) and deletes the sources', () => {
26
+ const libraryId = newLibrary('merge-core')
27
+ const target = graph.createEntity({ libraryId, name: 'Lin Mian', kind: 'person', aliases: ['Mian'] })
28
+ const source1 = graph.createEntity({ libraryId, name: 'Lin', kind: 'person', aliases: ["Mian'er"] })
29
+ const source2 = graph.createEntity({ libraryId, name: 'Mian', kind: 'person', aliases: ['Lin Mian'] })
30
+ state.savePrivateIndex(libraryId, { entries: {
31
+ 'mem-merge-a': { title: 'a', content: 'a scene', status: 'active', visibility: 'shared', links: [
32
+ { to: source1.id, kind: 'person', note: 'Lin is the person this scene is about.', confidence: 0.9 },
33
+ { to: target.id, kind: 'person', note: 'The pre-existing target edge wins the dedupe.', confidence: 0.4 },
34
+ { to: source1.id, kind: 'relation', note: 'Lin is related to the events in this scene.', confidence: 0.5 },
35
+ { to: 'mem-merge-b', kind: 'event', note: 'The same event seen from another side.', confidence: 0.6 },
36
+ ] },
37
+ 'mem-merge-b': { title: 'b', content: 'b scene', status: 'active', visibility: 'shared', links: [
38
+ { to: source2.id, kind: 'person', note: 'Mian is the person this scene is about.', confidence: 0.8, source: 'auto' },
39
+ { to: source1.id, kind: 'person', note: 'The same person named Lin again.', confidence: 0.7 },
40
+ ] },
41
+ } })
42
+
43
+ const result = graph.mergeEntities({ libraryId, targetId: target.id, sourceIds: [source1.id, source2.id] })
44
+ assert.equal(result.targetId, target.id)
45
+ assert.deepEqual(result.merged, [source1.id, source2.id])
46
+ assert.equal(result.remappedLinks, 4, 'every link that pointed at a source is redirected')
47
+ assert.equal(result.duplicateLinks, 2, 'the second (to, kind) pair per entry is dropped')
48
+ assert.deepEqual(result.relationships, { moved: 0, conflicts: [] })
49
+ assert.deepEqual(result.droppedAliases, [])
50
+ assert.deepEqual(result.aliases, ['Mian', 'Lin', "Mian'er", 'Lin Mian'])
51
+
52
+ const index = state.loadPrivateIndex(libraryId)
53
+ const allLinks = Object.values(index.entries).flatMap(entry => entry.links || [])
54
+ assert.ok(allLinks.every(link => link.to !== source1.id && link.to !== source2.id), 'no link survives pointing at a merged source')
55
+ const aLinks = index.entries['mem-merge-a'].links
56
+ assert.equal(aLinks.filter(link => link.to === target.id && link.kind === 'person').length, 1)
57
+ assert.equal(aLinks.find(link => link.to === target.id && link.kind === 'person').note, 'The pre-existing target edge wins the dedupe.')
58
+ assert.equal(aLinks.find(link => link.to === target.id && link.kind === 'relation').confidence, 0.5)
59
+ const bLinks = index.entries['mem-merge-b'].links
60
+ assert.equal(bLinks.length, 1, 'the duplicate source edge is dropped')
61
+ assert.equal(bLinks[0].to, target.id)
62
+ assert.equal(bLinks[0].source, 'auto', 'auto metadata survives the merge')
63
+
64
+ const store = graph.graphExport(libraryId)
65
+ assert.equal(store.entities[source1.id], undefined)
66
+ assert.equal(store.entities[source2.id], undefined)
67
+ assert.equal(store.entities[target.id].name, 'Lin Mian', 'the target name stays the display name')
68
+ assert.deepEqual(store.entities[target.id].aliases, ['Mian', 'Lin', "Mian'er", 'Lin Mian'])
69
+
70
+ const view = graph.getGraph({ libraryId, focusId: 'mem-merge-b', depth: 1 })
71
+ assert.ok(view.nodes.some(node => node.id === target.id && node.title === 'Lin Mian'))
72
+ assert.ok(!view.nodes.some(node => node.id === source1.id || node.id === source2.id), 'getGraph resolves the merged ids, not placeholders')
73
+
74
+ const events = listEvents({ limit: 100, kind: 'write' })
75
+ const event = events.find(item => item.detail?.op === 'entity-merge' && item.detail?.targetId === target.id)
76
+ assert.ok(event, 'the merge is recorded in the activity log')
77
+ assert.deepEqual(event.refs, [target.id, source1.id, source2.id])
78
+ assert.equal(event.ok, true)
79
+ })
80
+
81
+ test('mergeEntities unions aliases, caps at 30 and reports the dropped tail', () => {
82
+ const libraryId = newLibrary('merge-aliases')
83
+ const targetAliases = Array.from({ length: 10 }, (_, index) => `target-alias-${index}`)
84
+ const source1Aliases = Array.from({ length: 25 }, (_, index) => `source-one-alias-${index}`)
85
+ const source2Aliases = Array.from({ length: 10 }, (_, index) => `source-two-alias-${index}`)
86
+ const target = graph.createEntity({ libraryId, name: 'Alias Target', kind: 'person', aliases: targetAliases })
87
+ const source1 = graph.createEntity({ libraryId, name: 'Alias Source One', kind: 'person', aliases: source1Aliases })
88
+ const source2 = graph.createEntity({ libraryId, name: 'Alias Source Two', kind: 'person', aliases: source2Aliases })
89
+ const union = [...targetAliases, 'Alias Source One', ...source1Aliases, 'Alias Source Two', ...source2Aliases]
90
+
91
+ const result = graph.mergeEntities({ libraryId, targetId: target.id, sourceIds: [source1.id, source2.id] })
92
+ assert.equal(result.aliases.length, 30)
93
+ assert.deepEqual(result.aliases, union.slice(0, 30))
94
+ assert.deepEqual(result.droppedAliases, union.slice(30))
95
+ assert.equal(result.droppedAliases.length, union.length - 30)
96
+ const stored = readStore(libraryId).entities[target.id]
97
+ assert.ok(stored, 'the merge target is never collected by the safety-net prune, even while unreferenced')
98
+ assert.equal(stored.name, 'Alias Target')
99
+ assert.deepEqual(stored.aliases, union.slice(0, 30))
100
+ })
101
+
102
+ test('mergeEntities rejects kind mismatches, self-sources, empty lists and unknown ids without writing', () => {
103
+ const libraryId = newLibrary('merge-validation')
104
+ const otherLibraryId = newLibrary('merge-validation-other')
105
+ const keep = graph.createEntity({ libraryId, name: 'Keep', kind: 'person' })
106
+ const otherKind = graph.createEntity({ libraryId, name: 'Keep Place', kind: 'place' })
107
+ const peer = graph.createEntity({ libraryId, name: 'Peer', kind: 'person' })
108
+ const foreign = graph.createEntity({ libraryId: otherLibraryId, name: 'Foreign', kind: 'person' })
109
+ state.savePrivateIndex(libraryId, { entries: {
110
+ 'mem-validation': { title: 'validation', content: 'validation scene', status: 'active', visibility: 'shared', links: [
111
+ { to: peer.id, kind: 'person', note: 'Peer is the person this scene is about.', confidence: 0.9 },
112
+ ] },
113
+ } })
114
+ const before = fs.readFileSync(entitiesFile(libraryId), 'utf8')
115
+ assert.throws(() => graph.mergeEntities({ libraryId, targetId: keep.id, sourceIds: [otherKind.id] }), /different kinds/)
116
+ assert.throws(() => graph.mergeEntities({ libraryId, targetId: keep.id, sourceIds: [keep.id] }), /own sources/)
117
+ assert.throws(() => graph.mergeEntities({ libraryId, targetId: keep.id, sourceIds: [] }), /non-empty array/)
118
+ assert.throws(() => graph.mergeEntities({ libraryId, targetId: keep.id }), /non-empty array/)
119
+ assert.throws(() => graph.mergeEntities({ libraryId, targetId: keep.id, sourceIds: [peer.id, 'ent-ghost'] }), /unknown entity/)
120
+ assert.throws(() => graph.mergeEntities({ libraryId, targetId: keep.id, sourceIds: [foreign.id] }), /unknown entity/, 'an id that lives in another library is not mergeable here')
121
+ assert.throws(() => graph.mergeEntities({ libraryId, targetId: 'ent-ghost', sourceIds: [peer.id] }), /unknown entity/)
122
+ assert.throws(() => graph.mergeEntities({ targetId: keep.id, sourceIds: [peer.id] }), /no bound session/)
123
+ assert.equal(fs.readFileSync(entitiesFile(libraryId), 'utf8'), before, 'a rejected merge never rewrites the entity store')
124
+ const links = state.loadPrivateIndex(libraryId).entries['mem-validation'].links
125
+ assert.deepEqual(links.map(link => link.to), [peer.id])
126
+ })
127
+
128
+ test('mergeEntities re-keys relationship snapshots, preserves the target side and reports conflicts', () => {
129
+ const libraryId = newLibrary('merge-relationships')
130
+ const target = graph.createEntity({ libraryId, name: 'Target', kind: 'person' })
131
+ const source1 = graph.createEntity({ libraryId, name: 'Source One', kind: 'person' })
132
+ const source2 = graph.createEntity({ libraryId, name: 'Source Two', kind: 'person' })
133
+ const buddy = graph.createEntity({ libraryId, name: 'Buddy', kind: 'person' })
134
+ const companion = graph.createEntity({ libraryId, name: 'Companion', kind: 'person' })
135
+ const orphan = graph.createEntity({ libraryId, name: 'Orphan', kind: 'person' })
136
+ state.savePrivateIndex(libraryId, { entries: {
137
+ 'mem-rel-evidence': { title: 'evidence', content: 'evidence scene', status: 'active', visibility: 'shared' },
138
+ } })
139
+ graph.updateRelationship({ libraryId, fromId: target.id, toId: buddy.id, state: { trust: 0.2 }, evidenceIds: ['mem-rel-evidence'], reason: 'The target-side snapshot is the older evidence.' })
140
+ graph.updateRelationship({ libraryId, fromId: source1.id, toId: buddy.id, state: { trust: 0.9 }, evidenceIds: ['mem-rel-evidence'], reason: 'The source-side snapshot is the newer evidence.' })
141
+ graph.updateRelationship({ libraryId, fromId: buddy.id, toId: source1.id, state: { warmth: 0.4 }, evidenceIds: ['mem-rel-evidence'], reason: 'The reverse direction is its own snapshot.' })
142
+ graph.updateRelationship({ libraryId, fromId: buddy.id, toId: source1.id, state: { warmth: 0.5 }, evidenceIds: ['mem-rel-evidence'], reason: 'A second revision gives the snapshot history.' })
143
+ graph.updateRelationship({ libraryId, fromId: source1.id, toId: source2.id, state: { trust: 0.3 }, evidenceIds: ['mem-rel-evidence'], reason: 'A source-only snapshot becomes a self loop.' })
144
+ graph.updateRelationship({ libraryId, fromId: source2.id, toId: companion.id, state: { familiarity: 0.6 }, evidenceIds: ['mem-rel-evidence'], reason: 'A source behind the relationship moves with it.' })
145
+
146
+ const result = graph.mergeEntities({ libraryId, targetId: target.id, sourceIds: [source1.id, source2.id] })
147
+ assert.deepEqual(result.relationships, {
148
+ moved: 2,
149
+ conflicts: [
150
+ { key: JSON.stringify([source1.id, buddy.id]), reason: 'existing-target', keptKey: JSON.stringify([target.id, buddy.id]) },
151
+ { key: JSON.stringify([source1.id, source2.id]), reason: 'self' },
152
+ ],
153
+ })
154
+ const kept = graph.getRelationship({ libraryId, fromId: target.id, toId: buddy.id }).relationship
155
+ assert.equal(kept.state.trust, 0.2, 'the existing target-side snapshot is not overwritten')
156
+ assert.equal(kept.revision, 1)
157
+ const moved = graph.getRelationship({ libraryId, fromId: buddy.id, toId: target.id }).relationship
158
+ assert.equal(moved.fromId, buddy.id)
159
+ assert.equal(moved.toId, target.id)
160
+ assert.equal(moved.state.warmth, 0.5)
161
+ assert.equal(moved.history.length, 1, 'history moves with the snapshot')
162
+ assert.equal(moved.revision, 2)
163
+ const movedOut = graph.getRelationship({ libraryId, fromId: target.id, toId: companion.id }).relationship
164
+ assert.equal(movedOut.state.familiarity, 0.6)
165
+ assert.equal(graph.getRelationship({ libraryId, fromId: source1.id, toId: buddy.id }).relationship, null, 'no old source key survives')
166
+ const store = graph.graphExport(libraryId)
167
+ assert.ok(Object.keys(store.relationships).every(key => !key.includes(source1.id) && !key.includes(source2.id)))
168
+ assert.equal(store.entities[orphan.id], undefined, 'the prune safety net collected the unrelated orphan')
169
+ assert.ok(store.entities[target.id], 'the target itself stays')
170
+ })
171
+
172
+ test('suggestEntityMerges: containment and normalization produce shorter→longer pairs', () => {
173
+ const libraryId = newLibrary('suggest-names')
174
+ const lin = graph.createEntity({ libraryId, name: 'Lin', kind: 'person' })
175
+ const linMian = graph.createEntity({ libraryId, name: 'Lin Mian', kind: 'person' })
176
+ const lower = graph.createEntity({ libraryId, name: 'lin', kind: 'person' })
177
+ const yuike = graph.createEntity({ libraryId, name: 'YUIKE', kind: 'person' })
178
+ const tanaka = graph.createEntity({ libraryId, name: 'yuike tanaka', kind: 'person' })
179
+ const place = graph.createEntity({ libraryId, name: 'Lin Road', kind: 'place' })
180
+
181
+ const { items } = graph.suggestEntityMerges({ libraryId })
182
+ const pair = (source, target) => items.find(item => item.sourceId === source.id && item.targetId === target.id)
183
+ assert.ok(pair(lin, linMian), 'the shorter normalized name folds into the longer one')
184
+ assert.ok(pair(lower, linMian))
185
+ assert.equal(pair(lin, linMian).reason, 'containment')
186
+ assert.ok(pair(yuike, tanaka), 'NFKC/case folding finds the full-width variant')
187
+ assert.ok(!items.some(item => (item.sourceId === lin.id && item.targetId === lower.id) || (item.sourceId === lower.id && item.targetId === lin.id)),
188
+ 'identical normalized names are not a candidate')
189
+ assert.ok(!items.some(item => (item.sourceId === place.id && item.targetId === lin.id) || (item.sourceId === lin.id && item.targetId === place.id)),
190
+ 'different kinds never pair up')
191
+ assert.ok(!items.some(item => item.sourceId === place.id || item.targetId === place.id), 'the place has no same-kind candidate')
192
+ })
193
+
194
+ test('suggestEntityMerges: near-miss spellings within two edits are candidates, with a stable direction', async () => {
195
+ const libraryId = newLibrary('suggest-edit')
196
+ const kyle = graph.createEntity({ libraryId, name: 'Kyle', kind: 'person' })
197
+ await sleep(5)
198
+ const kile = graph.createEntity({ libraryId, name: 'Kile', kind: 'person' })
199
+ await sleep(5)
200
+ const marcus = graph.createEntity({ libraryId, name: 'Marcus', kind: 'person' })
201
+ await sleep(5)
202
+ const marcos = graph.createEntity({ libraryId, name: 'Marcos', kind: 'person' })
203
+
204
+ const first = graph.suggestEntityMerges({ libraryId })
205
+ const second = graph.suggestEntityMerges({ libraryId })
206
+ assert.deepEqual(first, second, 'suggestion order is deterministic')
207
+ assert.equal(first.items.length, 2)
208
+ assert.ok(first.items.every(item => item.reason === 'edit-distance'))
209
+ assert.deepEqual(first.items.find(item => [item.sourceId, item.targetId].includes(kyle.id)),
210
+ { sourceId: kile.id, targetId: kyle.id, reason: 'edit-distance' }, 'equal length folds into the older id')
211
+ assert.deepEqual(first.items.find(item => [item.sourceId, item.targetId].includes(marcus.id)),
212
+ { sourceId: marcos.id, targetId: marcus.id, reason: 'edit-distance' })
213
+ })
214
+
215
+ test('suggestEntityMerges: kind mismatch and identical folded names yield no candidates', () => {
216
+ const libraryId = newLibrary('suggest-filter')
217
+ graph.createEntity({ libraryId, name: 'Aria', kind: 'person' })
218
+ graph.createEntity({ libraryId, name: 'Ariadne', kind: 'place' })
219
+ graph.createEntity({ libraryId, name: 'Mika', kind: 'person' })
220
+ graph.createEntity({ libraryId, name: 'MIKA', kind: 'person' })
221
+ assert.deepEqual(graph.suggestEntityMerges({ libraryId }), { items: [] })
222
+ })
223
+
224
+ test('suggestEntityMerges: unrelated names yield an empty list', () => {
225
+ const libraryId = newLibrary('suggest-none')
226
+ graph.createEntity({ libraryId, name: 'Zephyr', kind: 'person' })
227
+ graph.createEntity({ libraryId, name: 'Quartz', kind: 'person' })
228
+ assert.deepEqual(graph.suggestEntityMerges({ libraryId }).items, [])
229
+ })
230
+
231
+ test('suggestEntityMerges caps the list at 20 and never writes', () => {
232
+ const libraryId = newLibrary('suggest-cap')
233
+ for (let index = 0; index < 25; index += 1) {
234
+ const suffix = String(index).padStart(2, '0')
235
+ graph.createEntity({ libraryId, name: `NestBase${suffix}`, kind: 'person' })
236
+ graph.createEntity({ libraryId, name: `NestBase${suffix}Extra`, kind: 'person' })
237
+ }
238
+ const file = entitiesFile(libraryId)
239
+ const before = fs.readFileSync(file, 'utf8')
240
+ const first = graph.suggestEntityMerges({ libraryId })
241
+ const second = graph.suggestEntityMerges({ libraryId })
242
+ assert.equal(fs.readFileSync(file, 'utf8'), before, 'suggesting is a pure read')
243
+ assert.deepEqual(second, first)
244
+ assert.equal(first.items.length, 20)
245
+ assert.ok(first.items.every(item => item.sourceId && item.targetId && item.sourceId !== item.targetId))
246
+ assert.ok(first.items.every(item => item.reason === 'containment' || item.reason === 'edit-distance'))
247
+ })
248
+
249
+ test('the RPC cases take exactly the payload the graph panel sends', async () => {
250
+ const libraryId = newLibrary('rpc-shape')
251
+ const target = graph.createEntity({ libraryId, name: '林眠儿', kind: 'person' })
252
+ const source = graph.createEntity({ libraryId, name: '林眠', kind: 'person' })
253
+ const rpc = await import('../lib/rpc.js')
254
+ const suggested = await rpc.dispatch({}, 'suggestEntityMerges', { libraryId })
255
+ assert.deepEqual(suggested.items, [{ sourceId: source.id, targetId: target.id, reason: 'containment' }])
256
+ // 面板一次只确认一对:sourceIds 是数组,但 UI 传的就是单个来源。
257
+ const merged = await rpc.dispatch({}, 'mergeEntities', { libraryId, targetId: target.id, sourceIds: [source.id] })
258
+ assert.equal(merged.targetId, target.id)
259
+ assert.deepEqual(merged.merged, [source.id])
260
+ assert.ok(merged.aliases.includes('林眠'), 'the source name becomes an alias of the main node')
261
+ })