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
@@ -212,14 +212,15 @@ test('the settings page renders every page instead of a blank panel', async () =
212
212
  await new Promise((resolve) => setTimeout(resolve, 0))
213
213
  await new Promise((resolve) => setTimeout(resolve, 0))
214
214
 
215
- for (let page = 0; page < 12; page++) {
215
+ // 13 页(含新增的关系图谱 graph:10);help 仍是最后一页,未纳入这轮巡检。
216
+ for (let page = 0; page < 13; page++) {
216
217
  const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, page)
217
218
  const text = treeText(tree)
218
219
  assert.match(String(tree.props?.className), /dshm-root/, `page ${page} did not render the shell`)
219
220
  // The rail is the nav: every page label has to be there. Counting the shared
220
221
  // dshm-nav-item class instead would also pick up the in-page tab strips (memory
221
222
  // backend, prompt scope, browser view), which use the same widget on purpose.
222
- const NAV = ['pageOverview', 'pageConnection', 'pageSettings', 'pageFolders', 'pageLibraries', 'pageBrowser', 'pageGlobal', 'pagePrompts', 'pageStats', 'pageMemories', 'pageLogs', 'pageLexicon']
223
+ const NAV = ['pageOverview', 'pageConnection', 'pageSettings', 'pageFolders', 'pageLibraries', 'pageBrowser', 'pageGlobal', 'pagePrompts', 'pageStats', 'pageMemories', 'pageGraph', 'pageLogs', 'pageLexicon']
223
224
  assert.ok(NAV.every((key) => text.includes(key)), `page ${page} lost a nav entry`)
224
225
  assert.equal((text.match(/dshm-nav-ind/g) || []).length, 1, `page ${page} lost or duplicated its rail indicator`)
225
226
  assert.match(text, /dshm-page/, `page ${page} lost the content pane`)
@@ -938,10 +939,10 @@ test('failed and degraded activity rows are visually distinguished from normal r
938
939
  collectPageHook()
939
940
  for (const effect of first.effects) effect.fn()
940
941
  await new Promise((resolve) => setTimeout(resolve, 0))
941
- const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
942
+ const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
942
943
  for (const effect of mid.effects) effect.fn()
943
944
  await new Promise((resolve) => setTimeout(resolve, 0))
944
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
945
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
945
946
  const rows = new Map()
946
947
  const labels = []
947
948
  walkNodes(tree, (node) => {
@@ -998,11 +999,11 @@ test('the log page renders rows with copy, download and locate actions', async (
998
999
  await new Promise((resolve) => setTimeout(resolve, 0))
999
1000
  // The log page's own effect only exists once that page renders, so it needs one
1000
1001
  // more render + effect pass before the data is in the hook.
1001
- const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
1002
+ const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1002
1003
  for (const effect of mid.effects) effect.fn()
1003
1004
  await new Promise((resolve) => setTimeout(resolve, 0))
1004
1005
  await new Promise((resolve) => setTimeout(resolve, 0))
1005
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
1006
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1006
1007
  const text = treeText(tree)
1007
1008
  assert.match(text, /整理超时/)
1008
1009
  assert.match(text, /logCopyAll/)
@@ -771,3 +771,151 @@ test('compactSeedEvents accepts the catalog and local recall as two read-only pr
771
771
  assert.equal(seed[2].type, 'user/message')
772
772
  assert.match(seed[2].data.content[0].text, /事件时间/)
773
773
  })
774
+
775
+ // ------------------------------------------------------- surface replacements
776
+ // Mirrors @deepseek-ai/dsh-session 0.2.2-rc.1 Session.create for the fields a
777
+ // consolidation seed touches: seq contiguity plus the surface fold. The host
778
+ // rejects "seed event at index N has seq M" and every dangling replace citation,
779
+ // so the assertion has to replay the fold, not just look at one event.
780
+ const HOST_SURFACE_EVENT_TYPES = new Set(['system/message', 'developer/message', 'user/message', 'assistant/message', 'tool/result'])
781
+ function assertSeedAcceptedByHost(seed, label = 'seed') {
782
+ const nodes = []
783
+ seed.forEach((event, index) => {
784
+ assert.equal(event.seq, index, `${label}: event at index ${index} has seq ${event.seq}`)
785
+ if (!HOST_SURFACE_EVENT_TYPES.has(event.type)) {
786
+ assert.equal(event.surfaceOp, undefined, `${label}: ${event.type} cannot carry surfaceOp`)
787
+ assert.equal(event.sourceEventSeqs, undefined, `${label}: ${event.type} cannot carry sourceEventSeqs`)
788
+ return
789
+ }
790
+ const op = event.surfaceOp
791
+ assert.ok(op !== undefined, `${label}: ${event.type} at ${index} requires a surfaceOp marker`)
792
+ const sources = event.sourceEventSeqs
793
+ if (sources !== undefined) {
794
+ assert.ok(Array.isArray(sources) && sources.length > 0, `${label}: sourceEventSeqs must be a non-empty array`)
795
+ assert.equal(new Set(sources).size, sources.length, `${label}: sourceEventSeqs must not repeat`)
796
+ assert.ok(sources.every(seq => Number.isSafeInteger(seq) && seq < event.seq), `${label}: sourceEventSeqs must reference earlier events`)
797
+ }
798
+ if (op === 'append') {
799
+ nodes.push(event.seq)
800
+ return
801
+ }
802
+ assert.deepEqual(Object.keys(op).sort(), ['endSeq', 'op', 'startSeq'], `${label}: replace markers carry exactly op/startSeq/endSeq`)
803
+ assert.ok(op.startSeq < event.seq && op.endSeq < event.seq, `${label}: surface replace at ${index} must reference earlier events`)
804
+ const startIdx = nodes.indexOf(op.startSeq)
805
+ const endIdx = nodes.indexOf(op.endSeq)
806
+ assert.ok(startIdx >= 0, `${label}: replace start seq ${op.startSeq} is not on the surface`)
807
+ assert.ok(endIdx >= startIdx, `${label}: replace range must be ordered`)
808
+ const shadowed = nodes.slice(startIdx, endIdx + 1)
809
+ if (event.type === 'tool/result') assert.equal(shadowed.length, 1, `${label}: tool/result replacement rewrites exactly one node`)
810
+ assert.ok(Array.isArray(sources), `${label}: replace at ${index} needs sourceEventSeqs`)
811
+ assert.deepEqual(shadowed.filter(seq => !sources.includes(seq)), [], `${label}: replace at ${index} must cite every shadowed node`)
812
+ nodes.splice(startIdx, endIdx - startIdx + 1)
813
+ nodes.push(event.seq)
814
+ })
815
+ }
816
+
817
+ const userEvent = (seq, text, extra = {}) => ({
818
+ seq, type: 'user/message', surfaceOp: 'append',
819
+ data: { source: { kind: 'user' }, content: [{ type: 'text', text }] }, ...extra,
820
+ })
821
+ const assistantEvent = (seq, text) => ({
822
+ seq, type: 'assistant/message', surfaceOp: 'append',
823
+ data: { message: { content: [{ type: 'text', text }] } },
824
+ })
825
+ const toolResultEvent = (seq, text, extra = {}) => ({
826
+ seq, type: 'tool/result', surfaceOp: 'append',
827
+ data: { message: { content: [{ type: 'text', text }] } }, ...extra,
828
+ })
829
+
830
+ test('a surface replace is renumbered into the seed instead of citing original seqs', () => {
831
+ const seed = compactSeedEvents([
832
+ userEvent(0, '记住:周五交房租'),
833
+ assistantEvent(1, '好'),
834
+ toolResultEvent(2, '原始工具输出'),
835
+ toolResultEvent(3, '[已裁剪]', {
836
+ surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 },
837
+ sourceEventSeqs: [2],
838
+ }),
839
+ userEvent(4, '继续'),
840
+ ])
841
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4])
842
+ assert.deepEqual(seed[3].surfaceOp, { op: 'replace', startSeq: 2, endSeq: 2 }, 'the citation follows the surviving node, not its original seq')
843
+ assert.deepEqual(seed[3].sourceEventSeqs, [2])
844
+ assertSeedAcceptedByHost(seed)
845
+ })
846
+
847
+ test('a replace pointing outside the window is dropped and the seed stays contiguous', () => {
848
+ // 窗口从父会话中间切出:seq 4 不在这一窗里;后面的 replace 又引用前面被丢的
849
+ // replace。旧实现先编号后丢弃,留下 seq 空洞,宿主报 index 1 has seq 5。
850
+ const seed = compactSeedEvents([
851
+ userEvent(10, '这一窗的第一句'),
852
+ toolResultEvent(11, '输出'),
853
+ toolResultEvent(12, '[已裁剪]', {
854
+ surfaceOp: { op: 'replace', startSeq: 4, endSeq: 4 },
855
+ sourceEventSeqs: [4],
856
+ }),
857
+ assistantEvent(13, '回答'),
858
+ toolResultEvent(14, '[已裁剪]', {
859
+ surfaceOp: { op: 'replace', startSeq: 12, endSeq: 12 },
860
+ sourceEventSeqs: [12],
861
+ }),
862
+ ])
863
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2], 'dropping a patch must renumber the survivors')
864
+ assert.equal(seed.some(event => event.surfaceOp && typeof event.surfaceOp === 'object'), false)
865
+ assertSeedAcceptedByHost(seed)
866
+ })
867
+
868
+ test('a replacement that cites another replacement keeps both when their targets survive', () => {
869
+ const seed = compactSeedEvents([
870
+ userEvent(0, '开头'),
871
+ toolResultEvent(1, '原始输出'),
872
+ toolResultEvent(2, '[第一次裁剪]', {
873
+ surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 },
874
+ sourceEventSeqs: [1],
875
+ }),
876
+ assistantEvent(3, '中间'),
877
+ toolResultEvent(4, '[第二次裁剪]', {
878
+ surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 },
879
+ sourceEventSeqs: [2],
880
+ }),
881
+ ])
882
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4])
883
+ assert.deepEqual(seed[2].surfaceOp, { op: 'replace', startSeq: 1, endSeq: 1 })
884
+ assert.deepEqual(seed[4].surfaceOp, { op: 'replace', startSeq: 2, endSeq: 2 })
885
+ assertSeedAcceptedByHost(seed)
886
+ })
887
+
888
+ test('a multi-node replace is remapped when every shadowed node survives', () => {
889
+ const seed = compactSeedEvents([
890
+ userEvent(0, 'A'),
891
+ userEvent(1, 'X'),
892
+ userEvent(2, 'B'),
893
+ userEvent(3, '外层摘要', {
894
+ surfaceOp: { op: 'replace', startSeq: 0, endSeq: 2 },
895
+ sourceEventSeqs: [0, 1, 2],
896
+ }),
897
+ ])
898
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3])
899
+ assert.deepEqual(seed[3].surfaceOp, { op: 'replace', startSeq: 0, endSeq: 2 })
900
+ assert.deepEqual(seed[3].sourceEventSeqs, [0, 1, 2])
901
+ assertSeedAcceptedByHost(seed)
902
+ })
903
+
904
+ test('a replace is dropped when filtering an inner checkpoint reveals a shadowed node', () => {
905
+ // 内层压缩检查点(source.kind 不是 user)会被种子过滤器丢掉;它遮住的 X 因此
906
+ // 重新出现在种子的 surface 上。外层替换写于 X 被遮住期间,引用里没有 X。
907
+ // 宿主会要求外层补上 X 的引用——补不出来就只能丢外层,种子回到纯 append。
908
+ const seed = compactSeedEvents([
909
+ userEvent(0, 'A'),
910
+ userEvent(1, 'X'),
911
+ userEvent(2, 'B'),
912
+ userEvent(3, '内层摘要', { data: { source: { kind: 'compact-checkpoint' }, content: [{ type: 'text', text: '内层摘要' }] }, surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 }, sourceEventSeqs: [1] }),
913
+ userEvent(4, '外层摘要', {
914
+ surfaceOp: { op: 'replace', startSeq: 0, endSeq: 2 },
915
+ sourceEventSeqs: [0, 2],
916
+ }),
917
+ ])
918
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2])
919
+ assert.deepEqual(seed.map(event => event.data.content[0].text), ['A', 'X', 'B'])
920
+ assertSeedAcceptedByHost(seed)
921
+ })
@@ -177,7 +177,7 @@ test('a fork that cannot be created is logged, not dropped silently', async () =
177
177
  },
178
178
  }
179
179
  await cycle.runSleepPass(ctx, { log: (m) => logs.push(m) })
180
- assert.ok(logs.some((m) => /consolidation skipped for cycle-hist: no fork in test env/.test(m)), 'attempt logged: ' + logs.join(' | '))
180
+ assert.ok(logs.some((m) => /consolidation skipped for cycle-hist: .*no fork in test env/.test(m)), 'attempt logged: ' + logs.join(' | '))
181
181
  assert.equal(state.getLastSleepAt('cycle-hist'), null)
182
182
  assert.match(state.getSessionBinding('cycle-hist').lastSleepError, /no fork/)
183
183
  })
@@ -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,96 @@ 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('configure maps all three force sliders and reheats without ever going non-finite', () => {
106
+ assert.equal(DEFAULT_OPTIONS.center, 0, 'center force is off by default')
107
+ assert.equal(DEFAULT_OPTIONS.clusterScope, true)
108
+ const layout = createForceLayout()
109
+ layout.update(graph(40)); layout.settle(80)
110
+ const cooled = layout.alpha
111
+ layout.configure({ repulsion: 300, distance: 180, center: 2 })
112
+ assert.ok(layout.alpha > cooled)
113
+ for (let i = 0; i < 200; i++) layout.tick()
114
+ assert.ok(layout.nodes.every(node => Number.isFinite(node.x) && Number.isFinite(node.y)))
115
+ layout.dispose()
116
+ })
117
+
118
+ test('drag scope freezes other clusters and repels the dragged one from them', () => {
119
+ // 两簇各 12 节点,链状相连;A 在左,B 在右,互不连通。
120
+ const nodes = [], edges = []
121
+ for (let group = 0; group < 2; group++) for (let i = 0; i < 12; i++) {
122
+ const id = `${group}-${String(i).padStart(2, '0')}`
123
+ nodes.push({ id, title: id, kind: 'memory' })
124
+ if (i) edges.push({ from: `${group}-${String(i - 1).padStart(2, '0')}`, to: id })
125
+ }
126
+ const layout = createForceLayout()
127
+ layout.update({ nodes, edges })
128
+ // 手动把两簇分开(布局原长由首次见到的距离决定,这里覆盖成稳定值)。
129
+ 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 })
130
+ layout.edges.forEach(edge => { edge.baseLen = 12 })
131
+ layout.settle(80)
132
+ const frozen = layout.nodes.slice(12).map(node => ({ id: node.id, x: node.x, y: node.y }))
133
+ const dragged = layout.nodes[0]
134
+ const scope = layout.startDragScope(dragged.id)
135
+ assert.ok(scope?.ids.size === 12, 'the drag scope is exactly one connected component')
136
+ assert.ok(!scope.ids.has(layout.nodes[12].id))
137
+ const centerX = frozen.reduce((sum, n) => sum + n.x, 0) / frozen.length
138
+ const centerY = frozen.reduce((sum, n) => sum + n.y, 0) / frozen.length
139
+ // 把整簇硬塞到冻结簇中心:靠单向斥力把活动簇推开,冻结簇自身只当障碍。
140
+ layout.reheat(.9)
141
+ for (let i = 0; i < scope.members.length; i++) {
142
+ const member = scope.members[i]
143
+ if (member === dragged) continue
144
+ member.x = centerX + (i % 4) * 4 - 6
145
+ member.y = centerY + Math.floor(i / 4) * 4 - 6
146
+ member.vx = 0; member.vy = 0
147
+ }
148
+ // 落点放在冻结簇包围盒之外:pin 节点优先跟手,不能被硬分离挪动。
149
+ layout.pin(dragged.id, Math.max(...frozen.map(n => n.x)) + 60, centerY)
150
+ for (let i = 0; i < 80; i++) layout.tick()
151
+ layout.setDragging(false)
152
+ for (let i = 0; i < 20; i++) layout.tick()
153
+ // 100 ticks 内 alpha 仍高于 .05,作用域未解除,其他簇必须一像素都不动。
154
+ for (const before of frozen) {
155
+ const after = layout.nodeById(before.id)
156
+ assert.equal(after.x, before.x, 'frozen clusters must not move at all')
157
+ assert.equal(after.y, before.y)
158
+ }
159
+ let min = Infinity
160
+ 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))
161
+ assert.ok(min > 12, `clusters must not overlap (min distance ${min.toFixed(1)} world px)`)
162
+ layout.dispose()
163
+ })
164
+
82
165
  function harness(reducedMotion = true) {
83
- const handlers = new Map(), windowHandlers = new Map(), frames = new Map(), arcs = [], focuses = []
166
+ const handlers = new Map(), windowHandlers = new Map(), frames = new Map(), arcs = [], focuses = [], texts = []
84
167
  let id = 0
85
168
  const ctx = new Proxy({
86
169
  arc(x, y, radius) { arcs.push({ x, y, radius }) },
87
170
  measureText(text) { return { width: text.length * 7 } },
88
- clearRect() { arcs.length = 0 },
171
+ clearRect() { arcs.length = 0; texts.length = 0 },
172
+ fillText(text) { texts.push(String(text)) },
89
173
  }, { get(target, key) { return key in target ? target[key] : () => {} } })
90
174
  const win = {
91
175
  requestAnimationFrame(fn) { frames.set(++id, fn); return id },
@@ -114,10 +198,20 @@ function harness(reducedMotion = true) {
114
198
  const emit = (type, x, y, extra = {}) => handlers.get(type)?.({
115
199
  type, clientX: x, clientY: y, button: 0, pointerId: 1, pointerType: 'mouse', preventDefault() {}, ...extra,
116
200
  })
117
- return { view, flush, emit, arcs, frames, focuses, handlers, windowHandlers }
201
+ return { view, flush, emit, arcs, texts, frames, focuses, handlers, windowHandlers }
118
202
  }
119
203
 
120
- test('dragging after cooling pins the node without click/refocus, and refresh keeps pixel position', () => {
204
+ test('the detailed layer actually paints labels and the label switch silences them', () => {
205
+ const h = harness()
206
+ h.view.update(graph(10)); h.flush()
207
+ assert.ok(h.texts.length > 0, 'labels must reach fillText (radius/textWidth must be finite)')
208
+ assert.ok(h.texts.length <= 10, 'labels must never be painted more often than there are nodes')
209
+ h.view.configure({ labels: false }); h.flush()
210
+ assert.equal(h.texts.length, 0)
211
+ h.view.dispose()
212
+ })
213
+
214
+ test('left drag never locks the node; right click toggles the pin; refresh preserves position', () => {
121
215
  const h = harness()
122
216
  h.view.update(graph(1)); h.flush()
123
217
  const p = { ...h.arcs[0] }
@@ -127,14 +221,40 @@ test('dragging after cooling pins the node without click/refocus, and refresh ke
127
221
  h.flush()
128
222
  assert.equal(h.arcs[0].x, p.x + 70); assert.equal(h.arcs[0].y, p.y + 25)
129
223
  h.emit('pointerup', p.x + 70, p.y + 25); h.flush()
130
- assert.deepEqual(h.focuses, [])
224
+ assert.deepEqual(h.focuses, [], 'a drag must never focus/refetch')
225
+ assert.equal(h.view.isPinned('n000'), false, 'a left drag must not pin the node')
226
+ // 松手后位置留在落点,心跳刷新不把它拽回。
227
+ for (let i = 0; i < 3; i++) { h.view.update(graph(1)); h.flush() }
228
+ assert.equal(h.arcs[0].x, p.x + 70); assert.equal(h.arcs[0].y, p.y + 25)
131
229
  h.emit('pointerdown', p.x + 70, p.y + 25)
132
230
  h.emit('pointerup', p.x + 70, p.y + 25)
133
- assert.deepEqual(h.focuses, ['n000'])
231
+ assert.deepEqual(h.focuses, ['n000'], 'a click without movement still focuses')
232
+ // 右键 = 锁定 / 解除,左键从不产生固定点。
233
+ h.emit('contextmenu', p.x + 70, p.y + 25); h.flush()
234
+ assert.equal(h.view.isPinned('n000'), true, 'right click pins the node')
235
+ assert.equal(h.view.pinnedCount(), 1)
236
+ assert.equal(h.arcs[0].x, p.x + 70, 'pinning must not teleport the node')
237
+ h.emit('contextmenu', p.x + 70, p.y + 25); h.flush()
238
+ assert.equal(h.view.isPinned('n000'), false, 'right click again unpins')
239
+ assert.equal(h.view.pinnedCount(), 0)
134
240
  h.view.dispose()
135
241
  assert.equal(h.handlers.size, 0); assert.equal(h.frames.size, 0); assert.equal(h.windowHandlers.size, 0)
136
242
  })
137
243
 
244
+ test('dragging an already pinned node keeps the lock at the new position', () => {
245
+ const h = harness()
246
+ h.view.update(graph(1)); h.flush()
247
+ const p = { ...h.arcs[0] }
248
+ h.emit('contextmenu', p.x, p.y); h.flush()
249
+ assert.equal(h.view.isPinned('n000'), true)
250
+ h.emit('pointerdown', p.x, p.y)
251
+ h.emit('pointermove', p.x + 40, p.y + 10)
252
+ h.emit('pointerup', p.x + 40, p.y + 10); h.flush()
253
+ assert.equal(h.view.isPinned('n000'), true, 'an existing lock survives a left drag')
254
+ assert.equal(h.arcs[0].x, p.x + 40)
255
+ h.view.dispose()
256
+ })
257
+
138
258
  test('pan/zoom and equivalent refresh never re-fit the camera; cancelled pointer never clicks', () => {
139
259
  const h = harness()
140
260
  h.view.update(graph(1)); h.flush()
@@ -163,7 +283,7 @@ test('dense hit targets choose the closest node, not the last node in draw order
163
283
  test('pinch does not trigger focus and reduced-motion/paused views do not run an idle animation loop', () => {
164
284
  const h = harness()
165
285
  h.view.update(graph(10)); h.flush()
166
- assert.equal(h.frames.size, 0)
286
+ assert.equal(h.frames.size, 0, 'reduced motion must not keep a rAF loop alive')
167
287
  const p = h.arcs[0]
168
288
  h.emit('pointerdown', p.x, p.y, { pointerType: 'touch' })
169
289
  h.emit('pointerdown', p.x + 40, p.y, { pointerType: 'touch', pointerId: 2 })
@@ -174,14 +294,36 @@ test('pinch does not trigger focus and reduced-motion/paused views do not run an
174
294
  h.view.dispose()
175
295
  const paused = harness(false)
176
296
  paused.view.configure({ motion: false }); paused.view.update(graph(10)); paused.flush()
177
- assert.equal(paused.frames.size, 0)
297
+ assert.equal(paused.frames.size, 0, 'paused motion must not keep a rAF loop alive')
178
298
  paused.view.dispose()
179
299
  })
180
300
 
301
+ test('Escape cancels a drag and clears the focus; toolbar actions do not throw', () => {
302
+ const h = harness()
303
+ h.view.update(graph(3)); h.flush()
304
+ const p = { ...h.arcs[0] }
305
+ h.emit('pointerdown', p.x, p.y)
306
+ h.emit('pointermove', p.x + 50, p.y + 30)
307
+ h.emit('keydown', p.x, p.y, { key: 'Escape' })
308
+ h.flush()
309
+ assert.deepEqual(h.focuses, [''])
310
+ h.view.unpinAll(); h.view.relayout(); h.view.configure({ center: 1, repulsion: 200, distance: 140 })
311
+ h.flush()
312
+ assert.ok(h.arcs.every(arc => Number.isFinite(arc.x) && Number.isFinite(arc.y)))
313
+ h.view.dispose()
314
+ })
315
+
181
316
  test('shipped browser bundle exposes the controller with no runtime npm imports', () => {
182
317
  const source = fs.readFileSync(new URL('../lib/webui/graph-view.bundle.js', import.meta.url), 'utf8')
183
- const scope = { setTimeout, clearTimeout, setInterval, clearInterval, performance }
318
+ assert.doesNotMatch(source, /d3-force|forceSimulation|forceManyBody|require\(/)
319
+ const scope = { setTimeout, clearTimeout, setInterval, clearInterval, performance, Date, Math, Map, Set, JSON, console }
184
320
  vm.runInNewContext(source, scope)
185
- assert.equal(typeof scope.DshMemuGraph.createGraphView, 'function')
186
- assert.equal(typeof scope.DshMemuGraph.createLayout, 'function')
321
+ const api = scope.DshMemuGraph
322
+ assert.equal(typeof api.createGraphView, 'function')
323
+ assert.equal(typeof api.createForceLayout, 'function')
324
+ assert.equal(typeof api.fitCamera, 'function')
325
+ assert.equal(typeof api.zoomCamera, 'function')
326
+ assert.equal(typeof api.placeLabels, 'function')
327
+ assert.equal(api.DEFAULT_OPTIONS.center, 0)
328
+ assert.equal(api.DEFAULT_OPTIONS.clusterScope, true)
187
329
  })
@@ -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
+ })