dsh-memu-memory 1.3.12 → 1.3.13

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.
@@ -212,15 +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
- // 13 页(含新增的关系图谱 graph:10);help 仍是最后一页,未纳入这轮巡检。
216
- for (let page = 0; page < 13; page++) {
215
+ // 14 页(含新增的关系图谱 graph:10 与诊断页 diagnostics:14);help 仍是最后一页,未纳入这轮巡检。
216
+ for (let page = 0; page < 14; page++) {
217
217
  const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, page)
218
218
  const text = treeText(tree)
219
219
  assert.match(String(tree.props?.className), /dshm-root/, `page ${page} did not render the shell`)
220
220
  // The rail is the nav: every page label has to be there. Counting the shared
221
221
  // dshm-nav-item class instead would also pick up the in-page tab strips (memory
222
222
  // backend, prompt scope, browser view), which use the same widget on purpose.
223
- const NAV = ['pageOverview', 'pageConnection', 'pageSettings', 'pageFolders', 'pageLibraries', 'pageBrowser', 'pageGlobal', 'pagePrompts', 'pageStats', 'pageMemories', 'pageGraph', 'pageLogs', 'pageLexicon']
223
+ const NAV = ['pageOverview', 'pageConnection', 'pageSettings', 'pageFolders', 'pageLibraries', 'pageBrowser', 'pageGlobal', 'pagePrompts', 'pageStats', 'pageMemories', 'pageGraph', 'pageLogs', 'pageLexicon', 'pageDiagnostics']
224
224
  assert.ok(NAV.every((key) => text.includes(key)), `page ${page} lost a nav entry`)
225
225
  assert.equal((text.match(/dshm-nav-ind/g) || []).length, 1, `page ${page} lost or duplicated its rail indicator`)
226
226
  assert.match(text, /dshm-page/, `page ${page} lost the content pane`)
@@ -230,6 +230,119 @@ test('the settings page renders every page instead of a blank panel', async () =
230
230
  }
231
231
  })
232
232
 
233
+ async function graphStudioHarness(call, libraries) {
234
+ const ctx = fakeCtx()
235
+ globalThis.__dshMemuExports.apply(ctx)
236
+ const settings = registrations.filter(row => row.slot === 'settings.section').pop()
237
+ const shell = await withHash('#/settings/graph', async () => {
238
+ const props = { ctx, t: key => key, standalone: true }
239
+ const first = await renderPage(settings.component, props, undefined, { remount: true })
240
+ for (const effect of first.effects) effect.fn()
241
+ await new Promise(resolve => setTimeout(resolve, 0))
242
+ return (await renderPage(settings.component, props)).tree
243
+ })
244
+ let studio
245
+ walkNodes(shell, node => { if (node.type?.name === 'GraphStudioPanel') { studio = node; return false } })
246
+ assert.ok(studio, 'graph studio not found')
247
+ const props = { ...studio.props, t: key => key, call, libraries }
248
+ const previous = new Map()
249
+ const pick = (tree, predicate) => {
250
+ const found = []
251
+ const visit = node => {
252
+ if (!node || typeof node !== 'object') return
253
+ if (Array.isArray(node)) { node.forEach(visit); return }
254
+ if (predicate(node)) found.push(node)
255
+ if (typeof node.type !== 'function') visit(node.props?.children)
256
+ }
257
+ visit(tree)
258
+ return found
259
+ }
260
+ let first = true
261
+ const render = async (flush = false) => {
262
+ let view = await renderPage(studio.type, props, undefined, { remount: first })
263
+ first = false
264
+ if (flush) {
265
+ for (const effect of view.effects) {
266
+ const old = previous.get(effect.index)
267
+ if (old && effect.deps?.length === old.deps?.length && effect.deps?.every((value, i) => Object.is(value, old.deps[i]))) continue
268
+ old?.cleanup?.()
269
+ previous.set(effect.index, { deps: effect.deps, cleanup: effect.fn() })
270
+ }
271
+ await new Promise(resolve => setTimeout(resolve, 0))
272
+ view = await renderPage(studio.type, props)
273
+ }
274
+ return view.tree
275
+ }
276
+ return { render, pick, close: () => { for (const value of previous.values()) value.cleanup?.() } }
277
+ }
278
+
279
+ test('graph studio pages all libraries and filters custom domains without merging identities', async () => {
280
+ const libraries = [{ id: 'lib-a', name: 'A' }, { id: 'lib-b', name: 'B' }], calls = []
281
+ const call = async (endpoint, payload) => {
282
+ calls.push({ endpoint, payload })
283
+ if (endpoint === 'getMemory') return { entry: { title: 'B editable', content: 'B full body' } }
284
+ if (endpoint !== 'getGraph') return { items: [] }
285
+ const domain = payload.libraryId === 'lib-a' ? 'coding' : 'project:travel'
286
+ const memories = Array.from({ length: payload.libraryId === 'lib-a' ? 201 : 1 }, (_, i) => ({
287
+ id: i ? 'mem-' + i : 'mem-shared', title: payload.libraryId + '-memory-' + i, kind: 'memory', domain,
288
+ }))
289
+ const nodes = payload.domain && payload.domain !== domain ? [] : [...memories, { id: 'ent-shared', title: payload.libraryId + '-person', kind: 'person' }]
290
+ const offset = payload.offset || 0, next = offset + 200
291
+ return { nodes: nodes.slice(offset, next), edges: !offset && nodes.length ? [{ from: 'mem-shared', to: 'ent-shared', kind: 'person' }] : [],
292
+ nextOffset: next < nodes.length ? next : null, domains: ['coding', 'project:travel'] }
293
+ }
294
+ const view = await graphStudioHarness(call, libraries)
295
+ try {
296
+ let tree = await view.render(true)
297
+ view.pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: '__global__' } })
298
+ tree = await view.render(true)
299
+ const canvas = () => view.pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph
300
+ assert.equal(canvas().nodes.length, 204)
301
+ assert.equal(canvas().nodes.filter(node => node.kind === 'person').length, 2)
302
+ assert.equal(new Set(canvas().nodes.map(node => node.id)).size, 204)
303
+ assert.equal(canvas().edges.length, 2)
304
+ for (const edge of canvas().edges) assert.equal(canvas().nodes.find(node => node.id === edge.from).libraryId, canvas().nodes.find(node => node.id === edge.to).libraryId)
305
+ assert.ok(calls.some(row => row.payload.libraryId === 'lib-a' && row.payload.offset === 200))
306
+ view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: ' PROJECT:travel ' } })
307
+ tree = await view.render(true)
308
+ assert.equal(canvas().nodes.length, 2)
309
+ assert.ok(canvas().nodes.every(node => node.libraryId === 'lib-b'))
310
+ assert.ok(calls.some(row => row.payload.domain === 'project:travel'))
311
+ view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: 'project:travel' } })
312
+ tree = await view.render(true)
313
+ assert.equal(canvas().nodes.length, 2, 'equivalent domain input must not clear the graph')
314
+ view.pick(tree, node => node.type === 'button' && node.props.children === 'gsManage')[0].props.onClick()
315
+ tree = await view.render()
316
+ const rows = view.pick(tree, node => String(node.props?.className || '').split(' ').includes('dshm-gs-mgr-row'))
317
+ assert.equal(rows.length, 2, 'management uses the same domain filter')
318
+ rows.find(row => treeText(row).includes('lib-b-memory-0')).props.onClick()
319
+ tree = await view.render()
320
+ view.pick(tree, node => node.type === 'button' && node.props['aria-label'] === 'gsEditNode')[0].props.onClick()
321
+ await new Promise(resolve => setTimeout(resolve, 0))
322
+ assert.deepEqual(calls.find(row => row.endpoint === 'getMemory').payload, { libraryId: 'lib-b', id: 'mem-shared' })
323
+ tree = await view.render()
324
+ view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: '' } })
325
+ tree = await view.render(true)
326
+ assert.equal(canvas().nodes.length, 204)
327
+ } finally { view.close() }
328
+ })
329
+
330
+ test('graph studio surfaces failed libraries and retains successful results', async () => {
331
+ const call = async (endpoint, payload) => {
332
+ if (endpoint !== 'getGraph') return { items: [] }
333
+ if (payload.libraryId === 'lib-denied') throw new Error('forbidden')
334
+ return { nodes: [{ id: 'mem-ok', title: 'visible', kind: 'memory' }], edges: [], nextOffset: null }
335
+ }
336
+ const view = await graphStudioHarness(call, [{ id: 'lib-ok', name: 'OK' }, { id: 'lib-denied', name: 'Denied library' }])
337
+ try {
338
+ let tree = await view.render(true)
339
+ view.pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: '__global__' } })
340
+ tree = await view.render(true)
341
+ assert.equal(view.pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.nodes.length, 1)
342
+ assert.match(treeText(view.pick(tree, node => node.props?.role === 'alert')[0]), /gsLoadPartial.*Denied library/)
343
+ } finally { view.close() }
344
+ })
345
+
233
346
  test('the immersive graph shell stays with the standalone WebUI', async () => {
234
347
  // 点「关系图谱」把宿主页面的导航条掰成 158px 竖排,是 is-graph-wide 没分外壳造成的:
235
348
  // 那套样式是为独立 WebUI 的全屏画布写的,宿主设置页只需要普通横排导航 + 一个入口按钮。
@@ -0,0 +1,257 @@
1
+ // 诊断体系(lib/diagnostics.js / lib/environment-check.js / lib/paths.js 的锁判据)的回归测试。
2
+ // 这些代码的失败方式是"静默":写盘失败被吞、锁永远不释放、摘要判定把好档案判废。
3
+ // 所以每个断言都盯着"它有没有发出可见信号",而不是只看返回值。
4
+ import test from 'node:test'
5
+ import assert from 'node:assert/strict'
6
+ import fs from 'node:fs'
7
+ import os from 'node:os'
8
+ import path from 'node:path'
9
+ import { execFileSync } from 'node:child_process'
10
+ import { pathToFileURL } from 'node:url'
11
+
12
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-diagnostics-'))
13
+ process.env.DSH_MEMU_HOME = home
14
+ process.env.DSH_MEMU_MEMORY_HOME = home
15
+
16
+ const diag = await import('../lib/diagnostics.js')
17
+ const paths = await import('../lib/paths.js')
18
+ const vp = await import('../lib/vector-profile.js')
19
+
20
+ test.after(() => {
21
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
22
+ })
23
+
24
+ test.beforeEach(() => {
25
+ diag.clearDiagnostics()
26
+ paths.setLockEventSink(null)
27
+ paths.setWarnSink(null)
28
+ })
29
+
30
+ // ---------------------------------------------------------------- 记录与去重
31
+
32
+ test('the same fault inside the dedupe window bumps a counter instead of adding rows', () => {
33
+ const first = diag.recordDiagnostic({ level: 'error', scope: 'vector', code: 'VECTOR_PROFILE_MANIFEST_CHANGED', message: 'manifest moved' })
34
+ const second = diag.recordDiagnostic({ level: 'error', scope: 'vector', code: 'VECTOR_PROFILE_MANIFEST_CHANGED', message: 'manifest moved' })
35
+ assert.equal(second.count, 2)
36
+ assert.equal(second.id, first.id, 'a repeat must keep the same row id')
37
+ const { items, total, counts } = diag.listDiagnostics({})
38
+ assert.equal(total, 1)
39
+ assert.equal(items[0].count, 2)
40
+ assert.equal(counts.error, 1)
41
+ })
42
+
43
+ test('a different message with the same code stays a separate row', () => {
44
+ diag.recordDiagnostic({ level: 'error', scope: 'vector', code: 'LOCAL_VECTOR_WORKER_EXITED', message: 'worker died: a' })
45
+ diag.recordDiagnostic({ level: 'error', scope: 'vector', code: 'LOCAL_VECTOR_WORKER_EXITED', message: 'worker died: b' })
46
+ assert.equal(diag.listDiagnostics({}).total, 2)
47
+ })
48
+
49
+ test('diagnostics land in their own file, not in the activity log', () => {
50
+ diag.recordDiagnostic({ level: 'warn', scope: 'engine', code: 'ENGINE_MISSING', message: 'no python' })
51
+ const csv = path.join(home, 'diagnostics', 'events.jsonl')
52
+ assert.ok(fs.existsSync(csv), 'diagnostics/events.jsonl must exist')
53
+ const lines = fs.readFileSync(csv, 'utf8').trim().split(/\r?\n/)
54
+ assert.equal(lines.length, 1)
55
+ assert.equal(JSON.parse(lines[0]).code, 'ENGINE_MISSING')
56
+ assert.equal(fs.existsSync(path.join(home, 'logs', 'activity.jsonl')), false,
57
+ 'nothing may leak into the regular activity log')
58
+ })
59
+
60
+ test('filters by level and by free text, newest first', () => {
61
+ diag.recordDiagnostic({ level: 'error', scope: 'vector', code: 'E1', message: 'alpha failed' })
62
+ diag.recordDiagnostic({ level: 'info', scope: 'store', code: 'I1', message: 'beta repaired' })
63
+ assert.equal(diag.listDiagnostics({ level: 'error' }).total, 1)
64
+ assert.equal(diag.listDiagnostics({ q: 'beta' }).items[0].code, 'I1')
65
+ assert.equal(diag.listDiagnostics({ q: 'nothing-matches-this' }).total, 0)
66
+ assert.equal(diag.listDiagnostics({}).items[0].code, 'I1', 'newest first')
67
+ })
68
+
69
+ test('detail is captured for repair but secrets are redacted', () => {
70
+ diag.recordDiagnostic({
71
+ level: 'error',
72
+ scope: 'vector',
73
+ code: 'LOCAL_VECTOR_WORKER_EXITED',
74
+ message: 'worker exited',
75
+ detail: { stderrTail: 'OPENAI_API_KEY=sk-abcdefghijklmnopqrstuvwxyz 0123' },
76
+ })
77
+ const row = diag.listDiagnostics({}).items[0]
78
+ assert.match(row.detail.stderrTail, /^OPENAI_API_KEY=/)
79
+ assert.doesNotMatch(row.detail.stderrTail, /sk-abcdefghijklmnopqrstuvwxyz/)
80
+ })
81
+
82
+ // ---------------------------------------------------------------- 启动告警
83
+
84
+ test('alerts only carry unacknowledged error/warn rows and stop after acknowledgement', () => {
85
+ diag.recordDiagnostic({ level: 'info', scope: 'store', code: 'I1', message: 'just information' })
86
+ diag.recordDiagnostic({ level: 'error', scope: 'vector', code: 'E1', message: 'broken' })
87
+ const first = diag.diagnosticAlerts()
88
+ assert.deepEqual(first.alerts.map(alert => alert.code), ['E1'], 'info rows never raise a popup')
89
+ diag.acknowledgeDiagnostics({ codes: ['E1'] })
90
+ assert.equal(diag.diagnosticAlerts().alerts.length, 0, 'an acknowledged fault is not re-announced')
91
+ // 同一个故障再次出现:出现次数超过已确认次数,必须重新提醒一次。
92
+ diag.recordDiagnostic({ level: 'error', scope: 'vector', code: 'E1', message: 'broken' })
93
+ assert.deepEqual(diag.diagnosticAlerts().alerts.map(alert => alert.code), ['E1'])
94
+ })
95
+
96
+ // ---------------------------------------------------------------- 修复记账
97
+
98
+ test('repair outcomes are recorded either way, so a failed repair is still diagnosable', () => {
99
+ diag.recordRepair({ action: 'release-stale-locks', ok: true, detail: { released: 2 } })
100
+ diag.recordRepair({ action: 'reinstall-engine', ok: false, detail: { stage: 'download' } })
101
+ const rows = diag.listDiagnostics({}).items
102
+ const ok = rows.find(row => row.code === 'MEMU_DIAGNOSTIC_REPAIRED')
103
+ const failed = rows.find(row => row.code === 'MEMU_DIAGNOSTIC_REPAIR_FAILED')
104
+ assert.ok(ok, 'a successful repair is recorded')
105
+ assert.ok(failed, 'a failed repair is recorded too')
106
+ assert.equal(failed.level, 'error')
107
+ assert.equal(failed.detail.action, 'reinstall-engine')
108
+ assert.equal(failed.detail.stage, 'download')
109
+ })
110
+
111
+ test('clearDiagnostics empties the ring and the file', () => {
112
+ diag.recordDiagnostic({ level: 'error', scope: 'vector', code: 'E1', message: 'x' })
113
+ diag.clearDiagnostics()
114
+ assert.equal(diag.listDiagnostics({}).total, 0)
115
+ assert.equal(fs.existsSync(path.join(home, 'diagnostics', 'events.jsonl')), false,
116
+ 'clearing must not leave a file that is re-read on the next start')
117
+ })
118
+
119
+ // ---------------------------------------------------------------- 锁判据
120
+
121
+ const lockFile = (name, body, ageMs = 0) => {
122
+ const file = path.join(home, 'locks', name + '.lock')
123
+ fs.mkdirSync(path.dirname(file), { recursive: true })
124
+ fs.writeFileSync(file, body)
125
+ if (ageMs) {
126
+ const when = new Date(Date.now() - ageMs)
127
+ fs.utimesSync(file, when, when)
128
+ }
129
+ return file
130
+ }
131
+
132
+ test('an empty lock file is stale only after the grace window', () => {
133
+ const fresh = lockFile('fresh-empty', '')
134
+ assert.equal(paths.inspectLock(fresh), null, 'a lock being created right now is not stale')
135
+ const old = lockFile('old-empty', '', 30_000)
136
+ assert.equal(paths.inspectLock(old)?.reason, 'unparseable-owner')
137
+ })
138
+
139
+ test('a lock owned by a dead pid is stale immediately', () => {
140
+ // pid 2^22 以上在这两个平台都远超 pid_max,kill(pid, 0) 必然 ESRCH。
141
+ const dead = lockFile('dead', '4194303\n' + new Date().toISOString())
142
+ assert.equal(paths.inspectLock(dead)?.reason, 'dead-owner')
143
+ })
144
+
145
+ test('a live foreign owner keeps the lock, and a very old one ages out', () => {
146
+ const live = lockFile('live', `${process.ppid}\n` + new Date().toISOString())
147
+ assert.equal(paths.inspectLock(live), null, 'pid 1 exists; the lock must be respected')
148
+ const aged = lockFile('aged', `${process.ppid}\n` + new Date().toISOString(), 5 * 60_000)
149
+ assert.equal(paths.inspectLock(aged)?.reason, 'aged-out')
150
+ })
151
+
152
+ test('a lock naming our own pid without a held transaction waits for the grace window', () => {
153
+ const own = lockFile('own', String(process.pid))
154
+ assert.equal(paths.inspectLock(own), null, 'another copy of the plugin may hold it')
155
+ const old = lockFile('own-old', String(process.pid), 30_000)
156
+ assert.equal(paths.inspectLock(old)?.reason, 'own-pid-without-transaction')
157
+ })
158
+
159
+ test('releaseStaleLocks only removes the ones it can prove are abandoned', () => {
160
+ const abandoned = lockFile('abandoned', '', 30_000)
161
+ const healthy = lockFile('healthy', `${process.ppid}\n` + new Date().toISOString())
162
+ const report = paths.releaseStaleLocks()
163
+ // 同一份 home 里前面的用例也留了遗弃锁,所以只核对"这一个被清掉、健康的没被动"。
164
+ assert.ok(report.released.some(item => path.resolve(item.path) === path.resolve(abandoned)))
165
+ assert.equal(fs.existsSync(abandoned), false)
166
+ assert.equal(fs.existsSync(healthy), true)
167
+ })
168
+
169
+ test('breaking a stale lock reports an event so the diagnostics page can show it', () => {
170
+ const seen = []
171
+ paths.setLockEventSink(event => seen.push(event))
172
+ const lock = path.join(home, 'store.json.lock')
173
+ fs.writeFileSync(lock, '')
174
+ const when = new Date(Date.now() - 30_000)
175
+ fs.utimesSync(lock, when, when)
176
+ // withFileLock 会先发现遗弃锁、清掉、再正常执行。
177
+ const value = paths.withFileLock(path.join(home, 'store.json'), () => 'ok')
178
+ assert.equal(value, 'ok')
179
+ assert.equal(seen.length, 1)
180
+ assert.equal(seen[0].code, 'MEMU_LOCK_BROKEN')
181
+ assert.equal(seen[0].reason, 'unparseable-owner')
182
+ })
183
+
184
+ test('a live lock still fails the write instead of being broken', () => {
185
+ const target = path.join(home, 'busy.json')
186
+ const lock = target + '.lock'
187
+ fs.writeFileSync(lock, `${process.ppid}\n` + new Date().toISOString())
188
+ try {
189
+ assert.throws(() => paths.withFileLock(target, () => 'never'), /busy/i)
190
+ assert.ok(fs.existsSync(lock), 'a live lock must survive the failure')
191
+ } finally {
192
+ fs.rmSync(lock, { force: true })
193
+ }
194
+ })
195
+
196
+ // ---------------------------------------------------------------- 摘要兼容
197
+
198
+ test('all three digest algorithms are still accepted, so upgrades do not invalidate a profile', () => {
199
+ const manifest = {
200
+ id: 'm', dimension: 512, tokenizer: { vocab: 21128 },
201
+ runtime: { engine: 'onnxruntime-node', version: '1.31.1' },
202
+ files: [{ name: 'model.onnx', bytes: 10, sha256: 'c'.repeat(64) }],
203
+ }
204
+ const current = vp.manifestDigest(manifest)
205
+ const raw = vp.rawManifestDigest(manifest)
206
+ const legacy = vp.legacyManifestDigest(manifest)
207
+ assert.ok(vp.manifestDigestAccepted(current, manifest))
208
+ assert.ok(vp.manifestDigestAccepted(raw, manifest), '1.3.x digests stay valid')
209
+ assert.ok(vp.manifestDigestAccepted(legacy, manifest), 'pre-1.3 digests stay valid')
210
+ assert.equal(vp.manifestDigestAccepted('d'.repeat(64), manifest), false)
211
+ })
212
+
213
+ test('a mirror-only artifact change is metadata drift, not an identity change', () => {
214
+ const artifact = { name: 'onnxruntime-node', version: '1.31.1', bytes: 10, sha256: 'e'.repeat(64) }
215
+ const recorded = { id: 'm', dimension: 512, runtime: { engine: 'onnxruntime-node', artifacts: { 'win32-x64': artifact } } }
216
+ const current = {
217
+ id: 'm',
218
+ dimension: 512,
219
+ runtime: {
220
+ engine: 'onnxruntime-node',
221
+ artifacts: {
222
+ 'win32-x64': {
223
+ ...artifact,
224
+ sources: [{ id: 'npmjs', url: 'https://registry.npmjs.org' }, { id: 'npmmirror', label: '国内镜像' }],
225
+ },
226
+ },
227
+ },
228
+ }
229
+ const drift = vp.manifestDrift(recorded, current)
230
+ assert.deepEqual(drift.metadataOnly, ['runtime'])
231
+ assert.deepEqual(drift.identityChanged, [], 'mirror metadata must not force a rebuild')
232
+ assert.equal(vp.manifestDigest(recorded), vp.manifestDigest(current), 'the identity digest ignores mirrors')
233
+ })
234
+
235
+ test('a version or hash change inside an artifact is an identity change', () => {
236
+ const recorded = { id: 'm', runtime: { engine: 'onnxruntime-node', artifacts: { 'win32-x64': { version: '1.31.1', sha256: 'a'.repeat(64) } } } }
237
+ const current = { id: 'm', runtime: { engine: 'onnxruntime-node', artifacts: { 'win32-x64': { version: '1.32.0', sha256: 'a'.repeat(64) } } } }
238
+ assert.deepEqual(vp.manifestDrift(recorded, current).identityChanged, ['runtime'])
239
+ })
240
+
241
+ test('rows on disk survive a restart, so the page is not empty after a reload', () => {
242
+ // 这条守的是一个真实事故:读盘时无条件丢掉第一行,导致"落盘了但重启后永远看不见"。
243
+ diag.recordDiagnostic({ level: 'error', scope: 'vector', code: 'PERSISTED_ROW', message: 'survive me' })
244
+ const entry = pathToFileURL(path.resolve('lib/diagnostics.js')).href
245
+ const script = [
246
+ "const diag = await import(process.env.MEMU_CHECK_ENTRY)",
247
+ 'const list = diag.listDiagnostics({})',
248
+ 'console.log(JSON.stringify({ total: list.total, code: list.items[0] && list.items[0].code }))',
249
+ ].join('\n')
250
+ const out = execFileSync(process.execPath, ['--input-type=module', '-e', script], {
251
+ env: { ...process.env, DSH_MEMU_HOME: home, DSH_MEMU_MEMORY_HOME: home, MEMU_CHECK_ENTRY: entry },
252
+ encoding: 'utf8',
253
+ }).trim()
254
+ const parsed = JSON.parse(out.split('\n').pop())
255
+ assert.equal(parsed.total >= 1, true, 'a fresh process must read the persisted rows')
256
+ assert.equal(parsed.code, 'PERSISTED_ROW')
257
+ })
@@ -0,0 +1,159 @@
1
+ // 环境自检与修复动作的回归测试。
2
+ // 这套代码的价值全在"故障可见 + 修得动":检查项漏报等于故障继续静默,
3
+ // 修复动作乱进安全名单等于半夜动用户数据。所以两条都要钉住。
4
+ import test from 'node:test'
5
+ import assert from 'node:assert/strict'
6
+ import fs from 'node:fs'
7
+ import os from 'node:os'
8
+ import path from 'node:path'
9
+
10
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-envcheck-'))
11
+ process.env.DSH_MEMU_HOME = home
12
+ process.env.DSH_MEMU_MEMORY_HOME = home
13
+
14
+ const env = await import('../lib/environment-check.js')
15
+ const diag = await import('../lib/diagnostics.js')
16
+ const paths = await import('../lib/paths.js')
17
+
18
+ test.after(() => {
19
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
20
+ })
21
+
22
+ test.beforeEach(() => {
23
+ diag.clearDiagnostics()
24
+ paths.setLockEventSink(null)
25
+ paths.setWarnSink(null)
26
+ // 上一个用例留下的锁文件会被"整个数据目录"的扫描看见,先清干净再断言。
27
+ try { fs.rmSync(path.join(home, 'locks'), { recursive: true, force: true }) } catch {}
28
+ })
29
+
30
+ function lockFile(name, payload, ageMs = 0) {
31
+ const dir = path.join(home, 'locks')
32
+ fs.mkdirSync(dir, { recursive: true })
33
+ const file = path.join(dir, `${name}.lock`)
34
+ fs.writeFileSync(file, payload)
35
+ if (ageMs) {
36
+ const when = new Date(Date.now() - ageMs)
37
+ fs.utimesSync(file, when, when)
38
+ }
39
+ return file
40
+ }
41
+
42
+ // ---------------------------------------------------------------- 检查项
43
+
44
+ test('every item carries the shape the diagnostics page renders', () => {
45
+ const report = env.runEnvironmentCheck()
46
+ assert.ok(Array.isArray(report.items) && report.items.length > 0, 'a check must produce items')
47
+ for (const entry of report.items) {
48
+ assert.ok(entry.id, 'item without id')
49
+ assert.ok(typeof entry.title === 'string' && entry.title.length > 0, `${entry.id} has no title`)
50
+ assert.ok(['ok', 'warn', 'error', 'skipped'].includes(entry.level), `${entry.id} has level ${entry.level}`)
51
+ assert.equal(typeof entry.ok, 'boolean')
52
+ }
53
+ assert.equal(typeof report.ok, 'boolean')
54
+ assert.equal(typeof report.checkedAt, 'string')
55
+ assert.ok(report.counts && typeof report.counts.ok === 'number')
56
+ })
57
+
58
+ test('a writable data dir is reported ok, so the check itself is not the alarm', () => {
59
+ const report = env.runEnvironmentCheck()
60
+ const dataDir = report.items.find(entry => entry.id === 'data-dir')
61
+ assert.ok(dataDir, 'data-dir must always be checked first')
62
+ assert.equal(dataDir.ok, true)
63
+ })
64
+
65
+ test('an abandoned lock is reported with the repair that clears it', () => {
66
+ lockFile('abandoned', '', 30_000)
67
+ const report = env.runEnvironmentCheck()
68
+ const locks = report.items.find(entry => entry.id === 'locks')
69
+ assert.ok(locks, 'locks must be checked')
70
+ assert.equal(locks.ok, false)
71
+ assert.equal(locks.level, 'warn')
72
+ assert.equal(locks.repair, 'release-stale-locks')
73
+ assert.equal(locks.auto, true, 'clearing provably abandoned locks is safe enough to run at startup')
74
+ assert.match(locks.detail, /abandoned\.lock/)
75
+ assert.ok(report.repairs.includes('release-stale-locks'))
76
+ })
77
+
78
+ test('a healthy live lock is not reported as a problem', () => {
79
+ lockFile('live', `${process.ppid}\n` + new Date().toISOString())
80
+ const report = env.runEnvironmentCheck()
81
+ const locks = report.items.find(entry => entry.id === 'locks')
82
+ assert.ok(locks)
83
+ assert.equal(locks.ok, true)
84
+ })
85
+
86
+ // ---------------------------------------------------------------- 修复门禁
87
+
88
+ test('repairEnvironment refuses to run without an explicit confirmation', async () => {
89
+ await assert.rejects(
90
+ () => env.repairEnvironment({ actions: ['release-stale-locks'] }),
91
+ /confirmed === true/,
92
+ )
93
+ })
94
+
95
+ test('a repair that runs is recorded, and the report reflects the new state', async () => {
96
+ const abandoned = lockFile('abandoned', '', 30_000)
97
+ const outcome = await env.repairEnvironment({ actions: ['release-stale-locks'], confirmed: true })
98
+ assert.equal(outcome.ok, true)
99
+ assert.equal(outcome.results.length, 1)
100
+ assert.equal(fs.existsSync(abandoned), false, 'the repair must actually remove the lock')
101
+ const repaired = diag.listDiagnostics({}).items.find(row => row.code === 'MEMU_DIAGNOSTIC_REPAIRED')
102
+ assert.ok(repaired, 'a successful repair is recorded in diagnostics')
103
+ assert.equal(repaired.detail.action, 'release-stale-locks')
104
+ const locks = outcome.after.items.find(entry => entry.id === 'locks')
105
+ assert.equal(locks.ok, true, 'the post-repair check must show the fix')
106
+ })
107
+
108
+ test('a repair that fails is still recorded, with the error', async () => {
109
+ const outcome = await env.repairEnvironment({ actions: ['not-a-real-action'], confirmed: true })
110
+ assert.equal(outcome.ok, false)
111
+ assert.equal(outcome.results[0].ok, false)
112
+ assert.match(outcome.results[0].detail, /unknown repair action/)
113
+ const failed = diag.listDiagnostics({}).items.find(row => row.code === 'MEMU_DIAGNOSTIC_REPAIR_FAILED')
114
+ assert.ok(failed, 'a failed repair must not disappear')
115
+ assert.equal(failed.level, 'error')
116
+ assert.equal(failed.detail.action, 'not-a-real-action')
117
+ })
118
+
119
+ test('startup auto-repair only touches the safe list', async () => {
120
+ assert.deepEqual([...env.SAFE_REPAIRS].sort(), ['release-stale-locks', 'repoint-runtime-dir', 'resign-vector-profile'])
121
+ for (const action of env.MANUAL_REPAIRS) {
122
+ assert.ok(!env.SAFE_REPAIRS.includes(action), `${action} must never run automatically`)
123
+ }
124
+ const blocked = await env.autoRepairEnvironment({ actions: ['reinstall-engine'] })
125
+ assert.equal(blocked.changed, false)
126
+ assert.deepEqual(blocked.results, [], 'a manual action asked for by mistake must be ignored, not run')
127
+ })
128
+
129
+ test('every repair action has a label, so the page never shows a bare slug', () => {
130
+ for (const action of [...env.SAFE_REPAIRS, ...env.MANUAL_REPAIRS]) {
131
+ assert.ok(env.REPAIR_LABELS[action], `${action} has no label`)
132
+ }
133
+ })
134
+
135
+ // ---------------------------------------------------------------- 运行时目录发现
136
+
137
+ test('the managed runtime root is discovered where the service actually installs it', async () => {
138
+ // 真实布局是 downloads/embeddings/runtime/<key>(与模型同级)。早先这里只看
139
+ // downloads/runtime,于是"运行时明明装着"也会报"没有安装",把用户推去重下 40MB。
140
+ const vp = await import('../lib/vector-profile.js')
141
+ const managed = path.join(home, 'downloads', 'embeddings', 'runtime', 'onnxruntime-node@test@napi-v6@win32-x64-abc')
142
+ const legacy = path.join(home, 'downloads', 'runtime', 'onnxruntime-node@test@napi-v6@win32-x64-def')
143
+ for (const dir of [managed, legacy]) {
144
+ fs.mkdirSync(path.join(dir, 'node_modules', 'onnxruntime-node'), { recursive: true })
145
+ fs.writeFileSync(path.join(dir, 'node_modules', 'onnxruntime-node', 'package.json'), '{"name":"onnxruntime-node"}')
146
+ }
147
+ const candidates = vp.runtimeDirCandidates().map(entry => path.resolve(entry.dir))
148
+ assert.ok(candidates.includes(path.resolve(managed)), 'the managed root must be scanned')
149
+ assert.ok(candidates.includes(path.resolve(legacy)), 'the legacy root keeps working')
150
+ })
151
+
152
+ test('a runtime directory without its package.json is not offered as a candidate', async () => {
153
+ // 真实事故:运行时目录只剩 bin/,package.json 与 lib/ 都没了 → 重指过去仍然 MODULE_NOT_FOUND。
154
+ const vp = await import('../lib/vector-profile.js')
155
+ const hollow = path.join(home, 'downloads', 'embeddings', 'runtime', 'hollow-key')
156
+ fs.mkdirSync(path.join(hollow, 'node_modules', 'onnxruntime-node', 'bin'), { recursive: true })
157
+ const candidates = vp.runtimeDirCandidates().map(entry => path.resolve(entry.dir))
158
+ assert.ok(!candidates.includes(path.resolve(hollow)))
159
+ })
@@ -41,13 +41,13 @@ test('disconnected 200-node layout stays finite, separated and framed without bo
41
41
  layout.dispose()
42
42
  })
43
43
 
44
- test('invalid/self edges are ignored, input bounded, node order deterministic', () => {
44
+ test('invalid/self edges are ignored, all unique nodes retained, node order deterministic', () => {
45
45
  const data = graph(250, false)
46
46
  data.edges.push({ from: 'missing', to: 'n000' }, { from: 'n000', to: 'n000' })
47
47
  const a = createForceLayout(), b = createForceLayout()
48
48
  a.update(data)
49
- b.update({ nodes: [...data.nodes.slice(0, 200)].reverse(), edges: [] })
50
- assert.equal(a.nodes.length, 200); assert.equal(a.edges.length, 0)
49
+ b.update({ nodes: [...data.nodes, data.nodes[0]].reverse(), edges: [] })
50
+ assert.equal(a.nodes.length, 250); assert.equal(b.nodes.length, 250); assert.equal(a.edges.length, 0)
51
51
  a.settle(); b.settle()
52
52
  assert.deepEqual(a.nodes.map(n => [n.id, n.x, n.y]), b.nodes.map(n => [n.id, n.x, n.y]),
53
53
  'the jitter must be deterministic, never Math.random')
@@ -226,6 +226,30 @@ function harness(reducedMotion = true) {
226
226
  return { view, flush, emit, arcs, texts, frames, focuses, handlers, windowHandlers, getPaints: () => paints }
227
227
  }
228
228
 
229
+ test('view snapshots retain multiple clusters and entities beyond the first 200 nodes', () => {
230
+ const data = graph(250, false)
231
+ for (let i = 0; i < 249; i++) {
232
+ if (i !== 119) data.edges.push({ from: data.nodes[i].id, to: data.nodes[i + 1].id })
233
+ }
234
+ for (const [id, from] of [['ent-first', 'n119'], ['ent-last', 'n249']]) {
235
+ data.nodes.push({ id, title: id, kind: 'person', strength: .5 })
236
+ data.edges.push({ from, to: id })
237
+ }
238
+ const h = harness()
239
+ h.view.update(data); h.flush()
240
+ const snapshot = h.view.snapshot()
241
+ assert.equal(snapshot.length, 252)
242
+ assert.deepEqual(new Set(snapshot.map(node => node.id)), new Set(data.nodes.map(node => node.id)))
243
+ for (const id of ['ent-first', 'ent-last']) {
244
+ const entity = snapshot.find(node => node.id === id)
245
+ assert.equal(entity.degree, 1, 'late entity links must survive canvas ingestion')
246
+ assert.ok(Number.isFinite(entity.x) && Number.isFinite(entity.y))
247
+ }
248
+ h.view.update({ nodes: [...data.nodes, data.nodes[0]].reverse(), edges: [...data.edges].reverse() }); h.flush()
249
+ assert.deepEqual(h.view.snapshot(), snapshot, 'equivalent refreshed input preserves every node and its position')
250
+ h.view.dispose()
251
+ })
252
+
229
253
  test('the detailed layer actually paints labels and the label switch silences them', () => {
230
254
  const h = harness()
231
255
  h.view.update(graph(10)); h.flush()
@@ -383,4 +407,8 @@ test('shipped browser bundle exposes the controller with no runtime npm imports'
383
407
  assert.equal(typeof api.placeLabels, 'function')
384
408
  assert.equal(api.DEFAULT_OPTIONS.center, 0)
385
409
  assert.equal(api.DEFAULT_OPTIONS.clusterScope, true)
410
+ const layout = api.createForceLayout()
411
+ layout.update(graph(251, false))
412
+ assert.equal(layout.nodes.length, 251, 'the shipped browser bundle must retain nodes beyond 200')
413
+ layout.dispose()
386
414
  })