dsh-memu-memory 1.3.1 → 1.3.2

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 (46) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -1
  4. package/docs/contributing.md +2 -2
  5. package/docs/env-and-commands.md +12 -1
  6. package/docs/memory-semantics.md +8 -2
  7. package/docs/troubleshooting.md +9 -6
  8. package/lib/auto-link/apply.js +249 -0
  9. package/lib/auto-link/candidates.js +155 -0
  10. package/lib/auto-link/decide.js +304 -0
  11. package/lib/auto-link/normalize.js +99 -0
  12. package/lib/auto-link/policy.js +42 -0
  13. package/lib/auto-link/suppression.js +101 -0
  14. package/lib/auto-link/terminology.js +265 -0
  15. package/lib/binding-diagnostics.js +2 -2
  16. package/lib/client.js +1412 -69
  17. package/lib/graph.js +269 -18
  18. package/lib/memory.js +11 -0
  19. package/lib/memu.js +7 -6
  20. package/lib/private-links.js +105 -137
  21. package/lib/private.js +138 -38
  22. package/lib/rpc.js +67 -7
  23. package/lib/state.js +7 -2
  24. package/lib/tools.js +4 -2
  25. package/lib/webui/graph-LICENSE.txt +1 -62
  26. package/lib/webui/graph-view.bundle.js +1 -1
  27. package/lib/webui/graph-view.js +891 -124
  28. package/lib/webui/standalone.js +3 -3
  29. package/package.json +1 -2
  30. package/scripts/build-graph.mjs +3 -3
  31. package/scripts/check-graph-browser.mjs +106 -23
  32. package/scripts/rebuild-auto-links.mjs +252 -0
  33. package/tests/audit-regression.test.mjs +11 -8
  34. package/tests/auto-link-candidates.test.mjs +161 -0
  35. package/tests/auto-link-decide.test.mjs +512 -0
  36. package/tests/auto-link-migration.test.mjs +133 -0
  37. package/tests/client-render.test.mjs +7 -6
  38. package/tests/consolidation-fork.test.mjs +148 -0
  39. package/tests/cycle.test.mjs +1 -1
  40. package/tests/graph-view.test.mjs +163 -21
  41. package/tests/graph.test.mjs +5 -0
  42. package/tests/help-page.test.mjs +3 -3
  43. package/tests/memu-resident-route.test.mjs +130 -0
  44. package/tests/private-links.test.mjs +81 -45
  45. package/tests/stubs/child-process-spy.mjs +14 -0
  46. package/tests/tools.test.mjs +24 -18
@@ -23,17 +23,17 @@
23
23
  }
24
24
  // 页序只留这一份 slug 清单;PAGE_NAMES 的键由 check-i18n.mjs 与
25
25
  // client.js 的 SETTINGS_PAGES 对齐校验,避免第三份清单漂移。
26
- var SETTINGS_PAGES = ['engine', 'connection', 'settings', 'folders', 'libraries', 'browser', 'global', 'prompts', 'stats', 'memories', 'logs', 'lexicon', 'help']
26
+ var SETTINGS_PAGES = ['engine', 'connection', 'settings', 'folders', 'libraries', 'browser', 'global', 'prompts', 'stats', 'memories', 'graph', 'logs', 'lexicon', 'help']
27
27
  var PAGE_NAMES = {
28
28
  zh: {
29
29
  engine: '引擎与连接', connection: '连接与向量', settings: '记忆设置', folders: '文件夹', libraries: '记忆库',
30
30
  browser: '记忆浏览', global: '全局记忆', prompts: '提示词', stats: '统计', memories: '记忆总览',
31
- logs: '日志', lexicon: '词典', help: '帮助',
31
+ graph: '关系图谱', logs: '日志', lexicon: '词典', help: '帮助',
32
32
  },
33
33
  en: {
34
34
  engine: 'Engine & connection', connection: 'Connection & vectors', settings: 'Memory settings', folders: 'Folders', libraries: 'Libraries',
35
35
  browser: 'Memory browser', global: 'Global memory', prompts: 'Prompts', stats: 'Stats', memories: 'Memories',
36
- logs: 'Logs', lexicon: 'Lexicon', help: 'Help',
36
+ graph: 'Relationship graph', logs: 'Logs', lexicon: 'Lexicon', help: 'Help',
37
37
  },
38
38
  }
39
39
  var copy = COPY[locale]
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memu-memory",
3
3
  "icon": "./assets/icon.png",
4
- "version": "1.3.1",
4
+ "version": "1.3.2",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -131,7 +131,6 @@
131
131
  },
132
132
  "license": "MIT",
133
133
  "devDependencies": {
134
- "d3-force": "3.0.0",
135
134
  "esbuild": "0.28.2",
136
135
  "playwright": "1.64.1"
137
136
  }
@@ -2,8 +2,7 @@ import { build } from 'esbuild'
2
2
  import fs from 'node:fs'
3
3
  import { fileURLToPath } from 'node:url'
4
4
 
5
- const packages = ['d3-force', 'd3-dispatch', 'd3-quadtree', 'd3-timer']
6
- const licenses = packages.map(name => `${name}\n${fs.readFileSync(new URL(`../node_modules/${name}/LICENSE`, import.meta.url), 'utf8')}`).join('\n\n')
5
+ // 引擎已改为自研力导向,bundle 里不再打包任何第三方运行时代码。
7
6
  await build({
8
7
  entryPoints: [fileURLToPath(new URL('../lib/webui/graph-view.js', import.meta.url))],
9
8
  outfile: fileURLToPath(new URL('../lib/webui/graph-view.bundle.js', import.meta.url)),
@@ -14,4 +13,5 @@ await build({
14
13
  minify: true,
15
14
  banner: { js: '/* Generated by scripts/build-graph.mjs. Licenses: graph-LICENSE.txt */' },
16
15
  })
17
- fs.writeFileSync(new URL('../lib/webui/graph-LICENSE.txt', import.meta.url), licenses)
16
+ fs.writeFileSync(new URL('../lib/webui/graph-LICENSE.txt', import.meta.url),
17
+ 'graph-view.bundle.js: 本 bundle 无第三方运行时依赖(自研力导向引擎)。\n')
@@ -6,7 +6,8 @@ import { chromium } from 'playwright'
6
6
 
7
7
  // Run against scripts/preview.mjs. All stress data is intercepted in this browser;
8
8
  // no memories or relationships are written to the running server.
9
- const url = process.argv[2] || 'http://127.0.0.1:7792/dsh-memu-memory/ui#/settings/memories'
9
+ // 关系图谱现在是复刻 Graph Studio 的独立工作台页(#/settings/graph)。
10
+ const url = process.argv[2] || 'http://127.0.0.1:7792/dsh-memu-memory/ui#/settings/graph'
10
11
  const output = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-graph-browser-'))
11
12
  console.log(`Screenshots: ${output}`)
12
13
  const browser = await chromium.launch({ headless: true, channel: process.env.GRAPH_BROWSER_CHANNEL || undefined })
@@ -30,6 +31,11 @@ const telemetry = async page => page.locator('canvas.dshm-graph-canvas').evaluat
30
31
  return { arcs: canvas.__arcs || [], labels: canvas.__labels || [], painted,
31
32
  width: canvas.clientWidth, height: canvas.clientHeight }
32
33
  })
34
+ const railButton = (page, name) => page.locator('.dshm-gs-rail').getByRole('button', { name, exact: true })
35
+ const distance = (a, b) => Math.hypot(a.x - b.x, a.y - b.y)
36
+ const nearestPoint = (points, target) => points.reduce((best, p) => distance(p, target) < distance(best, target) ? p : best, points[0])
37
+ const pinnedCount = page => page.evaluate(() => document.querySelector('canvas.dshm-graph-canvas')?.__dshmGraphView?.pinnedCount?.() ?? -1)
38
+ const snapshot = page => page.evaluate(() => document.querySelector('canvas.dshm-graph-canvas')?.__dshmGraphView?.snapshot?.() ?? [])
33
39
 
34
40
  try {
35
41
  for (const viewport of [{ width: 1440, height: 1000 }, { width: 390, height: 844 }]) {
@@ -48,37 +54,55 @@ try {
48
54
  await route.fulfill({ json: { type: 'server-response', result: { ok: true, value: fixture } } })
49
55
  })
50
56
  await page.goto(url)
51
- await page.getByRole('tab', { name: '关系', exact: true }).click()
57
+ await page.locator('#boot').waitFor({ state: 'hidden' })
52
58
  const canvas = page.locator('canvas.dshm-graph-canvas')
53
59
  await canvas.waitFor()
54
60
  await page.waitForFunction(() => document.querySelector('canvas.dshm-graph-canvas')?.__arcs?.length === 200)
55
- await page.locator('#boot').waitFor({ state: 'hidden' })
56
61
  await canvas.scrollIntoViewIfNeeded()
62
+ // 复刻界面的骨架必须都在:顶栏 / 竖排工具 / 检视面板 / 状态栏。
63
+ for (const selector of ['.dshm-gs-topbar', '.dshm-gs-rail', '.dshm-gs-inspector', '.dshm-gs-status']) {
64
+ assert.equal(await page.locator(selector).count(), 1, `${selector} is missing`)
65
+ }
57
66
  const initial = await telemetry(page)
58
- await page.locator('.dshm-graph-viewport').screenshot({ path: path.join(output, `graph-${viewport.width}.png`) })
67
+ await page.locator('.dshm-gs-stage').screenshot({ path: path.join(output, `graph-${viewport.width}.png`) })
59
68
  console.log(`${viewport.width}px initial: ${initial.arcs.length} nodes, ${initial.labels.length} labels, ${initial.width}x${initial.height}`)
60
69
  assert.equal(initial.arcs.length, 200)
61
70
  assert.ok(initial.painted > 1000, 'canvas pixels must be nonblank')
62
- assert.ok(initial.labels.length > 0 && initial.labels.length < 200)
71
+ // 缩得很小时原版也只给高度数节点铺标签,甚至一个都不铺(zoomFade 归零);
72
+ // 标签是否真的出现放到放大之后再断言。
73
+ assert.ok(initial.labels.length < 200)
63
74
  for (const p of initial.arcs) assert.ok(p.x > 10 && p.x < initial.width - 10 && p.y > 10 && p.y < initial.height - 10)
75
+ // 标签是 textAlign:center 画的:x 是文字中心,左右边缘要各减/加半个宽度。
64
76
  for (let i = 0; i < initial.labels.length; i++) {
65
77
  const a = initial.labels[i]
66
78
  for (const b of initial.labels.slice(i + 1)) assert.ok(
67
- a.x + a.width <= b.x || b.x + b.width <= a.x || a.y + 16 <= b.y || b.y + 16 <= a.y,
79
+ a.x + a.width / 2 <= b.x - b.width / 2 || b.x + b.width / 2 <= a.x - a.width / 2 ||
80
+ a.y + 14 <= b.y || b.y + 14 <= a.y,
68
81
  'visible labels must not overlap',
69
82
  )
70
83
  }
71
- const box = await canvas.boundingBox(), node = initial.arcs.at(-1)
84
+ const box = await canvas.boundingBox()
85
+ const initialNodes = await snapshot(page)
86
+ // 取画布左侧的节点:窄屏检视面板若被展开会覆盖右侧,左侧永远可命中。
87
+ const node = initialNodes.reduce((best, item) => item.x < best.x ? item : best, initialNodes[0])
72
88
  const beforeDrag = requests.length
89
+ const expected = { x: node.x + 25, y: node.y + 15 }
73
90
  await page.mouse.move(box.x + node.x, box.y + node.y)
74
91
  await page.mouse.down()
75
- await page.mouse.move(box.x + node.x + 25, box.y + node.y + 15, { steps: 8 })
92
+ await page.mouse.move(box.x + expected.x, box.y + expected.y, { steps: 8 })
93
+ // 按住时 1:1 跟手;松手后节点会被物理收敛(左键不锁定),所以落点断言只要求"没弹回原处"。
94
+ const draggedNode = (await snapshot(page)).find(item => item.id === node.id)
95
+ assert.ok(draggedNode && distance(draggedNode, expected) < 1, 'the dragged node must follow the pointer 1:1')
76
96
  await page.mouse.up()
77
97
  await page.mouse.move(box.x - 5, box.y - 5)
78
98
  await page.waitForTimeout(120)
79
99
  assert.equal(requests.length, beforeDrag, 'drag must not focus/refetch')
80
- const dragged = (await telemetry(page)).arcs.at(-1)
81
- assert.ok(Math.abs(dragged.x - node.x - 25) < 1 && Math.abs(dragged.y - node.y - 15) < 1)
100
+ assert.equal(await pinnedCount(page), 0, 'a left drag must not lock the node')
101
+ await page.waitForTimeout(320)
102
+ const released = (await snapshot(page)).find(item => item.id === node.id)
103
+ // 松手后整簇会跟着收敛,落点会有小幅漂移,但绝不会弹回原处。
104
+ assert.ok(released && distance(released, expected) < 120, 'a left-dragged node must stay near the drop point')
105
+ assert.ok(released && distance(released, node) > 20, 'a left-dragged node must not spring back to its origin')
82
106
  const beforeRefresh = (await telemetry(page)).arcs
83
107
  const refreshed = page.waitForResponse(response => response.url().endsWith('/getGraph'), { timeout: 10000 })
84
108
  revisionBump = '-graph-refresh-test'
@@ -98,16 +122,28 @@ try {
98
122
  await page.mouse.wheel(0, -120); await page.waitForTimeout(100)
99
123
  const wheel = await telemetry(page)
100
124
  assert.ok(wheel.arcs.some((p, i) => Math.abs(p.x - panned.arcs[i]?.x) > 1), 'wheel must zoom')
101
- await page.getByRole('button', { name: '适应全图', exact: true }).click()
102
- await page.getByRole('button', { name: '图谱设置', exact: true }).click()
103
- await page.getByRole('checkbox', { name: '动态布局', exact: true }).uncheck()
104
- await page.getByRole('checkbox', { name: '显示标签', exact: true }).uncheck()
125
+ await railButton(page, '适应全图').click()
126
+ // 放大后再验证标签开关:缩得太小时原版本来就把标签渐隐到 0。
127
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)
128
+ await page.mouse.wheel(0, -400); await page.waitForTimeout(100)
129
+ await page.mouse.wheel(0, -400); await page.waitForTimeout(100)
130
+ assert.ok((await telemetry(page)).labels.length > 0, 'labels must appear once zoomed in')
131
+ await railButton(page, '图谱设置').click()
132
+ await page.getByRole('switch', { name: '动态布局', exact: true }).click()
133
+ await page.getByRole('switch', { name: '显示标签', exact: true }).click()
105
134
  await page.waitForTimeout(60)
106
135
  assert.equal((await telemetry(page)).labels.length, 0)
107
- await page.getByRole('checkbox', { name: '显示标签', exact: true }).check()
108
- await page.getByRole('button', { name: '图谱设置', exact: true }).click()
136
+ await page.getByRole('switch', { name: '显示标签', exact: true }).click()
109
137
  await page.waitForTimeout(60)
110
- const fitted = await telemetry(page), selected = fitted.arcs.at(-1)
138
+ assert.ok((await telemetry(page)).labels.length > 0, 'the label switch must turn labels back on')
139
+ await page.getByRole('switch', { name: '动态布局', exact: true }).click()
140
+ await railButton(page, '图谱设置').click()
141
+ await page.waitForTimeout(60)
142
+ const fitted = await telemetry(page)
143
+ // 放大后要用视口内、离边缘有距离的节点,否则点击会落在空白处不触发 focus。
144
+ const clickable = (await snapshot(page)).filter(n =>
145
+ n.x > 60 && n.x < initial.width - 60 && n.y > 60 && n.y < initial.height - 60)
146
+ const selected = clickable[0] || fitted.arcs[0]
111
147
  const currentBox = await canvas.boundingBox()
112
148
  const beforeClick = requests.length
113
149
  await page.mouse.click(currentBox.x + selected.x, currentBox.y + selected.y)
@@ -116,8 +152,55 @@ try {
116
152
  await page.mouse.move(currentBox.x - 5, currentBox.y - 5)
117
153
  await canvas.press('Escape'); await page.waitForTimeout(100)
118
154
  assert.equal(requests.at(-1).focusId, null)
155
+
156
+ // 右键 = 锁定 / 解除;左键只做显示与拖动,不产生固定点。
157
+ // 放大后部分节点在视口外,右键必须点视口内的节点才命中。
158
+ const pinCandidates = (await snapshot(page)).filter(n =>
159
+ n.x > 20 && n.x < initial.width - 20 && n.y > 20 && n.y < initial.height - 20)
160
+ const pinTarget = pinCandidates[0] || (await snapshot(page))[0]
161
+ await page.mouse.click(currentBox.x + pinTarget.x, currentBox.y + pinTarget.y, { button: 'right' })
162
+ await page.waitForTimeout(80)
163
+ assert.equal(await pinnedCount(page), 1, 'right click must pin the node')
164
+ await page.mouse.click(currentBox.x + pinTarget.x, currentBox.y + pinTarget.y, { button: 'right' })
165
+ await page.waitForTimeout(80)
166
+ assert.equal(await pinnedCount(page), 0, 'right click again must unpin')
167
+
168
+ // 拖一簇穿过另一簇:只有被拖的连通簇会动,其他簇一像素都不动且不重合。
169
+ const crossBefore = await snapshot(page)
170
+ assert.equal(crossBefore.length, 200)
171
+ const center = { x: initial.width / 2, y: initial.height / 2 }
172
+ let anchor = crossBefore[0], best = Infinity
173
+ for (const p of crossBefore) {
174
+ const d = distance(p, center)
175
+ if (d < best) { best = d; anchor = p }
176
+ }
177
+ const from = crossBefore[0]
178
+ const dragBox = await canvas.boundingBox()
179
+ await page.mouse.move(dragBox.x + from.x, dragBox.y + from.y)
180
+ await page.mouse.down()
181
+ await page.mouse.move(dragBox.x + anchor.x + 58, dragBox.y + anchor.y + 38, { steps: 6 })
182
+ await page.mouse.up()
183
+ await page.mouse.move(dragBox.x - 5, dragBox.y - 5)
184
+ await page.waitForTimeout(150)
185
+ const crossAfter = await snapshot(page)
186
+ assert.equal(crossAfter.length, crossBefore.length, 'dragging must not drop nodes')
187
+ const moved = crossAfter.filter(item => {
188
+ const before = crossBefore.find(p => p.id === item.id)
189
+ return !before || distance(item, before) > .5
190
+ })
191
+ assert.ok(moved.length > 0, 'the dragged node must move')
192
+ assert.ok(crossBefore.length - moved.length >= crossBefore.length - 30,
193
+ `clusters outside the dragged one must stay frozen (${moved.length} moved)`)
194
+ const movingIds = new Set(moved.map(item => item.id))
195
+ let min = Infinity
196
+ for (const item of moved) for (const other of crossAfter) {
197
+ if (movingIds.has(other.id)) continue
198
+ // 用节点圆之间的净间距判断「不重合」,比固定 12px 更贴近实际观感。
199
+ min = Math.min(min, distance(item, other) - item.r - other.r)
200
+ }
201
+ assert.ok(min > 0, `node circles must not overlap (gap ${min.toFixed(1)}px)`)
119
202
  assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, 'page must not overflow horizontally')
120
- console.log(`${viewport.width}px: ${initial.arcs.length} nodes, ${initial.labels.length} non-overlapping labels, ${initial.painted} painted pixels; drag/pan/zoom/click/settings passed`)
203
+ console.log(`${viewport.width}px: ${initial.arcs.length} nodes, ${initial.labels.length} non-overlapping labels, ${initial.painted} painted pixels; pin/frozen clusters/min gap ${min.toFixed(1)}px passed`)
121
204
  await context.close()
122
205
  }
123
206
  const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: 'zh-CN' })
@@ -126,7 +209,6 @@ try {
126
209
  await page.addInitScript(recordCanvas)
127
210
  await page.route('**/ui-assets/graph-view.js', route => route.abort('failed'))
128
211
  await page.goto(url)
129
- await page.getByRole('tab', { name: '关系', exact: true }).click()
130
212
  const retry = page.getByRole('button', { name: '图谱加载失败,请重试', exact: true })
131
213
  await retry.waitFor()
132
214
  await page.unroute('**/ui-assets/graph-view.js')
@@ -135,10 +217,10 @@ try {
135
217
  await page.locator('#boot').waitFor({ state: 'hidden' })
136
218
  const actual = await telemetry(page)
137
219
  assert.ok(actual.painted > 100 && actual.labels.length > 0)
138
- await page.locator('.dshm-graph-viewport').screenshot({ path: path.join(output, 'graph-real-light.png') })
220
+ await page.locator('.dshm-gs-stage').screenshot({ path: path.join(output, 'graph-real-light.png') })
139
221
  await page.locator('#theme').click()
140
222
  await page.waitForTimeout(100)
141
- await page.locator('.dshm-graph-viewport').screenshot({ path: path.join(output, 'graph-real-dark.png') })
223
+ await page.locator('.dshm-gs-stage').screenshot({ path: path.join(output, 'graph-real-dark.png') })
142
224
  const settled = (await telemetry(page)).arcs
143
225
  await page.waitForTimeout(2800)
144
226
  assert.deepEqual((await telemetry(page)).arcs, settled, 'a heartbeat/re-render must not restart or jump the settled layout')
@@ -153,9 +235,10 @@ try {
153
235
  assert.ok(Math.abs(pinned.x - selected.x - 40) < 1 && Math.abs(pinned.y - selected.y + 20) < 1,
154
236
  'live physics must not displace the node under the pointer')
155
237
  await page.mouse.up()
156
- await page.waitForTimeout(100)
238
+ await page.waitForTimeout(420)
239
+ assert.equal(await pinnedCount(page), 0, 'a left drag must not pin the node')
157
240
  assert.ok((await telemetry(page)).arcs.every(p => Number.isFinite(p.x) && Number.isFinite(p.y)))
158
- console.log(`Real data: ${actual.arcs.length} nodes; module failure/retry, light/dark and heartbeat stability passed`)
241
+ console.log(`Real data: ${actual.arcs.length} nodes; module failure/retry, light/dark, heartbeat stability and left-drag-no-lock passed`)
159
242
  await context.close()
160
243
  assert.deepEqual(errors, [])
161
244
  console.log(`Screenshots: ${output}`)
@@ -0,0 +1,252 @@
1
+ #!/usr/bin/env node
2
+ // Auto-link migration / rebuild (DESIGN §14 S1–S4, local only).
3
+ //
4
+ // node scripts/rebuild-auto-links.mjs # dry run for every library
5
+ // node scripts/rebuild-auto-links.mjs --apply # backup -> grade -> clean -> rebuild
6
+ // node scripts/rebuild-auto-links.mjs --library lib_x --estimate-top 10
7
+ //
8
+ // Dry run is the default on purpose: it prints what would change and writes only
9
+ // the derived anchor-candidates.json queue. --apply takes a full backup first,
10
+ // grades pre-status entities, deletes every source:'auto' edge (legacy lexical
11
+ // noise and stale deterministic edges alike), then regenerates the deterministic
12
+ // edges for already-confirmed entities. Non-auto edges, text, vectors, attachments
13
+ // and suppression tables are never touched.
14
+
15
+
16
+ import path from 'node:path'
17
+ import { pathToFileURL } from 'node:url'
18
+
19
+ const RULES = new Set(['entity-mention', 'conflict', 'supersede', 'fact-key', 'worker-quote'])
20
+
21
+ export function parseArgs(argv) {
22
+ const args = { apply: false, json: false, library: null, home: null, estimateTop: 8, includeArchived: false }
23
+ for (let index = 2; index < argv.length; index += 1) {
24
+ const value = argv[index]
25
+ if (value === '--apply') args.apply = true
26
+ else if (value === '--dry-run') args.apply = false
27
+ else if (value === '--json') args.json = true
28
+ else if (value === '--include-archived') args.includeArchived = true
29
+ else if (value === '--library') args.library = argv[++index] || null
30
+ else if (value === '--home') args.home = argv[++index] || null
31
+ else if (value === '--estimate-top') args.estimateTop = Math.max(0, Number(argv[++index]) || 0)
32
+ else throw new Error(`unknown argument: ${value}`)
33
+ }
34
+ return args
35
+ }
36
+
37
+ function autoEdgesOf(index) {
38
+ const legacy = []
39
+ const deterministic = []
40
+ let nonAuto = 0
41
+ for (const [from, entry] of Object.entries(index?.entries || {})) {
42
+ for (const link of entry?.links || []) {
43
+ if (!link) continue
44
+ if (link.source !== 'auto') { nonAuto += 1; continue }
45
+ const rule = link.evidence?.rule
46
+ const row = { from, to: link.to, kind: link.kind, rule: rule || null }
47
+ if (rule && RULES.has(rule)) deterministic.push(row)
48
+ else legacy.push(row)
49
+ }
50
+ }
51
+ return { legacy, deterministic, nonAuto }
52
+ }
53
+
54
+ async function loadModules() {
55
+ const state = await import('../lib/state.js')
56
+ const graph = await import('../lib/graph.js')
57
+ const decide = await import('../lib/auto-link/decide.js')
58
+ const apply = await import('../lib/auto-link/apply.js')
59
+ const suppression = await import('../lib/auto-link/suppression.js')
60
+ const candidates = await import('../lib/auto-link/candidates.js')
61
+ const { record } = await import('../lib/activity-log.js')
62
+ return { state, graph, decide, apply, suppression, candidates, record }
63
+ }
64
+
65
+ function countByRule(edges) {
66
+ const counts = {}
67
+ for (const edge of edges) counts[edge.rule] = (counts[edge.rule] || 0) + 1
68
+ return counts
69
+ }
70
+
71
+ // Archived libraries are frozen by default, but a dry run that silently ignores
72
+ // most of the data reads as "nothing to migrate". Count what was skipped so the
73
+ // operator can decide to pass --include-archived.
74
+ function archivedSummary(modules, allLibraries) {
75
+ const skipped = allLibraries.filter(library => library.archived === true)
76
+ let memories = 0
77
+ let legacyAutoEdges = 0
78
+ for (const library of skipped) {
79
+ try {
80
+ const index = modules.state.loadPrivateIndex(library.id)
81
+ memories += Object.keys(index.entries || {}).length
82
+ legacyAutoEdges += autoEdgesOf(index).legacy.length
83
+ } catch {}
84
+ }
85
+ return { libraries: skipped.length, memories, legacyAutoEdges }
86
+ }
87
+
88
+ /** Estimated mention edges if the top N queued names were confirmed. */
89
+ function estimateMention(modules, libraryId, queue, topN) {
90
+ if (!topN) return { estimatedMentionEdges: 0, estimatedMemories: 0 }
91
+ const { state, graph, decide } = modules
92
+ const index = state.loadPrivateIndex(libraryId)
93
+ const entities = graph.listEntities({ libraryId }).items.filter(entity => entity.status === 'confirmed').slice()
94
+ const existing = new Set(entities.map(entity => entity.name))
95
+ let added = 0
96
+ for (const row of [...(queue?.tiers?.tier1 || []), ...(queue?.tiers?.tier2 || [])]) {
97
+ if (added >= topN) break
98
+ if (row.entityStatus === 'confirmed') continue
99
+ if (existing.has(row.term)) continue
100
+ entities.push({ id: `estimate-${added}`, name: row.term, kind: 'person', status: 'confirmed' })
101
+ existing.add(row.term)
102
+ added += 1
103
+ }
104
+ const edges = decide.mentionEdges(decide.eligibleEntries(index), entities)
105
+ return {
106
+ estimatedMentionEdges: edges.length,
107
+ estimatedMemories: new Set(edges.map(edge => edge.from)).size,
108
+ estimateConfirmed: added,
109
+ }
110
+ }
111
+
112
+ async function inspectLibrary(modules, libraryId, { estimateTop = 8 } = {}) {
113
+ const { state, graph, candidates } = modules
114
+ const index = state.loadPrivateIndex(libraryId)
115
+ const mine = autoEdgesOf(index)
116
+ const grading = graph.gradeLegacyEntities({ libraryId, apply: false })
117
+ const queue = candidates.generateAnchorCandidates({ libraryId })
118
+ return {
119
+ libraryId,
120
+ memories: Object.keys(index.entries || {}).length,
121
+ autoEdges: mine.legacy.length + mine.deterministic.length,
122
+ legacyAutoEdges: mine.legacy.length,
123
+ deterministicAutoEdges: mine.deterministic.length,
124
+ deterministicByRule: countByRule(mine.deterministic),
125
+ nonAutoEdges: mine.nonAuto,
126
+ grading: { scanned: grading.scanned, provisional: grading.provisional, confirmed: grading.confirmed },
127
+ queue: { tier1: queue?.totals?.tier1 || 0, tier2: queue?.totals?.tier2 || 0, provisionalEntities: queue?.entities?.provisional?.length || 0 },
128
+ ...estimateMention(modules, libraryId, queue, estimateTop),
129
+ }
130
+ }
131
+
132
+ async function applyLibrary(modules, libraryId) {
133
+ const { state, graph, decide, apply, suppression, record } = modules
134
+ const graded = graph.gradeLegacyEntities({ libraryId, apply: true })
135
+ const index = state.loadPrivateIndex(libraryId)
136
+ const before = autoEdgesOf(index)
137
+ const entities = graph.listEntities({ libraryId }).items
138
+ let supp = null
139
+ try { supp = suppression.suppressionSet(libraryId) } catch { supp = null }
140
+
141
+ // S3: every auto edge is derived data. Remove them all in one transaction,
142
+ // keeping manual/user/worker edges exactly as they are.
143
+ let removed = 0
144
+ state.updatePrivateIndex(libraryId, fresh => {
145
+ for (const entry of Object.values(fresh.entries || {})) {
146
+ if (!Array.isArray(entry.links)) continue
147
+ const kept = entry.links.filter(link => {
148
+ const drop = link && link.source === 'auto'
149
+ if (drop) removed += 1
150
+ return !drop
151
+ })
152
+ if (kept.length !== entry.links.length) entry.links = kept
153
+ }
154
+ })
155
+
156
+ // S4 for rows that were already confirmed: rebuild their deterministic edges
157
+ // now, so the graph does not go blank while the review queue waits for a human.
158
+ const desired = decide.decideAutoLinks({ index: state.loadPrivateIndex(libraryId), entities, suppression: supp })
159
+ const applied = apply.applyAutoEdges({ libraryId, edges: desired, entities, operation: 'auto-link-migration' })
160
+
161
+ try {
162
+ record({
163
+ kind: 'write', scope: 'private', libraryId, ok: true,
164
+ message: `自动关联迁移:清理 ${removed} 条旧边,重建 ${applied.added + applied.updated} 条确定性边`,
165
+ detail: {
166
+ op: 'auto-link-migration', removed, legacy: before.legacy.length,
167
+ rebuilt: applied.added + applied.updated, rules: countByRule(desired),
168
+ graded: { provisional: graded.provisional, confirmed: graded.confirmed, changed: graded.changed },
169
+ },
170
+ refs: [],
171
+ })
172
+ } catch {}
173
+
174
+ const after = autoEdgesOf(state.loadPrivateIndex(libraryId))
175
+ return {
176
+ libraryId,
177
+ removedAutoEdges: removed,
178
+ legacyRemoved: before.legacy.length,
179
+ rebuiltAutoEdges: applied.added + applied.updated,
180
+ rebuiltByRule: countByRule(desired),
181
+ remainingAutoEdges: after.legacy.length + after.deterministic.length,
182
+ remainingLegacyAutoEdges: after.legacy.length,
183
+ graded: { scanned: graded.scanned, provisional: graded.provisional, confirmed: graded.confirmed, changed: graded.changed },
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Run the migration for one data home. `home` must be set before this process
189
+ * imports the plugin modules; callers that already imported them share that home.
190
+ */
191
+ export async function runRebuildAutoLinks({ home = null, libraryId = null, apply = false, estimateTop = 8, json = false, includeArchived = false, log = console.log } = {}) {
192
+ if (home) process.env.DSH_MEMU_HOME = home
193
+ const modules = await loadModules()
194
+ const libraries = (includeArchived ? modules.state.listLibrariesAll() : modules.state.listLibraries())
195
+ .filter(lib => !libraryId || lib.id === libraryId)
196
+ if (libraryId && libraries.length === 0) throw new Error(`unknown library: ${libraryId}`)
197
+ const report = { home: home || null, apply, generatedAt: new Date().toISOString(), libraries: [], failures: [], ok: true, backup: null, skippedArchived: null }
198
+ if (!includeArchived) {
199
+ report.skippedArchived = archivedSummary(modules, modules.state.listLibrariesAll())
200
+ if (!json && report.skippedArchived.libraries) {
201
+ log(`skipped ${report.skippedArchived.libraries} archived library(ies): ${report.skippedArchived.memories} memories / ${report.skippedArchived.legacyAutoEdges} legacy auto edges; pass --include-archived to include them`)
202
+ }
203
+ }
204
+
205
+ if (apply) {
206
+ // One backup covers every library this run may touch.
207
+ report.backup = await modules.state.backupDatabases()
208
+ if (!json) log(`backup: ${report.backup}`)
209
+ }
210
+
211
+ for (const library of libraries) {
212
+ let info
213
+ try {
214
+ info = apply ? await applyLibrary(modules, library.id) : await inspectLibrary(modules, library.id, { estimateTop })
215
+ } catch (error) {
216
+ // One corrupt store must not stop the rest; the failure is reported and the
217
+ // exit code is non-zero so a scheduled run is visibly not a success.
218
+ const failure = { libraryId: library.id, archived: library.archived === true, error: String(error?.message || error) }
219
+ report.failures.push(failure)
220
+ report.ok = false
221
+ if (!json) log(`FAILED ${library.id} (${library.name || library.scopeKey || ''}): ${failure.error}`)
222
+ continue
223
+ }
224
+ report.libraries.push(info)
225
+ if (!json) {
226
+ log(`${apply ? 'apply' : 'dry-run'} ${library.id} (${library.name || library.scopeKey || ''})${library.archived === true ? ' · archived' : ''}`)
227
+ if (!apply) {
228
+ log(` memories ${info.memories} · auto ${info.autoEdges} (legacy ${info.legacyAutoEdges} / deterministic ${info.deterministicAutoEdges}) · non-auto ${info.nonAutoEdges}`)
229
+ log(` grading: ${info.grading.provisional} provisional / ${info.grading.confirmed} confirmed (no writes)`)
230
+ log(` queue: tier1 ${info.queue.tier1} · tier2 ${info.queue.tier2} · provisional entities ${info.queue.provisionalEntities}`)
231
+ log(` if the top ${info.estimateConfirmed || 0} queued names are confirmed: ~${info.estimatedMentionEdges} mention edges over ${info.estimatedMemories} memories`)
232
+ } else {
233
+ log(` removed ${info.removedAutoEdges} auto edges (legacy ${info.legacyRemoved}) · rebuilt ${info.rebuiltAutoEdges} deterministic edges`)
234
+ log(` remaining auto ${info.remainingAutoEdges} (legacy ${info.remainingLegacyAutoEdges}) · graded ${info.graded.changed} entities`)
235
+ }
236
+ }
237
+ }
238
+ if (json) log(JSON.stringify(report, null, 2))
239
+ return report
240
+ }
241
+
242
+ const isMain = process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url
243
+ if (isMain) {
244
+ try {
245
+ const args = parseArgs(process.argv)
246
+ const report = await runRebuildAutoLinks(args)
247
+ if (!report.ok) process.exitCode = 1
248
+ } catch (error) {
249
+ console.error(`rebuild-auto-links failed: ${error?.message || error}`)
250
+ process.exitCode = 1
251
+ }
252
+ }
@@ -68,17 +68,20 @@ test('agent backend accepts a global review without the engine', async () => {
68
68
 
69
69
  // ---- §2.1 MemU nonzero exit must reject, not crash the host
70
70
 
71
- test('a failing MemU command rejects with MEMU_COMMAND_FAILED (and the process survives)', async () => {
71
+ test('a broken MemU interpreter rejects with MEMU_SPAWN_FAILED (and the process survives)', async () => {
72
+ // Node 不是 Python:常驻 worker 连就绪都到不了。重点是命令侧得到明确拒绝、
73
+ // 宿主进程不被带崩,下一次调用仍然是同样的拒绝而不是挂死。
72
74
  fs.mkdirSync(path.join(home, 'engine'), { recursive: true })
73
75
  fs.writeFileSync(path.join(home, 'engine', 'current.json'), JSON.stringify({ python: process.execPath, venv: home }))
74
- let error = null
75
- try {
76
- await memu.retrieve({ query: 'x', db: path.join(home, 'x.sqlite3'), timeoutMs: 15_000 })
77
- } catch (e) {
78
- error = e
76
+ for (let attempt = 0; attempt < 2; attempt += 1) {
77
+ await assert.rejects(
78
+ () => memu.retrieve({ query: 'x', db: path.join(home, 'x.sqlite3'), timeoutMs: 15_000 }),
79
+ (error) => {
80
+ assert.equal(error.code, 'MEMU_SPAWN_FAILED')
81
+ return true
82
+ },
83
+ )
79
84
  }
80
- assert.ok(error, 'must reject, not resolve')
81
- assert.equal(error.code, 'MEMU_COMMAND_FAILED')
82
85
  fs.rmSync(path.join(home, 'engine'), { recursive: true, force: true })
83
86
  })
84
87