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
@@ -2,7 +2,7 @@ import test from 'node:test'
2
2
  import assert from 'node:assert/strict'
3
3
  import vm from 'node:vm'
4
4
  import fs from 'node:fs'
5
- import { createLayout, createGraphView, fitCamera, zoomCamera, placeLabels } from '../lib/webui/graph-view.js'
5
+ import { createForceLayout, createGraphView, DEFAULT_OPTIONS, fitCamera, zoomCamera, placeLabels } from '../lib/webui/graph-view.js'
6
6
 
7
7
  const graph = (count, connected = true) => ({
8
8
  nodes: Array.from({ length: count }, (_, i) => ({ id: `n${String(i).padStart(3, '0')}`, title: `Memory ${i}`, kind: 'memory', strength: .5 })),
@@ -10,23 +10,23 @@ const graph = (count, connected = true) => ({
10
10
  })
11
11
 
12
12
  test('layout preserves object identity, positions and cooling on equivalent refreshed snapshots', () => {
13
- const data = graph(30), before = structuredClone(data), layout = createLayout()
13
+ const data = graph(30), before = structuredClone(data), layout = createForceLayout()
14
14
  layout.update(data); layout.settle()
15
- const node = layout.nodes[0], position = { x: node.x, y: node.y }, alpha = layout.simulation.alpha()
15
+ const node = layout.nodes[0], position = { x: node.x, y: node.y }, alpha = layout.alpha
16
16
  assert.equal(layout.update(structuredClone(data)), false)
17
17
  assert.equal(layout.nodes[0], node)
18
18
  assert.equal(node.x, position.x); assert.equal(node.y, position.y)
19
- assert.equal(layout.simulation.alpha(), alpha)
20
- assert.deepEqual(data, before)
19
+ assert.equal(layout.alpha, alpha)
20
+ assert.equal(layout.active, false, 'a settled layout must stop integrating')
21
+ assert.deepEqual(data, before, 'the RPC snapshot must never be mutated')
21
22
  layout.update({ nodes: data.nodes.slice(0, 4), edges: data.edges.slice(0, 3) })
22
23
  layout.update(data)
23
- assert.equal(layout.nodes[0], node)
24
- assert.equal(node.x, position.x)
24
+ assert.equal(layout.nodes[0], node, 'positions live in the cache, not in the snapshot objects')
25
25
  layout.dispose()
26
26
  })
27
27
 
28
28
  test('disconnected 200-node layout stays finite, separated and framed without boundary clamping', () => {
29
- const layout = createLayout()
29
+ const layout = createForceLayout()
30
30
  layout.update(graph(200, false)); layout.settle(300)
31
31
  const camera = fitCamera(layout.nodes, 340, 380)
32
32
  for (const n of layout.nodes) {
@@ -44,12 +44,13 @@ test('disconnected 200-node layout stays finite, separated and framed without bo
44
44
  test('invalid/self edges are ignored, input bounded, node order deterministic', () => {
45
45
  const data = graph(250, false)
46
46
  data.edges.push({ from: 'missing', to: 'n000' }, { from: 'n000', to: 'n000' })
47
- const a = createLayout(), b = createLayout()
47
+ const a = createForceLayout(), b = createForceLayout()
48
48
  a.update(data)
49
49
  b.update({ nodes: [...data.nodes.slice(0, 200)].reverse(), edges: [] })
50
50
  assert.equal(a.nodes.length, 200); assert.equal(a.edges.length, 0)
51
51
  a.settle(); b.settle()
52
- assert.deepEqual(a.nodes.map(n => [n.id, n.x, n.y]), b.nodes.map(n => [n.id, n.x, n.y]))
52
+ assert.deepEqual(a.nodes.map(n => [n.id, n.x, n.y]), b.nodes.map(n => [n.id, n.x, n.y]),
53
+ 'the jitter must be deterministic, never Math.random')
53
54
  a.dispose(); b.dispose()
54
55
  })
55
56
 
@@ -79,13 +80,121 @@ test('labels neither overlap each other nor node obstacles and remain inside can
79
80
  }
80
81
  })
81
82
 
83
+ test('pin/unpin/relayout/unpinAll keep the physics state coherent', () => {
84
+ const layout = createForceLayout()
85
+ const data = graph(12)
86
+ layout.update(data); layout.settle(120)
87
+ layout.pin('n000', 321, 123)
88
+ assert.equal(layout.nodes[0].fx, 321); assert.equal(layout.nodes[0].x, 321)
89
+ assert.equal(layout.nodes[0].fy, 123); assert.equal(layout.nodes[0].y, 123)
90
+ layout.tick()
91
+ assert.equal(layout.nodes[0].x, 321, 'a pinned node is never moved by forces')
92
+ layout.update(structuredClone(data))
93
+ assert.equal(layout.nodes[0].x, 321, 'a heartbeat refresh must not drop the pin')
94
+ layout.unpin('n000')
95
+ assert.equal(layout.nodes[0].fx, null); assert.equal(layout.nodes[0].fy, null)
96
+ layout.pin('n001', 10, 10); layout.pin('n002', 20, 20)
97
+ layout.unpinAll()
98
+ assert.ok(layout.nodes.every(node => node.fx == null && node.fy == null))
99
+ layout.relayout(); layout.settle(120)
100
+ assert.ok(layout.nodes.every(node => Number.isFinite(node.x) && Number.isFinite(node.y) && node.fx == null))
101
+ assert.equal(layout.edges.length, 11)
102
+ layout.dispose()
103
+ })
104
+
105
+ test('relayout cools down and separates instead of shoving nodes forever', () => {
106
+ // 「缩到最小 → 重新布局 → 打架」的回归:硬分离阈值以前写成 24 / viewScale,
107
+ // k≈.06 时等于要求 400 世界像素间距,每帧互推、永不收敛。现在只看半径,
108
+ // 物理也拿不到相机(setScale 已删),缩放再小也不会改变力的量级。
109
+ assert.equal('setScale' in createForceLayout(), false, 'the physics must never be handed the camera scale')
110
+ const layout = createForceLayout()
111
+ layout.update(graph(60))
112
+ layout.relayout()
113
+ let previous = Infinity
114
+ for (let window = 0; window < 6; window++) {
115
+ const before = layout.nodes.map(node => [node.x, node.y])
116
+ for (let i = 0; i < 20; i++) layout.tick()
117
+ let maxMove = 0
118
+ layout.nodes.forEach((node, i) => { maxMove = Math.max(maxMove, Math.hypot(node.x - before[i][0], node.y - before[i][1])) })
119
+ assert.ok(maxMove < previous, `window ${window} must move less than the one before (${maxMove} >= ${previous})`)
120
+ previous = maxMove
121
+ }
122
+ assert.ok(previous < 4, `a cooled relayout must stop shoving, saw ${previous}px per window`)
123
+ for (let i = 0; i < layout.nodes.length; i++) for (let j = i + 1; j < layout.nodes.length; j++) {
124
+ const a = layout.nodes[i], b = layout.nodes[j]
125
+ assert.ok(Math.hypot(a.x - b.x, a.y - b.y) > a.radius + b.radius, 'relayout must not leave nodes overlapping')
126
+ }
127
+ layout.dispose()
128
+ })
129
+
130
+ test('configure maps all three force sliders and reheats without ever going non-finite', () => {
131
+ assert.equal(DEFAULT_OPTIONS.center, 0, 'center force is off by default')
132
+ assert.equal(DEFAULT_OPTIONS.clusterScope, true)
133
+ const layout = createForceLayout()
134
+ layout.update(graph(40)); layout.settle(80)
135
+ const cooled = layout.alpha
136
+ layout.configure({ repulsion: 300, distance: 180, center: 2 })
137
+ assert.ok(layout.alpha > cooled)
138
+ for (let i = 0; i < 200; i++) layout.tick()
139
+ assert.ok(layout.nodes.every(node => Number.isFinite(node.x) && Number.isFinite(node.y)))
140
+ layout.dispose()
141
+ })
142
+
143
+ test('drag scope freezes other clusters and repels the dragged one from them', () => {
144
+ // 两簇各 12 节点,链状相连;A 在左,B 在右,互不连通。
145
+ const nodes = [], edges = []
146
+ for (let group = 0; group < 2; group++) for (let i = 0; i < 12; i++) {
147
+ const id = `${group}-${String(i).padStart(2, '0')}`
148
+ nodes.push({ id, title: id, kind: 'memory' })
149
+ if (i) edges.push({ from: `${group}-${String(i - 1).padStart(2, '0')}`, to: id })
150
+ }
151
+ const layout = createForceLayout()
152
+ layout.update({ nodes, edges })
153
+ // 手动把两簇分开(布局原长由首次见到的距离决定,这里覆盖成稳定值)。
154
+ layout.nodes.forEach((node, i) => { node.x = i < 12 ? -260 + i * 8 : 260 + (i - 12) * 8; node.y = i < 12 ? 0 : 40; node.fx = null; node.fy = null })
155
+ layout.edges.forEach(edge => { edge.baseLen = 12 })
156
+ layout.settle(80)
157
+ const frozen = layout.nodes.slice(12).map(node => ({ id: node.id, x: node.x, y: node.y }))
158
+ const dragged = layout.nodes[0]
159
+ const scope = layout.startDragScope(dragged.id)
160
+ assert.ok(scope?.ids.size === 12, 'the drag scope is exactly one connected component')
161
+ assert.ok(!scope.ids.has(layout.nodes[12].id))
162
+ const centerX = frozen.reduce((sum, n) => sum + n.x, 0) / frozen.length
163
+ const centerY = frozen.reduce((sum, n) => sum + n.y, 0) / frozen.length
164
+ // 把整簇硬塞到冻结簇中心:靠单向斥力把活动簇推开,冻结簇自身只当障碍。
165
+ layout.reheat(.9)
166
+ for (let i = 0; i < scope.members.length; i++) {
167
+ const member = scope.members[i]
168
+ if (member === dragged) continue
169
+ member.x = centerX + (i % 4) * 4 - 6
170
+ member.y = centerY + Math.floor(i / 4) * 4 - 6
171
+ member.vx = 0; member.vy = 0
172
+ }
173
+ // 落点放在冻结簇包围盒之外:pin 节点优先跟手,不能被硬分离挪动。
174
+ layout.pin(dragged.id, Math.max(...frozen.map(n => n.x)) + 60, centerY)
175
+ for (let i = 0; i < 80; i++) layout.tick()
176
+ layout.setDragging(false)
177
+ for (let i = 0; i < 20; i++) layout.tick()
178
+ // 100 ticks 内 alpha 仍高于 .05,作用域未解除,其他簇必须一像素都不动。
179
+ for (const before of frozen) {
180
+ const after = layout.nodeById(before.id)
181
+ assert.equal(after.x, before.x, 'frozen clusters must not move at all')
182
+ assert.equal(after.y, before.y)
183
+ }
184
+ let min = Infinity
185
+ for (const a of scope.members) for (const b of frozen) min = Math.min(min, Math.hypot(a.x - b.x, a.y - b.y))
186
+ assert.ok(min > 12, `clusters must not overlap (min distance ${min.toFixed(1)} world px)`)
187
+ layout.dispose()
188
+ })
189
+
82
190
  function harness(reducedMotion = true) {
83
- const handlers = new Map(), windowHandlers = new Map(), frames = new Map(), arcs = [], focuses = []
84
- let id = 0
191
+ const handlers = new Map(), windowHandlers = new Map(), frames = new Map(), arcs = [], focuses = [], texts = []
192
+ let id = 0, paints = 0
85
193
  const ctx = new Proxy({
86
194
  arc(x, y, radius) { arcs.push({ x, y, radius }) },
87
195
  measureText(text) { return { width: text.length * 7 } },
88
- clearRect() { arcs.length = 0 },
196
+ clearRect() { paints++; arcs.length = 0; texts.length = 0 },
197
+ fillText(text) { texts.push(String(text)) },
89
198
  }, { get(target, key) { return key in target ? target[key] : () => {} } })
90
199
  const win = {
91
200
  requestAnimationFrame(fn) { frames.set(++id, fn); return id },
@@ -114,10 +223,20 @@ function harness(reducedMotion = true) {
114
223
  const emit = (type, x, y, extra = {}) => handlers.get(type)?.({
115
224
  type, clientX: x, clientY: y, button: 0, pointerId: 1, pointerType: 'mouse', preventDefault() {}, ...extra,
116
225
  })
117
- return { view, flush, emit, arcs, frames, focuses, handlers, windowHandlers }
226
+ return { view, flush, emit, arcs, texts, frames, focuses, handlers, windowHandlers, getPaints: () => paints }
118
227
  }
119
228
 
120
- test('dragging after cooling pins the node without click/refocus, and refresh keeps pixel position', () => {
229
+ test('the detailed layer actually paints labels and the label switch silences them', () => {
230
+ const h = harness()
231
+ h.view.update(graph(10)); h.flush()
232
+ assert.ok(h.texts.length > 0, 'labels must reach fillText (radius/textWidth must be finite)')
233
+ assert.ok(h.texts.length <= 10, 'labels must never be painted more often than there are nodes')
234
+ h.view.configure({ labels: false }); h.flush()
235
+ assert.equal(h.texts.length, 0)
236
+ h.view.dispose()
237
+ })
238
+
239
+ test('left drag never locks the node; right click toggles the pin; refresh preserves position', () => {
121
240
  const h = harness()
122
241
  h.view.update(graph(1)); h.flush()
123
242
  const p = { ...h.arcs[0] }
@@ -127,14 +246,40 @@ test('dragging after cooling pins the node without click/refocus, and refresh ke
127
246
  h.flush()
128
247
  assert.equal(h.arcs[0].x, p.x + 70); assert.equal(h.arcs[0].y, p.y + 25)
129
248
  h.emit('pointerup', p.x + 70, p.y + 25); h.flush()
130
- assert.deepEqual(h.focuses, [])
249
+ assert.deepEqual(h.focuses, [], 'a drag must never focus/refetch')
250
+ assert.equal(h.view.isPinned('n000'), false, 'a left drag must not pin the node')
251
+ // 松手后位置留在落点,心跳刷新不把它拽回。
252
+ for (let i = 0; i < 3; i++) { h.view.update(graph(1)); h.flush() }
253
+ assert.equal(h.arcs[0].x, p.x + 70); assert.equal(h.arcs[0].y, p.y + 25)
131
254
  h.emit('pointerdown', p.x + 70, p.y + 25)
132
255
  h.emit('pointerup', p.x + 70, p.y + 25)
133
- assert.deepEqual(h.focuses, ['n000'])
256
+ assert.deepEqual(h.focuses, ['n000'], 'a click without movement still focuses')
257
+ // 右键 = 锁定 / 解除,左键从不产生固定点。
258
+ h.emit('contextmenu', p.x + 70, p.y + 25); h.flush()
259
+ assert.equal(h.view.isPinned('n000'), true, 'right click pins the node')
260
+ assert.equal(h.view.pinnedCount(), 1)
261
+ assert.equal(h.arcs[0].x, p.x + 70, 'pinning must not teleport the node')
262
+ h.emit('contextmenu', p.x + 70, p.y + 25); h.flush()
263
+ assert.equal(h.view.isPinned('n000'), false, 'right click again unpins')
264
+ assert.equal(h.view.pinnedCount(), 0)
134
265
  h.view.dispose()
135
266
  assert.equal(h.handlers.size, 0); assert.equal(h.frames.size, 0); assert.equal(h.windowHandlers.size, 0)
136
267
  })
137
268
 
269
+ test('dragging an already pinned node keeps the lock at the new position', () => {
270
+ const h = harness()
271
+ h.view.update(graph(1)); h.flush()
272
+ const p = { ...h.arcs[0] }
273
+ h.emit('contextmenu', p.x, p.y); h.flush()
274
+ assert.equal(h.view.isPinned('n000'), true)
275
+ h.emit('pointerdown', p.x, p.y)
276
+ h.emit('pointermove', p.x + 40, p.y + 10)
277
+ h.emit('pointerup', p.x + 40, p.y + 10); h.flush()
278
+ assert.equal(h.view.isPinned('n000'), true, 'an existing lock survives a left drag')
279
+ assert.equal(h.arcs[0].x, p.x + 40)
280
+ h.view.dispose()
281
+ })
282
+
138
283
  test('pan/zoom and equivalent refresh never re-fit the camera; cancelled pointer never clicks', () => {
139
284
  const h = harness()
140
285
  h.view.update(graph(1)); h.flush()
@@ -163,7 +308,7 @@ test('dense hit targets choose the closest node, not the last node in draw order
163
308
  test('pinch does not trigger focus and reduced-motion/paused views do not run an idle animation loop', () => {
164
309
  const h = harness()
165
310
  h.view.update(graph(10)); h.flush()
166
- assert.equal(h.frames.size, 0)
311
+ assert.equal(h.frames.size, 0, 'reduced motion must not keep a rAF loop alive')
167
312
  const p = h.arcs[0]
168
313
  h.emit('pointerdown', p.x, p.y, { pointerType: 'touch' })
169
314
  h.emit('pointerdown', p.x + 40, p.y, { pointerType: 'touch', pointerId: 2 })
@@ -174,14 +319,68 @@ test('pinch does not trigger focus and reduced-motion/paused views do not run an
174
319
  h.view.dispose()
175
320
  const paused = harness(false)
176
321
  paused.view.configure({ motion: false }); paused.view.update(graph(10)); paused.flush()
177
- assert.equal(paused.frames.size, 0)
322
+ assert.equal(paused.frames.size, 0, 'paused motion must not keep a rAF loop alive')
178
323
  paused.view.dispose()
179
324
  })
180
325
 
326
+ // GPU 守卫:动效开着也不能在冷却后空转重绘(曾经的实现是 30fps 永久整幅重绘)。
327
+ test('a cooled layout stops requesting frames even while motion is enabled', () => {
328
+ const h = harness(false)
329
+ h.view.update(graph(60))
330
+ for (let i = 0; i < 900 && h.frames.size; i++) h.flush()
331
+ assert.equal(h.frames.size, 0, 'a settled layout must not keep a rAF loop alive')
332
+ const painted = h.getPaints()
333
+ for (let i = 0; i < 200; i++) h.flush()
334
+ assert.equal(h.getPaints(), painted, 'idle time must not repaint the canvas')
335
+ h.view.zoom(1.2)
336
+ assert.equal(h.frames.size, 1, 'an interaction schedules exactly one repaint')
337
+ h.flush()
338
+ assert.equal(h.frames.size, 0, 'that repaint must not restart the loop')
339
+ h.view.dispose()
340
+ })
341
+
342
+ // 极小缩放下两颗节点可能只差 2-3px:纯最近邻会随鼠标 1px 抖动来回换人,
343
+ // 高亮反复切换就是用户看到的「节点互相打架闪现」。
344
+ test('hover keeps its target through 1px jitter at minimum zoom', () => {
345
+ const h = harness()
346
+ h.view.update(graph(2)); h.flush()
347
+ h.view.zoom(.05); h.flush()
348
+ const p = { ...h.arcs[0] }
349
+ const before = h.getPaints()
350
+ h.emit('pointermove', p.x, p.y); h.flush()
351
+ const first = h.getPaints()
352
+ assert.ok(first > before, 'hovering a node must repaint once')
353
+ h.emit('pointermove', p.x + 1, p.y + 1); h.flush()
354
+ assert.equal(h.getPaints(), first, 'a 1px nudge must not flip the hover target')
355
+ h.view.dispose()
356
+ })
357
+
358
+ test('Escape cancels a drag and clears the focus; toolbar actions do not throw', () => {
359
+ const h = harness()
360
+ h.view.update(graph(3)); h.flush()
361
+ const p = { ...h.arcs[0] }
362
+ h.emit('pointerdown', p.x, p.y)
363
+ h.emit('pointermove', p.x + 50, p.y + 30)
364
+ h.emit('keydown', p.x, p.y, { key: 'Escape' })
365
+ h.flush()
366
+ assert.deepEqual(h.focuses, [''])
367
+ h.view.unpinAll(); h.view.relayout(); h.view.configure({ center: 1, repulsion: 200, distance: 140 })
368
+ h.flush()
369
+ assert.ok(h.arcs.every(arc => Number.isFinite(arc.x) && Number.isFinite(arc.y)))
370
+ h.view.dispose()
371
+ })
372
+
181
373
  test('shipped browser bundle exposes the controller with no runtime npm imports', () => {
182
374
  const source = fs.readFileSync(new URL('../lib/webui/graph-view.bundle.js', import.meta.url), 'utf8')
183
- const scope = { setTimeout, clearTimeout, setInterval, clearInterval, performance }
375
+ assert.doesNotMatch(source, /d3-force|forceSimulation|forceManyBody|require\(/)
376
+ const scope = { setTimeout, clearTimeout, setInterval, clearInterval, performance, Date, Math, Map, Set, JSON, console }
184
377
  vm.runInNewContext(source, scope)
185
- assert.equal(typeof scope.DshMemuGraph.createGraphView, 'function')
186
- assert.equal(typeof scope.DshMemuGraph.createLayout, 'function')
378
+ const api = scope.DshMemuGraph
379
+ assert.equal(typeof api.createGraphView, 'function')
380
+ assert.equal(typeof api.createForceLayout, 'function')
381
+ assert.equal(typeof api.fitCamera, 'function')
382
+ assert.equal(typeof api.zoomCamera, 'function')
383
+ assert.equal(typeof api.placeLabels, 'function')
384
+ assert.equal(api.DEFAULT_OPTIONS.center, 0)
385
+ assert.equal(api.DEFAULT_OPTIONS.clusterScope, true)
187
386
  })
@@ -83,8 +83,13 @@ test('an explicit link source persists on the record and surfaces on graph edges
83
83
  const autoEdge = view.edges.find(edge => edge.from === 'mem-src-a' && edge.to === 'mem-src-b')
84
84
  assert.equal(autoEdge.source, 'auto', 'the UI can tag an auto link')
85
85
  assert.equal(autoEdge.kind, 'relation', 'link semantics are unchanged')
86
+ // Legacy auto edges written before the rule schema carry no evidence.rule;
87
+ // they must still surface under the 'auto' bucket so the WebUI rule filter
88
+ // has an option on old data (new writes record the real rule).
89
+ assert.equal(autoEdge.rule, 'auto', 'a legacy auto link reports the compat rule bucket')
86
90
  const plainEdge = view.edges.find(edge => edge.from === 'mem-src-b')
87
91
  assert.equal(plainEdge.source, null, 'a link without a source reports null, not undefined')
92
+ assert.equal(plainEdge.rule, null, 'a manual link reports no rule')
88
93
  })
89
94
 
90
95
  test('graphs cap nodes at 200 and the recall carries at most two pointers', async () => {
@@ -219,7 +219,7 @@ test('the deep link #/settings/help lands on the help page when standalone', asy
219
219
  window.location.hash = '#/settings/help'
220
220
 
221
221
  await mountAndSettle(component, props, { standalone: true })
222
- // hooks 已经带着 page=12(初始器读 hash);再渲染一次即命中帮助页。
222
+ // hooks 已经带着 page=13(初始器读 hash);再渲染一次即命中帮助页。
223
223
  forcedList = []
224
224
  effects = []
225
225
  cursor = 0
@@ -237,7 +237,7 @@ test('the help page shows five steps, eleven FAQ details and the feedback action
237
237
  await mountAndSettle(component, props)
238
238
  collectPageHook()
239
239
 
240
- const { tree } = renderAt(component, props, 12)
240
+ const { tree } = renderAt(component, props, 13)
241
241
  const text = treeText(tree)
242
242
  for (const step of [1, 2, 3, 4, 5]) assert.ok(text.includes(`helpStep${step}`), `quick start step ${step} is missing`)
243
243
  for (const n of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) {
@@ -271,7 +271,7 @@ test('the detailed help sections and label table render between quick start and
271
271
  await mountAndSettle(component, props)
272
272
  collectPageHook()
273
273
 
274
- const { tree } = renderAt(component, props, 12)
274
+ const { tree } = renderAt(component, props, 13)
275
275
  const text = treeText(tree)
276
276
  for (const section of ['helpScopes', 'helpTitleCards', 'helpArchiveDelete', 'helpVector', 'helpAutoLink', 'helpLabels', 'helpSidebar']) {
277
277
  assert.ok(text.includes(section), `help section ${section} is missing`)
@@ -0,0 +1,130 @@
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 { EventEmitter } from 'node:events'
7
+ import { PassThrough } from 'node:stream'
8
+ import { registerHooks } from 'node:module'
9
+
10
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-resident-route-'))
11
+ process.env.DSH_MEMU_HOME = home
12
+
13
+ // A recorded engine pointer is enough: the fake child replaces the interpreter,
14
+ // but currentEngine() still has to see a python/venv pair.
15
+ const engineDir = path.join(home, 'engine')
16
+ fs.mkdirSync(engineDir, { recursive: true })
17
+ fs.writeFileSync(path.join(engineDir, 'current.json'), JSON.stringify({
18
+ version: '0.11.0b3', venv: path.join(home, 'venv'), python: path.join(home, 'venv', 'python.exe'),
19
+ }))
20
+
21
+ const stub = new URL('./stubs/child-process-spy.mjs', import.meta.url)
22
+ registerHooks({
23
+ resolve(specifier, context, next) {
24
+ if (specifier === 'node:child_process' && String(context.parentURL || '').endsWith('/lib/memu.js')) {
25
+ return { url: stub.href, shortCircuit: true }
26
+ }
27
+ return next(specifier, context)
28
+ },
29
+ })
30
+
31
+ const spawns = []
32
+ const requests = []
33
+
34
+ function createFakeResident() {
35
+ const child = new EventEmitter()
36
+ child.stdin = new PassThrough()
37
+ child.stdout = new PassThrough()
38
+ child.stderr = new PassThrough()
39
+ child.killed = false
40
+ child.kill = () => {
41
+ child.killed = true
42
+ child.emit('close', 0)
43
+ return true
44
+ }
45
+ let buffer = ''
46
+ child.stdin.on('data', (chunk) => {
47
+ buffer += chunk.toString()
48
+ let newline
49
+ while ((newline = buffer.indexOf('\n')) >= 0) {
50
+ const line = buffer.slice(0, newline)
51
+ buffer = buffer.slice(newline + 1)
52
+ if (!line.trim()) continue
53
+ const request = JSON.parse(line)
54
+ requests.push(request)
55
+ if (request.op === 'shutdown') continue
56
+ const failed = request.argv[1] === 'boom'
57
+ const stdout = failed ? '' : JSON.stringify({ recall_files: [{ name: 'probe' }], command: request.argv[0] })
58
+ child.stdout.write(JSON.stringify({
59
+ id: request.id,
60
+ code: failed ? 1 : 0,
61
+ stdout,
62
+ stderr: failed ? 'retrieve exploded' : '',
63
+ }) + '\n')
64
+ }
65
+ })
66
+ process.nextTick(() => child.stdout.write(JSON.stringify({ ready: true }) + '\n'))
67
+ return child
68
+ }
69
+
70
+ globalThis.__dshMemuSpawnSpy = () => {
71
+ spawns.push(1)
72
+ return createFakeResident()
73
+ }
74
+
75
+ const memu = await import('../lib/memu.js')
76
+
77
+ test.after(() => {
78
+ delete globalThis.__dshMemuSpawnSpy
79
+ memu.closeMemuResident()
80
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
81
+ })
82
+
83
+ const common = {
84
+ route: 'remote-api',
85
+ db: path.join(home, 'libraries', 'lib_test.sqlite3'),
86
+ provider: 'openai',
87
+ embedModel: 'text-embedding-3-small',
88
+ baseUrl: 'https://example.invalid/v1',
89
+ apiKey: 'sk-probe',
90
+ }
91
+
92
+ test('the remote API vector route reuses one resident interpreter across commands', async () => {
93
+ const first = await memu.retrieve({ query: '码头', ...common })
94
+ const second = await memu.retrieve({ query: '雨伞', ...common })
95
+ const listed = await memu.listFiles({ ...common })
96
+
97
+ assert.equal(first.recall_files?.[0]?.name, 'probe')
98
+ assert.equal(second.recall_files?.[0]?.name, 'probe')
99
+ assert.equal(listed.recall_files?.[0]?.name, 'probe')
100
+ assert.equal(spawns.length, 1, 'three commands share one warm interpreter; one-process-per-command would be three spawns')
101
+ assert.equal(requests.length, 3, 'every command reached the resident worker')
102
+ assert.equal(requests[0].argv[0], 'retrieve')
103
+ assert.equal(requests[0].argv[1], '码头')
104
+ assert.equal(requests[2].argv[0], 'list-files')
105
+ // The API route's env travels per command, so reuse never pins the wrong key,
106
+ // model or database into the long-lived interpreter.
107
+ for (const request of requests) {
108
+ assert.equal(request.env.MEMU_BASE_URL, common.baseUrl)
109
+ assert.equal(request.env.MEMU_API_KEY, common.apiKey)
110
+ assert.equal(request.env.MEMU_EMBED_MODEL, common.embedModel)
111
+ assert.equal(request.env.MEMU_DB, common.db)
112
+ assert.equal(request.env.MEMU_MEMORY_MODE, 'local')
113
+ }
114
+ })
115
+
116
+ test('a failing API command rejects with the resident stderr instead of hanging', async () => {
117
+ await assert.rejects(
118
+ () => memu.retrieve({ query: 'boom', ...common }),
119
+ (error) => {
120
+ assert.equal(error.code, 'MEMU_COMMAND_FAILED')
121
+ assert.match(error.message, /retrieve exploded/)
122
+ return true
123
+ },
124
+ )
125
+ // The failed command must not take the interpreter down: the next one is served
126
+ // by the same warm process.
127
+ const after = await memu.retrieve({ query: '码头', ...common })
128
+ assert.equal(after.recall_files?.[0]?.name, 'probe')
129
+ assert.equal(spawns.length, 1)
130
+ })