dsh-memu-memory 1.3.1 → 1.3.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 (58) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +57 -0
  3. package/README.md +8 -7
  4. package/README.zh.md +8 -5
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/mobile.jpg +0 -0
  7. package/assets/screenshots/relations.jpg +0 -0
  8. package/assets/screenshots/settings.jpg +0 -0
  9. package/assets/screenshots/stats.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +11 -0
  13. package/docs/contributing.md +6 -4
  14. package/docs/env-and-commands.md +12 -1
  15. package/docs/memory-semantics.md +8 -2
  16. package/docs/troubleshooting.md +24 -6
  17. package/lib/auto-link/apply.js +249 -0
  18. package/lib/auto-link/candidates.js +155 -0
  19. package/lib/auto-link/decide.js +304 -0
  20. package/lib/auto-link/normalize.js +99 -0
  21. package/lib/auto-link/policy.js +42 -0
  22. package/lib/auto-link/suppression.js +101 -0
  23. package/lib/auto-link/terminology.js +265 -0
  24. package/lib/binding-diagnostics.js +2 -2
  25. package/lib/client.js +1509 -72
  26. package/lib/graph.js +269 -18
  27. package/lib/memory.js +11 -0
  28. package/lib/memu.js +7 -6
  29. package/lib/private-links.js +105 -137
  30. package/lib/private.js +138 -38
  31. package/lib/rpc.js +73 -8
  32. package/lib/state.js +7 -2
  33. package/lib/tools.js +4 -2
  34. package/lib/webui/graph-LICENSE.txt +1 -62
  35. package/lib/webui/graph-view.bundle.js +1 -1
  36. package/lib/webui/graph-view.js +921 -126
  37. package/lib/webui/standalone.js +3 -3
  38. package/package.json +1 -2
  39. package/scripts/build-graph.mjs +35 -7
  40. package/scripts/check-all.mjs +2 -0
  41. package/scripts/check-graph-browser.mjs +106 -23
  42. package/scripts/make-readme-shots.mjs +59 -0
  43. package/scripts/rebuild-auto-links.mjs +252 -0
  44. package/tests/audit-regression.test.mjs +11 -8
  45. package/tests/auto-link-candidates.test.mjs +161 -0
  46. package/tests/auto-link-decide.test.mjs +512 -0
  47. package/tests/auto-link-migration.test.mjs +133 -0
  48. package/tests/browser.test.mjs +27 -0
  49. package/tests/client-render.test.mjs +178 -6
  50. package/tests/consolidation-fork.test.mjs +148 -0
  51. package/tests/cycle.test.mjs +1 -1
  52. package/tests/graph-view.test.mjs +221 -22
  53. package/tests/graph.test.mjs +5 -0
  54. package/tests/help-page.test.mjs +3 -3
  55. package/tests/memu-resident-route.test.mjs +130 -0
  56. package/tests/private-links.test.mjs +81 -45
  57. package/tests/stubs/child-process-spy.mjs +14 -0
  58. package/tests/tools.test.mjs +24 -18
@@ -0,0 +1,512 @@
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 { performance } from 'node:perf_hooks'
7
+
8
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-autolink-'))
9
+ process.env.DSH_MEMU_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
11
+
12
+ const state = await import('../lib/state.js')
13
+ const memory = await import('../lib/memory.js')
14
+ const graph = await import('../lib/graph.js')
15
+ const decide = await import('../lib/auto-link/decide.js')
16
+ const apply = await import('../lib/auto-link/apply.js')
17
+ const suppression = await import('../lib/auto-link/suppression.js')
18
+ const normalize = await import('../lib/auto-link/normalize.js')
19
+ const policy = await import('../lib/auto-link/policy.js')
20
+ const privateLinks = await import('../lib/private-links.js')
21
+ const rpc = await import('../lib/rpc.js')
22
+
23
+ test.after(() => {
24
+ try { state.flushState() } catch {}
25
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
26
+ })
27
+
28
+ let counter = 0
29
+ function library(name) {
30
+ counter += 1
31
+ const binding = state.ensureSession(`autolink-${name}-${counter}`, { cwd: path.join(home, `ws-${name}-${counter}`), agentPreset: 'rp' })
32
+ return binding.libraryId
33
+ }
34
+
35
+ const at = (day) => `2026-11-${String(day).padStart(2, '0')}T00:00:00.000Z`
36
+
37
+ function entry(title, content, extra = {}) {
38
+ return { title, content, status: 'active', visibility: 'shared', layer: 'long_term', createdAt: at(1), updatedAt: at(1), ...extra }
39
+ }
40
+
41
+ function index(entries) {
42
+ return { version: 1, entries }
43
+ }
44
+
45
+ // ---------------------------------------------------------------- normalization
46
+
47
+ test('mentions are boundary-aware and punctuation-insensitive: CJK substrings, identifiers, NFKC folding', () => {
48
+ assert.equal(normalize.mentionCount('yuike 和 yuikeee', 'yuike'), 1, 'Latin must not match a longer identifier')
49
+ assert.equal(normalize.mentionCount('YUIKE!来了', 'yuike'), 1, 'full-width and punctuation fold away')
50
+ assert.equal(normalize.mentionCount('星宫雲来了,星宫雲走了', '星宫雲'), 2)
51
+ // §8.1: NFKC + 去标点/空白 applies to the name as well as the text.
52
+ assert.equal(normalize.mentionCount('小·柚来了', '小柚'), 1)
53
+ assert.equal(normalize.mentionCount('小 柚来了', '小柚'), 1)
54
+ assert.equal(normalize.mentionCount('小柚来了', '小 柚'), 1)
55
+ // §2: code identifiers keep their punctuation and their word boundaries.
56
+ assert.equal(normalize.mentionCount('Yuike_01 上线', 'Yuike_01'), 1)
57
+ assert.equal(normalize.mentionCount('yuike.dev is down', 'yuike.dev'), 1)
58
+ assert.equal(normalize.mentionCount('星宫雲-yuike 来了', '星宫雲-yuike'), 1)
59
+ assert.equal(normalize.firstMention('猫娘yuike', 'yuike'), 2)
60
+ assert.equal(normalize.firstMention('「小·柚」来了', '小柚'), 1, 'offset is the raw text position, not the compact index')
61
+ assert.equal(normalize.isMentionSurface('小'), false, 'one CJK character is not a surface')
62
+ assert.equal(normalize.isMentionSurface('小柚'), true)
63
+ assert.equal(normalize.isMentionSurface('a'), false, 'one Latin character is not a surface')
64
+ })
65
+
66
+ test('punctuated and identifier surfaces produce mention edges with raw offsets', () => {
67
+ const lib = library('punct')
68
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person', status: 'confirmed' })
69
+ const yuike = graph.createEntity({ libraryId: lib, name: 'yuike_01', kind: 'person', status: 'confirmed' })
70
+ const mixed = graph.createEntity({ libraryId: lib, name: '星宫雲-yuike', kind: 'person', status: 'confirmed' })
71
+ const snapshot = index({
72
+ 'mem-a': entry('「小·柚」来了', '她带着伞。'),
73
+ 'mem-b': entry('yuike_01 上线', 'yuike_01 迟到了。'),
74
+ 'mem-c': entry('星宫雲-yuike 到访', '星宫雲-yuike 和 星宫雲 yuike 都来了。'),
75
+ })
76
+ const edges = decide.decideAutoLinks({ index: snapshot, entities: [you, yuike, mixed] })
77
+ const mention = edges.filter(edge => edge.rule === 'entity-mention')
78
+ assert.equal(mention.length, 3, JSON.stringify(mention.map(edge => `${edge.from}->${edge.to}`)))
79
+ for (const edge of edges) assert.ok(policy.EVIDENCE_RULES.includes(edge.rule), 'only the declared rule vocabulary: ' + edge.rule)
80
+ const byEntity = new Map(mention.map(edge => [edge.to, edge]))
81
+ const youEdge = byEntity.get(you.id)
82
+ assert.equal(youEdge.evidence.surface, '小柚')
83
+ assert.equal(youEdge.evidence.offset, 1, 'raw offset inside 「小·柚」')
84
+ assert.ok(byEntity.has(yuike.id), 'identifier with underscore is found')
85
+ assert.ok(byEntity.has(mixed.id), 'mixed CJK-Latin name is found')
86
+ })
87
+
88
+ // ---------------------------------------------------------------- decision layer
89
+
90
+ test('only confirmed entities produce mention edges; provisional, archived and secret rows do not', () => {
91
+ const lib = library('mention')
92
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person', aliases: ['柚子'], status: 'confirmed', confirmedBy: 'user' })
93
+ graph.createEntity({ libraryId: lib, name: '未晞', kind: 'person' })
94
+ graph.createEntity({ libraryId: lib, name: '阿兰', kind: 'person', status: 'archived' })
95
+ const snapshot = index({
96
+ 'mem-a': entry('小柚今天来了', '她带了一篮柚子。'),
97
+ 'mem-b': entry('未晞的日记', '未晞写下了今天的安排。'),
98
+ 'mem-c': entry('阿兰回信', '阿兰说下周再联系。'),
99
+ 'mem-d': entry('小柚与秘密', '关于小柚的一件不能外传的事。', { visibility: 'secret' }),
100
+ 'mem-e': entry('小柚旧事', '小柚很久以前来过。', { status: 'archived' }),
101
+ })
102
+ const edges = decide.decideAutoLinks({ index: snapshot, entities: [you, { id: 'ent-provisional', name: '未晞', kind: 'person', status: 'provisional' }, { id: 'ent-archived', name: '阿兰', kind: 'person', status: 'archived' }] })
103
+ const mention = edges.filter(edge => edge.rule === 'entity-mention')
104
+ assert.equal(mention.length, 1, 'one eligible memory mentions the confirmed entity')
105
+ assert.equal(mention[0].from, 'mem-a')
106
+ assert.equal(mention[0].to, you.id)
107
+ assert.equal(mention[0].kind, 'person')
108
+ assert.equal(mention[0].confidence, 1)
109
+ assert.equal(mention[0].schemaVersion, 2)
110
+ assert.ok(mention[0].evidence.surface === '小柚' || mention[0].evidence.surface === '柚子')
111
+ assert.equal(mention[0].evidence.entityId, you.id)
112
+ assert.equal(mention[0].evidence.field, 'title')
113
+ assert.equal(mention[0].evidence.offset, 0)
114
+ })
115
+
116
+ test('suppression removes a decided edge and decide stays pure', () => {
117
+ const lib = library('suppress')
118
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person', status: 'confirmed' })
119
+ const snapshot = index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') })
120
+ const first = decide.decideAutoLinks({ index: snapshot, entities: [you] })
121
+ const second = decide.decideAutoLinks({ index: snapshot, entities: [you] })
122
+ assert.deepEqual(second, first, 'same input -> same output')
123
+ const key = suppression.suppressionKey(first[0])
124
+ const suppressed = decide.decideAutoLinks({ index: snapshot, entities: [you], suppression: new Set([key]) })
125
+ assert.deepEqual(suppressed, [])
126
+ })
127
+
128
+ test('field evidence builds conflict, supersede and fact-key edges without cliques', () => {
129
+ const lib = library('fields')
130
+ const snapshot = index({
131
+ 'mem-a': entry('说法一', '内容一。', { conflicts_with: 'mem-b' }),
132
+ 'mem-b': entry('说法二', '内容二。', { conflicts_with: 'mem-a' }),
133
+ 'mem-c': entry('新版本', '更新后的说法。', { supersedes: 'mem-d' }),
134
+ 'mem-d': entry('旧版本', '旧的说明。', { status: 'superseded' }),
135
+ 'mem-e': entry('同一事实 1', '第一版。', { fact_key: 'k1', context: { worldId: 'w1' }, createdAt: at(1), updatedAt: at(1), version: 1 }),
136
+ 'mem-f': entry('同一事实 2', '第二版。', { fact_key: 'k1', context: { worldId: 'w1' }, createdAt: at(2), updatedAt: at(2), version: 2 }),
137
+ 'mem-g': entry('同一事实 3', '第三版。', { fact_key: 'k1', context: { worldId: 'w1' }, createdAt: at(3), updatedAt: at(3), version: 3, conflicts_with: 'mem-f' }),
138
+ })
139
+ const edges = decide.decideAutoLinks({ index: snapshot, entities: [] })
140
+ const conflicts = edges.filter(edge => edge.rule === 'conflict')
141
+ assert.equal(conflicts.length, 3, 'a<->b plus g->f (the reverse f->g is not a field)')
142
+ assert.ok(conflicts.some(edge => edge.from === 'mem-a' && edge.to === 'mem-b' && edge.kind === 'conflict'))
143
+ assert.ok(conflicts.some(edge => edge.from === 'mem-b' && edge.to === 'mem-a'))
144
+ assert.ok(conflicts.some(edge => edge.from === 'mem-g' && edge.to === 'mem-f'))
145
+ const supersedes = edges.filter(edge => edge.rule === 'supersede')
146
+ assert.deepEqual(supersedes.map(edge => `${edge.from}->${edge.to}:${edge.kind}`), ['mem-c->mem-d:supersede'])
147
+ const factKey = edges.filter(edge => edge.rule === 'fact-key')
148
+ assert.deepEqual(factKey.map(edge => `${edge.from}->${edge.to}`), ['mem-f->mem-e'], 'chain, not a clique; g-f is already a conflict')
149
+ })
150
+
151
+ // ---------------------------------------------------------------- write layer
152
+
153
+ test('apply writes evidence and never overwrites a manual edge', () => {
154
+ const lib = library('apply')
155
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person', status: 'confirmed' })
156
+ state.savePrivateIndex(lib, index({
157
+ 'mem-a': entry('小柚来了', '小柚进门坐下。'),
158
+ 'mem-b': entry('小柚与阿柚', '小柚提起阿柚。', {
159
+ links: [{ to: you.id, kind: 'person', note: '用户手动确认过这条关系。', confidence: 0.9 }],
160
+ }),
161
+ }))
162
+ const edges = decide.decideAutoLinks({ index: state.loadPrivateIndex(lib), entities: [you] })
163
+ const applied = apply.applyAutoEdges({ libraryId: lib, edges, entities: [you] })
164
+ assert.equal(applied.added, 1)
165
+ assert.equal(applied.skippedManual, 1, 'the manual memory→entity edge wins')
166
+ const after = state.loadPrivateIndex(lib)
167
+ const link = after.entries['mem-a'].links[0]
168
+ assert.equal(link.source, 'auto')
169
+ assert.equal(link.confidence, 1)
170
+ assert.equal(link.evidence.rule, 'entity-mention')
171
+ assert.equal(link.evidence.entityId, you.id)
172
+ assert.match(link.note, /已确认实体/)
173
+ assert.equal(after.entries['mem-b'].links.length, 1)
174
+ assert.equal(after.entries['mem-b'].links[0].source, undefined, 'the manual edge is untouched')
175
+ const again = apply.applyAutoEdges({ libraryId: lib, edges, entities: [you] })
176
+ assert.equal(again.added, 0, 'the same decision is a no-op')
177
+ assert.equal(again.updated, 0)
178
+ })
179
+
180
+ // ---------------------------------------------------------------- entity lifecycle
181
+
182
+ test('confirming an entity flips its status and backfills mention edges immediately', () => {
183
+ const lib = library('confirm')
184
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person' })
185
+ assert.equal(you.status, 'provisional', 'creation alone does not confirm')
186
+ state.savePrivateIndex(lib, index({
187
+ 'mem-a': entry('小柚来了', '小柚进门坐下。'),
188
+ 'mem-b': entry('小柚的伞', '小柚把伞落在门口。'),
189
+ }))
190
+ const confirmed = graph.confirmEntities({ libraryId: lib, entityIds: [you.id], by: 'user' })
191
+ assert.deepEqual(confirmed.confirmed, [you.id])
192
+ assert.equal(confirmed.entities, 2, 'both memories gained an edge in the same action')
193
+ const store = graph.graphExport(lib)
194
+ assert.equal(store.entities[you.id].status, 'confirmed')
195
+ assert.equal(store.entities[you.id].confirmedBy, 'user')
196
+ assert.ok(store.entities[you.id].confirmedAt)
197
+ const rows = state.loadPrivateIndex(lib)
198
+ assert.ok((rows.entries['mem-a'].links || []).some(link => link.to === you.id && link.evidence?.rule === 'entity-mention'))
199
+ const again = graph.confirmEntities({ libraryId: lib, entityIds: [you.id], by: 'user' })
200
+ assert.deepEqual(again.confirmed, [])
201
+ assert.equal(again.entities, 0, 'confirming twice is a no-op')
202
+ })
203
+
204
+ test('renaming a confirmed entity retires stale mention edges and attaches the new surface', () => {
205
+ const lib = library('rename')
206
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person' })
207
+ state.savePrivateIndex(lib, index({
208
+ 'mem-a': entry('小柚来了', '小柚进门坐下。'),
209
+ 'mem-b': entry('柚子来了', '柚子带着伞。'),
210
+ }))
211
+ graph.confirmEntities({ libraryId: lib, entityIds: [you.id], by: 'user' })
212
+ assert.ok((state.loadPrivateIndex(lib).entries['mem-a'].links || []).some(link => link.to === you.id))
213
+ graph.renameEntity({ libraryId: lib, entityId: you.id, name: '柚子', aliases: [] })
214
+ const rows = state.loadPrivateIndex(lib)
215
+ assert.equal((rows.entries['mem-a'].links || []).some(link => link.to === you.id), false, 'old name no longer matches')
216
+ assert.ok((rows.entries['mem-b'].links || []).some(link => link.to === you.id && link.evidence?.surface === '柚子'))
217
+ })
218
+
219
+ test('merging a confirmed source into a provisional target confirms it and remaps evidence', () => {
220
+ const lib = library('merge')
221
+ const source = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person' })
222
+ state.savePrivateIndex(lib, index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') }))
223
+ graph.confirmEntities({ libraryId: lib, entityIds: [source.id], by: 'user' })
224
+ const target = graph.createEntity({ libraryId: lib, name: '柚子', kind: 'person' })
225
+ graph.mergeEntities({ libraryId: lib, targetId: target.id, sourceIds: [source.id] })
226
+ const store = graph.graphExport(lib)
227
+ assert.equal(store.entities[target.id].status, 'confirmed', 'a confirmed source confirms the surviving row')
228
+ assert.deepEqual(store.entities[target.id].aliases, ['小柚'])
229
+ const link = (state.loadPrivateIndex(lib).entries['mem-a'].links || []).find(item => item.to === target.id)
230
+ assert.ok(link, 'the mention edge points at the merged row')
231
+ assert.equal(link.evidence.entityId, target.id)
232
+ })
233
+
234
+ test('deleting an entity records suppression for the auto edges it collects', () => {
235
+ const lib = library('delete')
236
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person' })
237
+ state.savePrivateIndex(lib, index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') }))
238
+ graph.confirmEntities({ libraryId: lib, entityIds: [you.id], by: 'user' })
239
+ graph.deleteEntity({ libraryId: lib, entityId: you.id, force: true })
240
+ const store = suppression.readSuppression(lib)
241
+ const keys = Object.keys(store.entries)
242
+ assert.ok(keys.includes(`mem-a|${you.id}|person|entity-mention`), 'the collected edge key is suppressed: ' + keys.join(','))
243
+ })
244
+
245
+ test('removing an auto edge by hand suppresses it against the next recompute', () => {
246
+ const lib = library('unlink')
247
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person' })
248
+ state.savePrivateIndex(lib, index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') }))
249
+ graph.confirmEntities({ libraryId: lib, entityIds: [you.id], by: 'user' })
250
+ const removed = graph.unlinkEntry({ libraryId: lib, fromId: 'mem-a', toId: you.id, kind: 'person' })
251
+ assert.equal(removed.removed, 1)
252
+ const set = suppression.suppressionSet(lib)
253
+ assert.ok(set.has(`mem-a|${you.id}|person|entity-mention`))
254
+ assert.ok(set.has(`mem-a|${you.id}|person|*`), 'the triple wildcard is written too')
255
+ apply.refreshEntityMentions({ libraryId: lib, entity: graph.graphExport(lib).entities[you.id], suppression: set })
256
+ assert.equal((state.loadPrivateIndex(lib).entries['mem-a'].links || []).some(link => link.to === you.id), false, 'suppressed edge stays gone')
257
+ })
258
+
259
+ test('deleting a legacy auto edge also blocks the later entity-mention edge (P6)', () => {
260
+ const lib = library('legacy-suppress')
261
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person' })
262
+ state.savePrivateIndex(lib, index({
263
+ 'mem-a': entry('小柚来了', '小柚进门坐下。', {
264
+ links: [{ to: you.id, kind: 'person', note: '旧算法自动建立的实体枢纽。', confidence: 0.65, source: 'auto' }],
265
+ }),
266
+ }))
267
+ const removed = graph.unlinkEntry({ libraryId: lib, fromId: 'mem-a', toId: you.id, kind: 'person' })
268
+ assert.equal(removed.removed, 1)
269
+ const set = suppression.suppressionSet(lib)
270
+ assert.ok(set.has(`mem-a|${you.id}|person|auto`), 'the legacy edge had no rule')
271
+ // Confirming the entity would normally rebuild the mention edge; the deleted
272
+ // fact must stay deleted even though the rule string changed.
273
+ const result = graph.confirmEntities({ libraryId: lib, entityIds: [you.id], by: 'user' })
274
+ assert.equal(result.entities, 0)
275
+ assert.equal((state.loadPrivateIndex(lib).entries['mem-a'].links || []).length, 0, 'the edge does not come back under entity-mention')
276
+ })
277
+
278
+ test('purgeAutoLinks removes only auto edges, keeps a manual edge byte-for-byte and suppresses', () => {
279
+ const lib = library('purge')
280
+ state.savePrivateIndex(lib, index({
281
+ 'mem-a': entry('a', 'a', {
282
+ links: [
283
+ { to: 'mem-b', kind: 'relation', note: '手动边,必须原样保留。', confidence: 0.7 },
284
+ { to: 'mem-b', kind: 'event', note: '自动边,应被清理。', confidence: 1, source: 'auto', evidence: { rule: 'fact-key', field: 'fact_key' } },
285
+ ],
286
+ }),
287
+ 'mem-b': entry('b', 'b'),
288
+ }))
289
+ const before = JSON.parse(JSON.stringify(state.loadPrivateIndex(lib).entries['mem-a'].links[0]))
290
+ const result = graph.purgeAutoLinks({ libraryId: lib })
291
+ assert.equal(result.removed, 1)
292
+ const after = state.loadPrivateIndex(lib).entries['mem-a'].links
293
+ assert.equal(after.length, 1)
294
+ assert.deepEqual(after[0], before, 'the manual edge object is untouched')
295
+ assert.ok(suppression.suppressionSet(lib).has('mem-a|mem-b|event|*'), 'the removed pair is suppressed')
296
+ })
297
+
298
+ test('off mode closes explicit mention maintenance too, and apply rejects unknown rules', () => {
299
+ const lib = library('off-mode')
300
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person' })
301
+ state.savePrivateIndex(lib, index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') }))
302
+ state.updateSettings({ autoLinkMode: 'off' })
303
+ try {
304
+ const result = graph.confirmEntities({ libraryId: lib, entityIds: [you.id], by: 'user' })
305
+ assert.deepEqual(result.confirmed, [you.id], 'status still changes')
306
+ assert.equal(result.entities, 0, 'off writes no edge')
307
+ assert.equal((state.loadPrivateIndex(lib).entries['mem-a'].links || []).length, 0)
308
+ // A hand-supplied edge outside the evidence vocabulary is refused by the writer.
309
+ state.savePrivateIndex(lib, index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') }))
310
+ const applied = apply.applyAutoEdges({
311
+ libraryId: lib,
312
+ entities: [you],
313
+ edges: [{ from: 'mem-a', to: you.id, kind: 'person', rule: 'made-up', evidence: { rule: 'made-up' } }],
314
+ })
315
+ assert.equal(applied.skipped, 1)
316
+ assert.equal((state.loadPrivateIndex(lib).entries['mem-a'].links || []).length, 0)
317
+ } finally {
318
+ state.updateSettings({ autoLinkMode: 'suggest' })
319
+ }
320
+ })
321
+
322
+ test('clearLinkSuppression removes markers and the deterministic rebuild restores the edge', async () => {
323
+ const lib = library('clear-suppress')
324
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person' })
325
+ state.savePrivateIndex(lib, index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') }))
326
+ state.updateSettings({ autoLinkMode: 'deterministic' })
327
+ try {
328
+ graph.confirmEntities({ libraryId: lib, entityIds: [you.id], by: 'user' })
329
+ graph.unlinkEntry({ libraryId: lib, fromId: 'mem-a', toId: you.id, kind: 'person' })
330
+ assert.ok(suppression.suppressionSet(lib).size > 0)
331
+ assert.equal((state.loadPrivateIndex(lib).entries['mem-a'].links || []).length, 0)
332
+ const cleared = await rpc.dispatch({}, 'clearLinkSuppression', { libraryId: lib })
333
+ assert.ok(cleared.cleared >= 1)
334
+ assert.equal(suppression.suppressionSet(lib).size, 0)
335
+ assert.ok((state.loadPrivateIndex(lib).entries['mem-a'].links || []).some(link => link.to === you.id), 'the full rebuild restores the deleted edge')
336
+ } finally {
337
+ state.updateSettings({ autoLinkMode: 'suggest' })
338
+ }
339
+ })
340
+
341
+ test('switching to deterministic backfills entities confirmed while off', async () => {
342
+ const lib = library('mode-switch')
343
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person' })
344
+ state.savePrivateIndex(lib, index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') }))
345
+ state.updateSettings({ autoLinkMode: 'off' })
346
+ try {
347
+ const off = graph.confirmEntities({ libraryId: lib, entityIds: [you.id], by: 'user' })
348
+ assert.equal(off.entities, 0)
349
+ assert.equal((state.loadPrivateIndex(lib).entries['mem-a'].links || []).length, 0)
350
+ await rpc.dispatch({}, 'setSettings', { patch: { autoLinkMode: 'deterministic' } })
351
+ const links = state.loadPrivateIndex(lib).entries['mem-a'].links || []
352
+ assert.ok(links.some(link => link.to === you.id && link.evidence?.rule === 'entity-mention'), 'the switch rebuilds missing mentions')
353
+ } finally {
354
+ state.updateSettings({ autoLinkMode: 'suggest' })
355
+ }
356
+ })
357
+
358
+ test('re-confirming an already-confirmed entity backfills missing mentions', () => {
359
+ const lib = library('reconfirm')
360
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person', status: 'confirmed' })
361
+ state.savePrivateIndex(lib, index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') }))
362
+ const result = graph.confirmEntities({ libraryId: lib, entityIds: [you.id], by: 'user' })
363
+ assert.deepEqual(result.confirmed, [], 'it was already confirmed')
364
+ assert.equal(result.entities, 1, 'the refresh still runs and attaches the edge')
365
+ assert.ok((state.loadPrivateIndex(lib).entries['mem-a'].links || []).some(link => link.to === you.id))
366
+ })
367
+
368
+ test('three automatic passes in suggest mode add no edges', async () => {
369
+ state.updateSettings({ autoLinkMode: 'suggest' })
370
+ try {
371
+ const lib = library('suggest-three')
372
+ graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person', status: 'confirmed' })
373
+ state.savePrivateIndex(lib, index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') }))
374
+ for (let pass = 0; pass < 3; pass += 1) {
375
+ const result = await privateLinks.refreshPrivateAutoLinks({ libraryId: lib, ids: ['mem-a'] })
376
+ assert.equal(result.skipped, 'suggest')
377
+ }
378
+ assert.equal((state.loadPrivateIndex(lib).entries['mem-a'].links || []).length, 0)
379
+ } finally {
380
+ state.updateSettings({ autoLinkMode: 'suggest' })
381
+ }
382
+ })
383
+
384
+ test('confirming eight entities backfills all mentions in one batch (8 x 9 = 72)', () => {
385
+ const lib = library('batch-confirm')
386
+ const names = Array.from({ length: 8 }, (_, i) => `角色${i + 1}`)
387
+ const entities = names.map(name => graph.createEntity({ libraryId: lib, name, kind: 'person' }))
388
+ const entries = {}
389
+ for (let i = 0; i < 9; i += 1) entries[`mem-${i}`] = entry(`第 ${i} 场`, names.join('、') + ' 都在场。')
390
+ state.savePrivateIndex(lib, index(entries))
391
+ const result = graph.confirmEntities({ libraryId: lib, entityIds: entities.map(entity => entity.id), by: 'user' })
392
+ assert.equal(result.confirmed.length, 8)
393
+ assert.equal(result.entities, 72, '9 memories x 8 entities')
394
+ const second = graph.confirmEntities({ libraryId: lib, entityIds: entities.map(entity => entity.id), by: 'user' })
395
+ assert.deepEqual(second.confirmed, [])
396
+ assert.equal(second.entities, 0)
397
+ })
398
+
399
+ test('a broken entity store makes the automatic refresh fail open (warn, no throw)', async () => {
400
+ const lib = library('broken-entities')
401
+ state.savePrivateIndex(lib, index({ 'mem-a': entry('小柚来了', '小柚进门坐下。') }))
402
+ const file = path.join(home, 'index', `${lib}.entities.json`)
403
+ fs.mkdirSync(path.dirname(file), { recursive: true })
404
+ fs.writeFileSync(file, '{not json', 'utf8')
405
+ state.updateSettings({ autoLinkMode: 'deterministic' })
406
+ try {
407
+ const result = await privateLinks.refreshPrivateAutoLinks({ libraryId: lib, ids: ['mem-a'] })
408
+ assert.equal(result.skipped, 'entities')
409
+ assert.equal(result.applied, null)
410
+ } finally {
411
+ state.updateSettings({ autoLinkMode: 'suggest' })
412
+ fs.rmSync(file, { force: true })
413
+ }
414
+ })
415
+
416
+ test('field evidence stays linear: 10k full rebuild and a 10-id incremental stay in budget', () => {
417
+ const entries = {}
418
+ for (let i = 0; i < 10000; i += 1) {
419
+ const id = `mem-${String(i).padStart(5, '0')}`
420
+ const row = entry(`记忆 ${i}`, `第 ${i} 条正文。`, { createdAt: at(1), updatedAt: at(1) })
421
+ if (i % 10 === 1) row.conflicts_with = `mem-${String(i - 1).padStart(5, '0')}`
422
+ if (i % 20 === 1) {
423
+ // 200-row fact families stress the grouping/sort path as well as the count.
424
+ row.fact_key = `k${Math.floor(i / 200)}`
425
+ row.context = { worldId: `w${Math.floor(i / 200)}` }
426
+ row.version = i % 200
427
+ }
428
+ entries[id] = row
429
+ }
430
+ const snapshot = index(entries)
431
+ const startedFull = performance.now()
432
+ const full = decide.fieldEvidenceEdges(snapshot)
433
+ const fullMs = performance.now() - startedFull
434
+ const sample = Object.keys(entries).slice(0, 10)
435
+ const startedInc = performance.now()
436
+ const incremental = decide.fieldEvidenceEdgesFor(snapshot, sample)
437
+ const incMs = performance.now() - startedInc
438
+ assert.ok(full.length > 900, 'the fixture really produces conflict/fact-key edges: ' + full.length)
439
+ assert.ok(incremental.length > 0)
440
+ assert.ok(fullMs < 5000, `10k full rebuild took ${Math.round(fullMs)} ms (design budget <5000)`)
441
+ assert.ok(incMs < 500, `10-id incremental took ${Math.round(incMs)} ms (design budget <50, allow CI slack)`)
442
+ })
443
+
444
+ // ---------------------------------------------------------------- write-path hooks
445
+
446
+ test('a private write carrying conflicts_with gets its evidence edges immediately', async () => {
447
+ state.updateSettings({ autoLinkMode: 'deterministic' })
448
+ try {
449
+ const cwd = path.join(home, 'ws-write-hook')
450
+ const binding = state.ensureSession('write-hook', { cwd, agentPreset: 'rp' })
451
+ const exec = { agent: { session: { header: { id: 'write-hook', cwd, agentPreset: 'rp' } } } }
452
+ const first = await memory.privateRemember({ exec, title: '周五安排', content: '旧说法:周五去书店。' })
453
+ const second = await memory.privateRemember({ exec, title: '周五安排', content: '新说法:周五改去河边。', conflictsWith: first.id })
454
+ assert.equal(second.conflictsWith, first.id)
455
+ const index = state.loadPrivateIndex(binding.libraryId)
456
+ const forward = (index.entries[second.id].links || []).find(link => link.to === first.id)
457
+ assert.ok(forward, 'the new entry links to the conflicting version')
458
+ assert.equal(forward.kind, 'conflict')
459
+ assert.equal(forward.evidence?.rule, 'conflict')
460
+ assert.equal(forward.confidence, 1)
461
+ const reverse = (index.entries[first.id].links || []).find(link => link.to === second.id)
462
+ assert.ok(reverse, 'memory.js writes the reverse field; the reverse edge follows')
463
+ assert.equal(reverse.evidence?.rule, 'conflict')
464
+ } finally {
465
+ state.updateSettings({ autoLinkMode: 'suggest' })
466
+ }
467
+ })
468
+
469
+ test('review accept refreshes the supersede edge immediately and stays silent in suggest mode', async () => {
470
+ const lib = library('review-hook')
471
+ const seed = () => index({
472
+ 'mem-old': entry('周五安排', '旧说法:周五去书店。'),
473
+ 'mem-new': entry('周五安排', '新说法:周五改去河边。', { status: 'pending_review', conflictingWith: 'mem-old' }),
474
+ })
475
+ state.savePrivateIndex(lib, seed())
476
+ state.updateSettings({ autoLinkMode: 'deterministic' })
477
+ try {
478
+ await memory.resolveMemoryReview({ libraryId: lib, id: 'mem-new', action: 'accept', resolution: 'replace', sessionId: null })
479
+ const links = state.loadPrivateIndex(lib).entries['mem-new'].links || []
480
+ const edge = links.find(link => link.to === 'mem-old')
481
+ assert.ok(edge, 'the supersede edge is written with the review commit')
482
+ assert.equal(edge.kind, 'supersede')
483
+ assert.equal(edge.evidence?.rule, 'supersede')
484
+
485
+ state.savePrivateIndex(lib, seed())
486
+ state.updateSettings({ autoLinkMode: 'suggest' })
487
+ await memory.resolveMemoryReview({ libraryId: lib, id: 'mem-new', action: 'accept', resolution: 'replace', sessionId: null })
488
+ const after = state.loadPrivateIndex(lib).entries['mem-new'].links || []
489
+ assert.equal(after.some(link => link.evidence?.rule === 'supersede'), false, 'suggest mode never writes an edge')
490
+ } finally {
491
+ state.updateSettings({ autoLinkMode: 'suggest' })
492
+ }
493
+ })
494
+
495
+ // ---------------------------------------------------------------- recall governance
496
+
497
+ test('recallRelations ignores entity-mention edges even at confidence 1.0 but keeps field evidence', () => {
498
+ const lib = library('recall')
499
+ const you = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person', status: 'confirmed' })
500
+ state.savePrivateIndex(lib, index({
501
+ 'mem-a': entry('小柚来了', '小柚进门坐下。', {
502
+ links: [
503
+ { to: you.id, kind: 'person', note: '提及已确认实体「小柚」(标题)。', confidence: 1, source: 'auto', evidence: { rule: 'entity-mention', entityId: you.id, surface: '小柚', field: 'title', offset: 0 } },
504
+ { to: 'mem-b', kind: 'conflict', note: '字段证据:conflicts_with 指向这条记忆。', confidence: 1, source: 'auto', evidence: { rule: 'conflict', field: 'conflicts_with' } },
505
+ ],
506
+ }),
507
+ 'mem-b': entry('另一种说法', '内容不同。'),
508
+ }))
509
+ const related = graph.recallRelations(lib, state.loadPrivateIndex(lib), 'mem-a', null)
510
+ assert.deepEqual(related.map(item => item.id), ['mem-b'], 'the mention edge never takes a top-2 seat')
511
+ assert.equal(related[0].kind, 'conflict')
512
+ })
@@ -0,0 +1,133 @@
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-migration-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+ process.env.DSH_MEMU_MEMORY_HOME = home
10
+
11
+ const state = await import('../lib/state.js')
12
+ const graph = await import('../lib/graph.js')
13
+ const { runRebuildAutoLinks, parseArgs } = await import('../scripts/rebuild-auto-links.mjs')
14
+
15
+ test.after(() => {
16
+ try { state.flushState() } catch {}
17
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
18
+ })
19
+
20
+ function entry(title, content, links = []) {
21
+ return { title, content, status: 'active', visibility: 'shared', layer: 'long_term', createdAt: '2026-11-01T00:00:00.000Z', updatedAt: '2026-11-01T00:00:00.000Z', ...(links.length ? { links } : {}) }
22
+ }
23
+
24
+ test('argument parsing defaults to a dry run', () => {
25
+ assert.deepEqual(parseArgs(['node', 'script']), { apply: false, json: false, library: null, home: null, estimateTop: 8, includeArchived: false })
26
+ const applied = parseArgs(['node', 'script', '--apply', '--library', 'lib_x', '--estimate-top', '10', '--include-archived'])
27
+ assert.equal(applied.apply, true)
28
+ assert.equal(applied.includeArchived, true)
29
+ assert.throws(() => parseArgs(['node', 'script', '--nope']), /unknown argument/)
30
+ })
31
+
32
+ test('one corrupt library is reported without stopping the rest', async () => {
33
+ const good = state.ensureSession('migration-good', { cwd: path.join(home, 'ws-good'), agentPreset: 'rp' }).libraryId
34
+ state.savePrivateIndex(good, { version: 1, entries: { 'mem-good': entry('正常库', '正常内容。') } })
35
+ const bad = state.ensureSession('migration-bad', { cwd: path.join(home, 'ws-bad'), agentPreset: 'rp' }).libraryId
36
+ state.savePrivateIndex(bad, { version: 1, entries: { 'mem-bad': entry('坏库', '坏内容。') } })
37
+ const badStore = path.join(home, 'index', `${bad}.entities.json`)
38
+ fs.mkdirSync(path.dirname(badStore), { recursive: true })
39
+ fs.writeFileSync(badStore, '{not json', 'utf8')
40
+ try {
41
+ const report = await runRebuildAutoLinks({ apply: false, json: true, log: () => {} })
42
+ assert.equal(report.ok, false)
43
+ assert.ok(report.failures.some(item => item.libraryId === bad), 'the corrupt library is reported: ' + JSON.stringify(report.failures))
44
+ assert.ok(report.libraries.some(item => item.libraryId === good), 'the healthy library still ran')
45
+ } finally {
46
+ fs.rmSync(badStore, { force: true })
47
+ }
48
+ })
49
+
50
+ test('dry run reports legacy edges and writes no entity status or edge', async () => {
51
+ const binding = state.ensureSession('migration-dry', { cwd: path.join(home, 'ws-dry'), agentPreset: 'rp' })
52
+ const lib = binding.libraryId
53
+ const legacyEntity = graph.createEntity({ libraryId: lib, name: '旧实体', kind: 'person' })
54
+ // Simulate pre-status rows again (createEntity now always writes a status).
55
+ const file = path.join(home, 'index', `${lib}.entities.json`)
56
+ const store = JSON.parse(fs.readFileSync(file, 'utf8'))
57
+ delete store.entities[legacyEntity.id].status
58
+ fs.writeFileSync(file, JSON.stringify(store, null, 2), 'utf8')
59
+ state.savePrivateIndex(lib, { version: 1, entries: {
60
+ 'mem-a': entry('旧记录', '旧内容。', [
61
+ { to: 'mem-b', kind: 'relation', note: '旧的词面自动关联,没有任何证据字段。', confidence: 0.66, source: 'auto' },
62
+ { to: 'mem-b', kind: 'event', note: '用户手动建立的一条边,不能被迁移删掉。', confidence: 0.8 },
63
+ ]),
64
+ 'mem-b': entry('另一条旧记录', '另一个内容。'),
65
+ } })
66
+ const report = await runRebuildAutoLinks({ apply: false, json: true, log: () => {} })
67
+ const row = report.libraries.find(item => item.libraryId === lib)
68
+ assert.equal(row.legacyAutoEdges, 1)
69
+ assert.equal(row.nonAutoEdges, 1)
70
+ assert.equal(row.grading.provisional, 1, 'the status-less row is planned as provisional')
71
+ const after = state.loadPrivateIndex(lib)
72
+ assert.equal((after.entries['mem-a'].links || []).filter(link => link.source === 'auto').length, 1, 'dry run keeps edges')
73
+ assert.equal(JSON.parse(fs.readFileSync(file, 'utf8')).entities[legacyEntity.id].status, undefined, 'dry run keeps statuses')
74
+ })
75
+
76
+ test('apply backs up, removes legacy auto edges, grades rows and rebuilds confirmed mentions', async () => {
77
+ const binding = state.ensureSession('migration-apply', { cwd: path.join(home, 'ws-apply'), agentPreset: 'rp' })
78
+ const lib = binding.libraryId
79
+ const confirmed = graph.createEntity({ libraryId: lib, name: '小柚', kind: 'person', status: 'confirmed' })
80
+ const provisional = graph.createEntity({ libraryId: lib, name: '未晞', kind: 'person' })
81
+ state.savePrivateIndex(lib, { version: 1, entries: {
82
+ 'mem-a': entry('小柚来了,未晞也在', '小柚进门,未晞在窗边。', [
83
+ { to: 'mem-b', kind: 'relation', note: '旧的词面自动关联,没有任何证据字段。', confidence: 0.66, source: 'auto' },
84
+ { to: 'mem-b', kind: 'event', note: '用户手动建立的一条边,不能被迁移删掉。', confidence: 0.8 },
85
+ ]),
86
+ 'mem-b': entry('另一条记录', '只有小柚出现。'),
87
+ } })
88
+ const report = await runRebuildAutoLinks({ apply: true, json: true, log: () => {} })
89
+ assert.ok(report.backup, 'apply takes a backup first')
90
+ assert.ok(fs.existsSync(report.backup), 'the backup directory exists')
91
+ // Rollback material: the pre-migration index (legacy edge included) is in the backup.
92
+ const backupIndex = path.join(report.backup, 'index', `${lib}.json`)
93
+ assert.ok(fs.existsSync(backupIndex), 'the backup carries this library index')
94
+ const beforeIndex = JSON.parse(fs.readFileSync(backupIndex, 'utf8'))
95
+ assert.ok((beforeIndex.entries['mem-a'].links || []).some(link => link.source === 'auto' && !link.evidence?.rule), 'the backup still holds the legacy edge')
96
+ const row = report.libraries.find(item => item.libraryId === lib)
97
+ assert.equal(row.legacyRemoved, 1)
98
+ assert.equal(row.remainingLegacyAutoEdges, 0, 'no marker-less auto edge survives')
99
+ assert.ok(row.rebuiltAutoEdges >= 2, 'confirmed entity mentions are rebuilt: ' + row.rebuiltAutoEdges)
100
+ const index = state.loadPrivateIndex(lib)
101
+ const links = index.entries['mem-a'].links || []
102
+ assert.equal(links.some(link => link.source === 'auto' && !link.evidence?.rule), false)
103
+ assert.equal(links.some(link => link.kind === 'event' && link.source === undefined), true, 'manual edge untouched')
104
+ assert.ok(links.some(link => link.to === confirmed.id && link.evidence?.rule === 'entity-mention'))
105
+ assert.equal(links.some(link => link.to === provisional.id), false, 'provisional entities produce no edges')
106
+ const store = graph.graphExport(lib)
107
+ assert.equal(store.entities[provisional.id].status, 'provisional')
108
+ assert.equal(store.entities[confirmed.id].status, 'confirmed')
109
+ })
110
+
111
+ test('a second dry run after apply sees no legacy edges (idempotent)', async () => {
112
+ const report = await runRebuildAutoLinks({ apply: false, json: true, log: () => {} })
113
+ for (const row of report.libraries) {
114
+ assert.equal(row.legacyAutoEdges, 0, row.libraryId + ' still has legacy auto edges')
115
+ }
116
+ })
117
+
118
+ test('archived libraries are skipped by default and counted, included on request', async () => {
119
+ const lib = state.ensureSession('migration-archived', { cwd: path.join(home, 'ws-archived'), agentPreset: 'rp' }).libraryId
120
+ state.savePrivateIndex(lib, { version: 1, entries: {
121
+ 'mem-a': entry('旧记录', '旧内容。', [
122
+ { to: 'mem-b', kind: 'relation', note: '旧的词面自动关联,没有任何证据字段。', confidence: 0.6, source: 'auto' },
123
+ ]),
124
+ 'mem-b': entry('另一条', '另一个内容。'),
125
+ } })
126
+ state.archiveLibrary(lib)
127
+ const dry = await runRebuildAutoLinks({ apply: false, json: true, log: () => {} })
128
+ assert.ok(dry.skippedArchived.libraries >= 1)
129
+ assert.ok(dry.skippedArchived.legacyAutoEdges >= 1)
130
+ assert.equal(dry.libraries.some(row => row.libraryId === lib), false, 'archived library is not migrated by default')
131
+ const withArchived = await runRebuildAutoLinks({ apply: false, json: true, includeArchived: true, log: () => {} })
132
+ assert.ok(withArchived.libraries.some(row => row.libraryId === lib), '--include-archived reaches it')
133
+ })