dsh-memu-memory 1.3.12 → 1.3.14

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 的全屏画布写的,宿主设置页只需要普通横排导航 + 一个入口按钮。
@@ -408,4 +408,161 @@ test('only the host saying the conversation is gone counts as deleted', () => {
408
408
  assert.equal(cycle.isGoneSessionError('this session does not exist any more'), true)
409
409
  assert.equal(cycle.isGoneSessionError("ENOENT: no such file or directory, open 'D:/x/log.jsonl'"), false)
410
410
  assert.equal(cycle.isGoneSessionError('EACCES: permission denied, open D:/x'), false)
411
- })
411
+ })
412
+ // ---------------------------------------------------------------- 归档 vs 在用(2026-11-21 外部报告)
413
+
414
+ // 报告里的真实形态:IM 插件数据目录不是 DSH 工作区,库建好后 176 秒被扫描归档,
415
+ // 而绑定会话继续写 9 小时。这里把那条时间线压成三轮 sweep。
416
+
417
+ test('a library bound to a live conversation is never archived for an unregistered scope', () => {
418
+ const cwd = path.join(home, 'im-in-use')
419
+ state.ensureSession('cycle-im', { cwd })
420
+ const binding = state.getSessionBinding('cycle-im')
421
+ const libId = binding.libraryId
422
+ assert.ok(libId, 'the session created a library')
423
+
424
+ const first = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
425
+ assert.ok(!first.archived.includes(libId), 'an in-use library must not be archived')
426
+ assert.ok(first.skippedInUse.includes(libId), 'the sweep must report why it skipped')
427
+ assert.ok(state.listLibraries().some((lib) => lib.id === libId), 'it stays in the active list')
428
+
429
+ // 连续三轮(≈15 分钟的真实节奏)都不能翻车。
430
+ const second = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
431
+ const third = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
432
+ for (const pass of [second, third]) assert.ok(!pass.archived.includes(libId))
433
+ const lib = state.getLibrary(libId)
434
+ assert.equal(lib.archived, undefined, 'never archived')
435
+ assert.equal(lib.archivedAt, undefined)
436
+ })
437
+
438
+ test('an unbound library with an unregistered scope still archives (the cleanup keeps working)', () => {
439
+ const lib = state.createLibrary({ name: 'cycle-unused', cwd: '/work/cycle-unused' })
440
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
441
+ assert.ok(pass.archived.includes(lib.id), 'nobody uses it, so the old behaviour stands')
442
+ assert.equal(state.getLibrary(lib.id).archivedBy, 'sweep', 'the sweep records that it did the archiving')
443
+ })
444
+
445
+ test('a library the old sweep archived while in use comes back instead of staying hidden', () => {
446
+ const cwd = path.join(home, 'im-misarchived')
447
+ state.ensureSession('cycle-im-revive', { cwd })
448
+ const libId = state.getSessionBinding('cycle-im-revive').libraryId
449
+ // 复现旧版:扫描把在用的库归档,且当时还没有 archivedBy 字段。
450
+ state.archiveLibrary(libId, { by: 'sweep' })
451
+ assert.ok(state.listArchivedLibraries().some((lib) => lib.id === libId))
452
+
453
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
454
+ assert.ok(pass.revived.includes(libId), 'an in-use archive is a bug and must self-heal')
455
+ assert.ok(state.listLibraries().some((lib) => lib.id === libId))
456
+ assert.ok(!pass.archived.includes(libId), 'and it must not be archived again in the same pass')
457
+ })
458
+
459
+ test('a user-archived library is respected even while a conversation still points at it', () => {
460
+ const cwd = path.join(home, 'im-user-archived')
461
+ state.ensureSession('cycle-user-archive', { cwd })
462
+ const libId = state.getSessionBinding('cycle-user-archive').libraryId
463
+ state.archiveLibrary(libId) // 默认 by: 'user'
464
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
465
+ assert.ok(!pass.revived.includes(libId), 'the sweep must not undo a deliberate archive')
466
+ assert.ok(state.listArchivedLibraries().some((lib) => lib.id === libId))
467
+ })
468
+
469
+ test('purging never proposes an archived library that is still in use', () => {
470
+ const cwd = path.join(home, 'im-purge')
471
+ state.ensureSession('cycle-purge', { cwd })
472
+ const libId = state.getSessionBinding('cycle-purge').libraryId
473
+ state.archiveLibrary(libId)
474
+ const st = state.loadState()
475
+ st.libraries[libId].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
476
+ state.saveState(st)
477
+ state.updateSettings({ purgeArchivedAfterDays: 30 })
478
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
479
+ assert.ok(!pass.purgeCandidates.includes(libId), 'age alone must not queue a live library for deletion')
480
+ })
481
+
482
+ test('deleting a library the sweep archived while still in use is refused', () => {
483
+ const cwd = path.join(home, 'im-delete')
484
+ state.ensureSession('cycle-delete', { cwd })
485
+ const libId = state.getSessionBinding('cycle-delete').libraryId
486
+ // 危险类:旧版扫描归档的库(archivedBy='sweep')仍在被会话使用,一次误点就会删掉全部记忆。
487
+ state.archiveLibrary(libId, { by: 'sweep' })
488
+ const refused = state.deleteLibrary(libId)
489
+ assert.equal(refused.ok, false)
490
+ assert.match(refused.error, /still uses it|live conversations/)
491
+ assert.ok(state.getLibrary(libId), 'the refusal leaves the data alone')
492
+
493
+ // 解绑之后不再是「在用」,同一个调用就放行——这正是正常删除流程。
494
+ state.deleteSessionBinding('cycle-delete')
495
+ const allowed = state.deleteLibrary(libId)
496
+ assert.equal(allowed.ok, true, allowed.error || '')
497
+ assert.equal(state.getLibrary(libId), null)
498
+ })
499
+
500
+ test('a user-archived library can still be deleted while a conversation points at it', () => {
501
+ const cwd = path.join(home, 'im-user-delete')
502
+ state.ensureSession('cycle-user-delete', { cwd })
503
+ const libId = state.getSessionBinding('cycle-user-delete').libraryId
504
+ state.archiveLibrary(libId) // by: 'user'
505
+ const result = state.deleteLibrary(libId)
506
+ assert.equal(result.ok, true, result.error || 'the user asked for this; the bindings go with it')
507
+ assert.equal(state.getLibrary(libId), null)
508
+ })
509
+
510
+ test('a session arriving at an archived library revives it through the fast path', () => {
511
+ const cwd = path.join(home, 'im-fastpath')
512
+ state.ensureSession('cycle-fastpath', { cwd })
513
+ const libId = state.getSessionBinding('cycle-fastpath').libraryId
514
+ state.archiveLibrary(libId, { by: 'sweep' })
515
+ // 快路径 = 已绑定会话再来一轮。旧版只刷新 lastUsedAt,库永远停在归档。
516
+ const again = state.ensureSession('cycle-fastpath', { cwd })
517
+ assert.equal(again.libraryId, libId, 'the binding is unchanged')
518
+ const lib = state.getLibrary(libId)
519
+ assert.notEqual(lib.archived, true, 'an in-use library must not stay archived')
520
+ assert.ok(lib.revivedAt)
521
+ })
522
+
523
+ test('a legacy archive with no recorded source is not revived just because an old binding exists', () => {
524
+ // 本机实测:rp(14 个绑定)、ai中转站(4 个)都是「归档 + 还有旧绑定」,但 lastUsed 三周前。
525
+ // 旧数据分不清是用户归档还是老扫描误归档,所以只复活「还热」的;冷的不动。
526
+ const lib = state.createLibrary({ name: 'legacy-cold', cwd: path.join(home, 'legacy-cold') })
527
+ const st = state.loadState()
528
+ st.libraries[lib.id].archived = true
529
+ st.libraries[lib.id].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
530
+ st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 30 * 86_400_000).toISOString()
531
+ delete st.libraries[lib.id].archivedBy
532
+ st.sessions['cycle-legacy'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-cold') }
533
+ state.saveState(st)
534
+
535
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
536
+ assert.ok(!pass.revived.includes(lib.id), 'a cold legacy archive stays archived')
537
+ assert.ok(state.listArchivedLibraries().some((row) => row.id === lib.id))
538
+ })
539
+
540
+ test('a warm legacy archive (no source recorded, used minutes ago) is revived', () => {
541
+ const lib = state.createLibrary({ name: 'legacy-warm', cwd: path.join(home, 'legacy-warm') })
542
+ const st = state.loadState()
543
+ st.libraries[lib.id].archived = true
544
+ st.libraries[lib.id].archivedAt = new Date(Date.now() - 60_000).toISOString()
545
+ st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 60_000).toISOString()
546
+ delete st.libraries[lib.id].archivedBy
547
+ st.sessions['cycle-warm'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-warm') }
548
+ state.saveState(st)
549
+
550
+ const pass = cycle.runLibraryHousekeeping(registryCtx(['/work/unrelated']))
551
+ assert.ok(pass.revived.includes(lib.id), 'a library still being written minutes ago must not stay hidden')
552
+ assert.ok(state.listLibraries().some((row) => row.id === lib.id))
553
+ })
554
+
555
+ test('a cold legacy archive with an old binding can still be deleted', () => {
556
+ // 本机 rp / ai中转站 形态:很久以前归档、仍留着旧绑定、lastUsed 三周前。
557
+ // 它不是扫描误归档(那类会被自愈),也不该因为“有旧绑定”变成永远删不掉。
558
+ const lib = state.createLibrary({ name: 'legacy-deletable', cwd: path.join(home, 'legacy-deletable') })
559
+ const st = state.loadState()
560
+ st.libraries[lib.id].archived = true
561
+ st.libraries[lib.id].archivedAt = new Date(Date.now() - 40 * 86_400_000).toISOString()
562
+ st.libraries[lib.id].lastUsedAt = new Date(Date.now() - 30 * 86_400_000).toISOString()
563
+ delete st.libraries[lib.id].archivedBy
564
+ st.sessions['cycle-legacy-del'] = { libraryId: lib.id, scopeKey: path.join(home, 'legacy-deletable') }
565
+ state.saveState(st)
566
+ const result = state.deleteLibrary(lib.id)
567
+ assert.equal(result.ok, true, result.error || '')
568
+ })
@@ -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
+ })