dsh-memu-memory 1.4.4 → 1.4.5

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 (180) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +11 -0
  3. package/README.md +33 -14
  4. package/README.zh.md +34 -12
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/libraries.jpg +0 -0
  7. package/assets/screenshots/mobile.jpg +0 -0
  8. package/assets/screenshots/relations.jpg +0 -0
  9. package/assets/screenshots/settings.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +19 -3
  13. package/docs/contributing.md +4 -2
  14. package/docs/env-and-commands.md +9 -1
  15. package/docs/graph-scale.md +214 -0
  16. package/docs/lexicon-recall.md +100 -0
  17. package/docs/mcp-porting.md +8 -6
  18. package/docs/memory-semantics.md +35 -3
  19. package/docs/pending-work.md +3 -1
  20. package/docs/retention.md +83 -0
  21. package/docs/rt-index.md +452 -0
  22. package/docs/scale-performance.md +101 -0
  23. package/docs/token-budget.md +92 -0
  24. package/docs/troubleshooting.md +50 -11
  25. package/lib/auto-link/apply.js +7 -2
  26. package/lib/auto-link/candidates.js +32 -10
  27. package/lib/backup.js +67 -32
  28. package/lib/binding-diagnostics.js +1 -1
  29. package/lib/bounded-cache.js +80 -0
  30. package/lib/client.js +2096 -409
  31. package/lib/consolidation-ledger.js +21 -4
  32. package/lib/consolidation-worker.js +14 -1
  33. package/lib/cycle.js +16 -11
  34. package/lib/diagnostic-context.js +372 -0
  35. package/lib/diagnostics.js +147 -61
  36. package/lib/embedding-download.js +7 -8
  37. package/lib/engine-sources.js +286 -0
  38. package/lib/engine.js +23 -10
  39. package/lib/entity-repair.js +43 -13
  40. package/lib/entity-review.js +64 -0
  41. package/lib/environment-check.js +348 -36
  42. package/lib/feedback.js +25 -0
  43. package/lib/global-graph.js +46 -2
  44. package/lib/graph-adjacency-index.js +525 -0
  45. package/lib/graph-overview.js +293 -0
  46. package/lib/graph.js +658 -105
  47. package/lib/inbound.js +44 -15
  48. package/lib/index-pages.js +57 -0
  49. package/lib/index.js +44 -6
  50. package/lib/inject.js +119 -50
  51. package/lib/lexicon-rt-source.js +25 -0
  52. package/lib/lexicon-rt-worker.js +26 -0
  53. package/lib/lexicon-rt.js +224 -0
  54. package/lib/lexicon-scope.js +56 -5
  55. package/lib/lexicon.js +143 -54
  56. package/lib/local-vector-service.js +3 -0
  57. package/lib/maintenance-ledger.js +542 -12
  58. package/lib/managed-runtime.js +260 -80
  59. package/lib/media.js +1 -1
  60. package/lib/memory.js +564 -131
  61. package/lib/port-surface.js +96 -11
  62. package/lib/private.js +47 -21
  63. package/lib/recall-cache.js +20 -34
  64. package/lib/retention.js +173 -0
  65. package/lib/rpc.js +135 -52
  66. package/lib/rt-index/builder.js +209 -0
  67. package/lib/rt-index/format.js +231 -0
  68. package/lib/rt-index/manifest.js +105 -0
  69. package/lib/rt-index/reader.js +673 -0
  70. package/lib/rt-index-retention.js +151 -0
  71. package/lib/rt-index-service.js +283 -0
  72. package/lib/rt-index-worker.js +21 -0
  73. package/lib/salient-wake.js +55 -4
  74. package/lib/state.js +195 -24
  75. package/lib/temporal.js +39 -13
  76. package/lib/token-measurement.js +126 -0
  77. package/lib/tools.js +101 -6
  78. package/lib/turn-log.js +108 -3
  79. package/lib/webui/graph-layout-worker.js +68 -0
  80. package/lib/webui/graph-local-physics.js +390 -0
  81. package/lib/webui/graph-spatial-grid.js +64 -0
  82. package/lib/webui/graph-view.bundle.js +6 -1
  83. package/lib/webui/graph-view.js +478 -135
  84. package/lib/webui/graph-webgl-renderer.js +74 -0
  85. package/lib/webui/standalone.js +1 -1
  86. package/lib/worker-pool.js +30 -4
  87. package/package.json +3 -2
  88. package/scripts/acceptance-local.mjs +4 -10
  89. package/scripts/bench-all-libraries.mjs +47 -0
  90. package/scripts/check-classic-graph-browser.mjs +189 -0
  91. package/scripts/check-client-browser.mjs +929 -0
  92. package/scripts/check-graph-browser.mjs +6 -0
  93. package/scripts/check-graph-elastic-browser.mjs +139 -0
  94. package/scripts/check-memory-review-browser.mjs +124 -0
  95. package/scripts/entity-dedupe.mjs +19 -3
  96. package/scripts/graph-artifact-provenance.mjs +30 -0
  97. package/scripts/graph-freeze-manifest.mjs +129 -0
  98. package/scripts/graph-geometry-fixture.mjs +40 -0
  99. package/scripts/graph-physics-bench.mjs +218 -0
  100. package/scripts/graph-scale-bench.mjs +213 -0
  101. package/scripts/graph-scale-memory.mjs +48 -0
  102. package/scripts/graph-service-bench.mjs +72 -0
  103. package/scripts/make-readme-shots.mjs +17 -5
  104. package/scripts/preview.mjs +1 -0
  105. package/scripts/rebuild-rt.mjs +18 -0
  106. package/scripts/scale-bench.mjs +183 -0
  107. package/scripts/simulate-injection.mjs +47 -8
  108. package/scripts/verify-host-fixtures.mjs +108 -0
  109. package/scripts/verify-host-recovery.mjs +565 -0
  110. package/scripts/verify-vector-recovery.mjs +740 -0
  111. package/tests/auto-link-candidates.test.mjs +20 -0
  112. package/tests/browser.test.mjs +16 -2
  113. package/tests/client-export.test.mjs +16 -1
  114. package/tests/client-pagination.test.mjs +1495 -0
  115. package/tests/client-render.test.mjs +223 -28
  116. package/tests/consolidation-fork.test.mjs +93 -10
  117. package/tests/consolidation-ledger.test.mjs +17 -1
  118. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  119. package/tests/diagnostic-report.test.mjs +429 -0
  120. package/tests/diagnostic-wiring.test.mjs +88 -0
  121. package/tests/diagnostics.test.mjs +27 -0
  122. package/tests/embedding-download.test.mjs +44 -0
  123. package/tests/engine-source-settings.test.mjs +69 -0
  124. package/tests/engine-sources.test.mjs +145 -0
  125. package/tests/entity-dedupe.test.mjs +143 -0
  126. package/tests/entity-merge-review.test.mjs +363 -0
  127. package/tests/entity-merge.test.mjs +12 -4
  128. package/tests/entity-review.test.mjs +87 -0
  129. package/tests/environment-check.test.mjs +51 -1
  130. package/tests/feedback.test.mjs +95 -0
  131. package/tests/graph-adjacency-index.test.mjs +536 -0
  132. package/tests/graph-cascade.test.mjs +229 -0
  133. package/tests/graph-import-diagnostic.test.mjs +25 -0
  134. package/tests/graph-overview.test.mjs +709 -0
  135. package/tests/graph-session-authorization.test.mjs +419 -0
  136. package/tests/graph-view-geometry.test.mjs +426 -0
  137. package/tests/graph-view-scale.test.mjs +88 -0
  138. package/tests/graph-view.test.mjs +444 -5
  139. package/tests/graph.test.mjs +43 -0
  140. package/tests/help-page.test.mjs +128 -54
  141. package/tests/inbound.test.mjs +19 -0
  142. package/tests/index-pagination.test.mjs +113 -0
  143. package/tests/index-read-view.test.mjs +212 -0
  144. package/tests/inject-guide.test.mjs +9 -0
  145. package/tests/injection-dedupe.test.mjs +213 -0
  146. package/tests/lexicon-recall.test.mjs +641 -0
  147. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  148. package/tests/lexicon-rt.test.mjs +468 -0
  149. package/tests/local-embedding-worker.test.mjs +38 -0
  150. package/tests/local-vector-service.test.mjs +32 -3
  151. package/tests/maintenance-compat.test.mjs +128 -0
  152. package/tests/maintenance-settlement.test.mjs +1003 -0
  153. package/tests/managed-memory.test.mjs +39 -11
  154. package/tests/managed-runtime.test.mjs +109 -0
  155. package/tests/memory-fields.test.mjs +24 -12
  156. package/tests/observed-evidence.test.mjs +52 -0
  157. package/tests/port-surface.test.mjs +93 -1
  158. package/tests/recall-cache.test.mjs +56 -3
  159. package/tests/recall-dedup.test.mjs +63 -2
  160. package/tests/retention.test.mjs +260 -0
  161. package/tests/rt-index-cross-library.test.mjs +230 -0
  162. package/tests/rt-index-integration.test.mjs +194 -0
  163. package/tests/rt-index-retention.test.mjs +552 -0
  164. package/tests/rt-index-scale.test.mjs +204 -0
  165. package/tests/rt-index.test.mjs +705 -0
  166. package/tests/salient-date-boundaries.test.mjs +121 -0
  167. package/tests/salient-wake.test.mjs +29 -0
  168. package/tests/scale-bench.test.mjs +53 -0
  169. package/tests/settings-plumbing.test.mjs +25 -0
  170. package/tests/simulate-injection.test.mjs +15 -1
  171. package/tests/standalone-navigation.test.mjs +44 -0
  172. package/tests/state.test.mjs +51 -0
  173. package/tests/temporal-precision.test.mjs +102 -0
  174. package/tests/temporal.test.mjs +10 -6
  175. package/tests/token-measurement.test.mjs +98 -0
  176. package/tests/tool-schema.test.mjs +41 -5
  177. package/tests/tools.test.mjs +6 -3
  178. package/tests/turn-token-budget.test.mjs +149 -0
  179. package/tests/webui-auth.test.mjs +57 -1
  180. package/tests/webui.test.mjs +40 -15
@@ -7,6 +7,8 @@
7
7
  import test from 'node:test'
8
8
  import assert from 'node:assert/strict'
9
9
  import fs from 'node:fs'
10
+ import path from 'node:path'
11
+ import { buildGraphOverview, selectGraphOverview } from '../lib/graph-overview.js'
10
12
 
11
13
  const registrations = []
12
14
 
@@ -231,6 +233,16 @@ test('the settings page renders every page instead of a blank panel', async () =
231
233
  }
232
234
  })
233
235
 
236
+ test('entity reviews live on MemU memories, not diagnostics, and graph entry stays available', () => {
237
+ const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
238
+ const memories = src.slice(src.indexOf('const memoriesBlock ='), src.indexOf('const graphBlock ='))
239
+ const graph = src.slice(src.indexOf('const graphBlock ='), src.indexOf('const lexiconBlock ='))
240
+ const diagnostics = src.slice(src.indexOf('const diagRuntimeSection ='), src.indexOf('const pageBlocks ='))
241
+ assert.match(memories, /EntityMergeReviewPanel/)
242
+ assert.doesNotMatch(diagnostics, /diagMerge|entityMergeCandidates|data-entity-merge-candidate/)
243
+ assert.match(graph, /openGraphStudio/)
244
+ })
245
+
234
246
  async function graphStudioHarness(call, libraries) {
235
247
  const ctx = fakeCtx()
236
248
  globalThis.__dshMemuExports.apply(ctx)
@@ -288,6 +300,7 @@ test('graph studio pages all libraries and filters custom domains without mergin
288
300
  id: i ? 'mem-' + i : 'mem-shared', title: payload.libraryId + '-memory-' + i, kind: 'memory', domain,
289
301
  }))
290
302
  const nodes = payload.domain && payload.domain !== domain ? [] : [...memories, { id: 'ent-shared', title: payload.libraryId + '-person', kind: 'person' }]
303
+ if (Object.hasOwn(payload, 'includeOrphans')) return selectGraphOverview(buildGraphOverview({ nodes, edges: [] }, { revision: 'r1' }), payload)
291
304
  const offset = payload.offset || 0, next = offset + 200
292
305
  return { nodes: nodes.slice(offset, next), edges: !offset && nodes.length ? [{ from: 'mem-shared', to: 'ent-shared', kind: 'person' }] : [],
293
306
  nextOffset: next < nodes.length ? next : null, domains: ['coding', 'project:travel'] }
@@ -313,7 +326,11 @@ test('graph studio pages all libraries and filters custom domains without mergin
313
326
  tree = await view.render(true)
314
327
  assert.equal(canvas().nodes.length, 2, 'equivalent domain input must not clear the graph')
315
328
  view.pick(tree, node => node.type === 'button' && node.props.children === 'gsManage')[0].props.onClick()
316
- tree = await view.render()
329
+ tree = await view.render(true)
330
+ assert.equal(view.pick(tree, node => String(node.props?.className || '').split(' ').includes('dshm-gs-mgr-row')).length, 2,
331
+ 'merged management opens all libraries with the same domain filter')
332
+ view.pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'gsManagerScope')[0].props.onChange({ target: { value: 'lib-b' } })
333
+ tree = await view.render(true)
317
334
  const rows = view.pick(tree, node => String(node.props?.className || '').split(' ').includes('dshm-gs-mgr-row'))
318
335
  assert.equal(rows.length, 2, 'management uses the same domain filter')
319
336
  rows.find(row => treeText(row).includes('lib-b-memory-0')).props.onClick()
@@ -503,6 +520,43 @@ test('the sidebar tab renders with the two-layer header', async () => {
503
520
  assert.match(text, /dmCoding/, 'domain picker did not render its options')
504
521
  })
505
522
 
523
+ test('sidebar folder labels and tooltips omit full paths on either platform', async () => {
524
+ const scopes = ['C:\\Users\\PortOwner\\private\\ProjectLeaf', 'c:/users/PORTOWNER/private/ProjectLeaf', '/home/PortOwner/private/ProjectLeaf', '\\\\server\\PortOwner\\private\\ProjectLeaf']
525
+ for (const scopeKey of scopes) {
526
+ const answer = structuredClone(RPC_ANSWERS.getSidebarState)
527
+ answer.binding.scopeKey = scopeKey
528
+ answer.folder.scopeKey = scopeKey
529
+ answer.effective.folder.scopeKey = scopeKey
530
+ const ctx = fakeCtx({ answers: { getSidebarState: answer } })
531
+ globalThis.__dshMemuExports.apply(ctx)
532
+ const tab = registrations.filter(item => item.slot === 'sidebar.right.pane.tab').at(-1)
533
+ const wrapper = tab.component({ ctx, t: key => key, sessionId: 'probe-session' })
534
+ const first = await renderPage(wrapper.type, wrapper.props, undefined, { remount: true })
535
+ for (const effect of first.effects) effect.fn()
536
+ await new Promise(resolve => setTimeout(resolve, 0))
537
+ await new Promise(resolve => setTimeout(resolve, 0))
538
+ const { tree } = await renderPage(wrapper.type, wrapper.props)
539
+ const displayed = [], titles = []
540
+ const visit = node => {
541
+ if (node === null || node === undefined || typeof node === 'boolean') return
542
+ if (typeof node === 'string' || typeof node === 'number') { displayed.push(String(node)); return }
543
+ if (Array.isArray(node)) { node.forEach(visit); return }
544
+ if (typeof node.type === 'function') { visit(node.type(node.props)); return }
545
+ if (typeof node.props?.title === 'string') titles.push(node.props.title)
546
+ visit(node.props?.children)
547
+ }
548
+ visit(tree)
549
+ assert.ok(displayed.includes('ProjectLeaf'), 'the real sidebar renders the folder basename, not a loading placeholder')
550
+ assert.ok(titles.length > 0, 'the test traverses tooltip titles as well as visible text')
551
+ for (const value of [...displayed, ...titles]) {
552
+ const normalized = value.replaceAll('\\', '/').toLowerCase()
553
+ assert.ok(!normalized.includes('portowner'), `parent directory leaked for ${scopeKey}: ${value}`)
554
+ assert.ok(!normalized.includes(scopeKey.replaceAll('\\', '/').toLowerCase()), `full scope leaked: ${value}`)
555
+ assert.ok(!path.win32.isAbsolute(value) && !path.posix.isAbsolute(value), `absolute display path: ${value}`)
556
+ }
557
+ }
558
+ })
559
+
506
560
  test('the sidebar context-scope card cannot be flex-shrunk and keeps a two-column field grid', () => {
507
561
  const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
508
562
  assert.match(src, /className: 'dshm-tab-body'/, 'the sidebar body needs its non-shrinking class')
@@ -557,9 +611,51 @@ test('consolidation alerts keep identity separate from actions when expanded', a
557
611
  assert.ok(!treeText(tree).includes('consolidateStarted'))
558
612
  })
559
613
 
560
- test('consolidation alert columns wrap before their controls must be clipped', () => {
614
+ test('sidebar entity reminder opens the selected library memory page and can be snoozed', async () => {
615
+ const rpcCalls = [], opened = []
616
+ const savedOpen = globalThis.window.open
617
+ globalThis.window.location = { href: 'http://host/app' }
618
+ globalThis.window.open = url => { opened.push(String(url)); return { focus() {} } }
619
+ const ctx = fakeCtx({ rpcCalls, answers: {
620
+ listEntityMergeReviews: payload => ({ ok: true, value: {
621
+ items: [{ sourceId: 'entity-a', targetId: 'entity-b', reviewToken: 'a'.repeat(64) }],
622
+ total: 8, totalExact: false,
623
+ } }),
624
+ } })
625
+ try {
626
+ globalThis.__dshMemuExports.apply(ctx)
627
+ const tab = registrations.filter(row => row.slot === 'sidebar.right.pane.tab').at(-1)
628
+ const element = tab.component({ ctx, t: key => key, sessionId: 'probe-session' })
629
+ const first = await renderPage(element.type, element.props, undefined, { remount: true })
630
+ for (const effect of first.effects) effect.fn()
631
+ await new Promise(resolve => setTimeout(resolve, 0))
632
+ await new Promise(resolve => setTimeout(resolve, 0))
633
+ let tree = (await renderPage(element.type, element.props)).tree
634
+ const buttons = () => {
635
+ const found = []
636
+ walkNodes(tree, node => { if (node.type === 'button') found.push(node) })
637
+ return found
638
+ }
639
+ const review = rpcCalls.find(row => row.endpoint === 'listEntityMergeReviews')
640
+ assert.deepEqual(review.payload, { libraryId: 'lib-1', sessionId: 'probe-session', limit: 1, reviewState: 'human' })
641
+ assert.ok(treeText(tree).includes('entityReviewSidebarTitle'), 'the unresolved-candidate reminder is visible')
642
+ buttons().find(node => node.props.children === 'entityReviewSidebarOpen').props.onClick()
643
+ assert.equal(opened.length, 1)
644
+ assert.ok(opened[0].includes('libraryId=lib-1') && opened[0].endsWith('#/settings/memories'),
645
+ 'the reminder opens the WebUI memory page for the bound library, not diagnostics')
646
+ buttons().find(node => node.props.children === 'entityReviewSidebarLater').props.onClick()
647
+ tree = (await renderPage(element.type, element.props)).tree
648
+ assert.ok(!treeText(tree).includes('entityReviewSidebarTitle'), 'Later hides this unchanged candidate set')
649
+ } finally {
650
+ globalThis.window.open = savedOpen
651
+ }
652
+ })
653
+
654
+ test('consolidation alert keeps two columns and wraps its controls', () => {
561
655
  const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
562
- assert.match(src, /\.dshm-consolidation-columns\{[^}]*grid-template-columns:repeat\(auto-fit,minmax\(min\(100%,240px\),1fr\)\)/)
656
+ // 契约:侧栏里始终是失败/成功两列(用户明确要求两列更好扫读)。
657
+ // 早先用 auto-fit+minmax(240px) 在窄侧栏里会退化成单列,那正是被投诉的“并成一列”。
658
+ assert.match(src, /\.dshm-consolidation-columns\{[^}]*grid-template-columns:repeat\(2,minmax\(0,1fr\)\)/)
563
659
  assert.match(src, /\.dshm-consolidation-meta\{[^}]*flex-wrap:wrap/)
564
660
  assert.match(src, /\.dshm-consolidation-column-head\{[^}]*flex-wrap:wrap/)
565
661
  assert.match(src, /\.dshm-consolidation-label\{[^}]*text-overflow:ellipsis/)
@@ -750,6 +846,9 @@ test('the memory browser decides pending reviews in place', async () => {
750
846
  assert.equal(reviewTab.length, 1, 'the review pool tab did not render')
751
847
  reviewTab[0].props.onClick()
752
848
  tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
849
+ for (const effect of effects) effect.fn()
850
+ await new Promise(resolve => setTimeout(resolve, 0))
851
+ tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
753
852
  const buttons = []
754
853
  walkNodes(tree, (node) => {
755
854
  if (typeof node.type === 'function' && (node.props?.children === 'accept' || node.props?.children === 'reject')) buttons.push(node)
@@ -814,6 +913,10 @@ test('the memory wall drawer decides pending reviews without leaving the wall',
814
913
  assert.equal(poolTab.length, 1, 'the wall review pool tab did not render')
815
914
  poolTab[0].props.onClick()
816
915
  tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 9)).tree
916
+ treeText(tree)
917
+ for (const effect of effects) effect.fn()
918
+ await new Promise(resolve => setTimeout(resolve, 0))
919
+ tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 9)).tree
817
920
  const cards = []
818
921
  walkNodes(tree, (node) => {
819
922
  if (node.type === 'button' && String(node.props?.className || '').includes('dshm-wall-item')) cards.push(node)
@@ -846,9 +949,8 @@ test('the memory wall drawer decides pending reviews without leaving the wall',
846
949
  }
847
950
  })
848
951
 
849
- test('the browse search box filters the loaded library in place', async () => {
850
- // 搜索是纯前端的:它只过滤已经拉回来的那一页,不新发 RPC。库一切换就清空,
851
- // 否则上一个库的关键词会把当前库筛成「空库」。
952
+ test('the browse search box asks the server after debounce and labels loaded counts', async () => {
953
+ // 搜索必须覆盖未加载的正文;服务端负责筛选,清空查询也要开启新的快照。
852
954
  const originalGetState = RPC_ANSWERS.getState
853
955
  const originalSettingsState = RPC_ANSWERS.getSettingsState
854
956
  const loaded = { ...EMPTY_STATE, libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 2 }] }
@@ -863,7 +965,10 @@ test('the browse search box filters the loaded library in place', async () => {
863
965
  }
864
966
  try {
865
967
  const rpcCalls = []
866
- const ctx = fakeCtx({ rpcCalls })
968
+ const ctx = fakeCtx({ rpcCalls, answers: { browseLibrary: payload => {
969
+ const files = RPC_ANSWERS.browseLibrary.files.filter(file => !payload.query || file.title.includes(payload.query))
970
+ return { ok: true, value: { source: 'index', files, total: files.length, snapshotRevision: payload.query || 'all' } }
971
+ } } })
867
972
  globalThis.__dshMemuExports.apply(ctx)
868
973
  const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
869
974
  const props = { ctx, t: (key) => key }
@@ -905,17 +1010,30 @@ test('the browse search box filters the loaded library in place', async () => {
905
1010
  walkNodes(tree, (node) => { if (node.type === 'input' && node.props?.placeholder === 'browseSearchPlaceholder') box.push(node) })
906
1011
  assert.equal(box.length, 1, 'no search box under 当前记忆库')
907
1012
  box[0].props.onChange({ target: { value: 'attic' } })
1013
+ await render(5)
1014
+ for (const effect of effects) effect.fn()
1015
+ assert.equal(rpcCalls.filter(call => call.endpoint === 'browseLibrary').length, 0, 'typing waits for trailing debounce')
1016
+ await new Promise(resolve => setTimeout(resolve, 280))
1017
+ await render(5)
1018
+ for (const effect of effects) effect.fn()
1019
+ await new Promise(resolve => setTimeout(resolve, 0))
908
1020
  const filteredTree = (await render(5)).tree
909
1021
  assert.deepEqual(snapshot(filteredTree), { rows: 1, titles: ['the attic'] }, 'the filter keeps only the matching row')
910
- assert.match(treeText(filteredTree), /1 \/ 2/, 'the counter says how much of the library the filter kept')
911
- assert.match(treeText(filteredTree), /browseActiveTab \(1\)/, 'the tab counts follow the filter, not the whole library')
912
- assert.deepEqual(rpcCalls, [], 'filtering an already loaded library must not re-fetch it')
1022
+ assert.match(treeText((await render(5)).tree), /memoryLoaded 1 \/ 1/, 'the counter names loaded rows and server query total')
1023
+ assert.match(treeText((await render(5)).tree), /browseActiveTab \(memoryLoaded 1\)/, 'tab counts explicitly describe the loaded subset')
1024
+ assert.equal(rpcCalls.filter(call => call.endpoint === 'browseLibrary').at(-1).payload.query, 'attic')
913
1025
  box[0].props.onChange({ target: { value: 'no-such-memory' } })
914
- assert.match(treeText((await render(5)).tree), /browseActiveTab \(0\)/, 'a query that matches nothing empties the tab counts')
1026
+ assert.match(treeText((await render(5)).tree), /browseActiveTab \(memoryLoaded 0\)/, 'an unsettled query cannot display an old query count')
915
1027
  const clear = []
916
1028
  walkNodes((await render(5)).tree, (node) => { if (node.type === 'button' && node.props?.children === 'browseSearchClear') clear.push(node) })
917
1029
  assert.equal(clear.length, 1, 'no way to clear the query')
918
1030
  clear[0].props.onClick()
1031
+ await render(5)
1032
+ for (const effect of effects) effect.fn()
1033
+ await new Promise(resolve => setTimeout(resolve, 280))
1034
+ await render(5)
1035
+ for (const effect of effects) effect.fn()
1036
+ await new Promise(resolve => setTimeout(resolve, 0))
919
1037
  assert.deepEqual(snapshot((await render(5)).tree), before, 'clearing the query brings the library back')
920
1038
  } finally {
921
1039
  RPC_ANSWERS.getState = originalGetState
@@ -973,6 +1091,42 @@ test('the WebUI buttons open a new tab and never navigate this one', async () =>
973
1091
  }
974
1092
  })
975
1093
 
1094
+ test('the browser relations entry routes the chosen library without mounting legacy graph management', async () => {
1095
+ const rpcCalls = [], opened = [], savedOpen = globalThis.window.open
1096
+ const ctx = fakeCtx({ rpcCalls, answers: { getSettingsState: { ...EMPTY_STATE, libraries: [{ id: 'lib-a', name: 'A' }, { id: 'lib-b', name: 'B' }] } } })
1097
+ try {
1098
+ globalThis.__dshMemuExports.apply(ctx)
1099
+ const settings = registrations.filter(row => row.slot === 'settings.section').pop()
1100
+ const props = { ctx, t: key => key }
1101
+ const first = await renderPage(settings.component, props, undefined, { remount: true })
1102
+ collectPageHook()
1103
+ for (const effect of first.effects) effect.fn()
1104
+ await new Promise(resolve => setTimeout(resolve, 0))
1105
+ const pickers = [], tabs = []
1106
+ walkNodes((await renderPage(settings.component, props, 5)).tree, node => {
1107
+ if (node.type === 'select' && node.props.value === 'lib-a') pickers.push(node)
1108
+ if (node.props?.role === 'tab' && node.props.children === 'relations') tabs.push(node)
1109
+ })
1110
+ pickers[0].props.onChange({ target: { value: 'lib-b' } })
1111
+ tabs[0].props.onClick()
1112
+ const legacy = [], buttons = []
1113
+ const pass = await renderPage(settings.component, props, 5)
1114
+ walkNodes(pass.tree, node => {
1115
+ if (node.type?.name === 'GraphPanel') { legacy.push(node); return false }
1116
+ if (node.type === 'button' && node.props.children === 'openGraphStudio') buttons.push(node)
1117
+ })
1118
+ for (const effect of pass.effects) effect.fn()
1119
+ await new Promise(resolve => setTimeout(resolve, 0))
1120
+ assert.equal(legacy.length, 0)
1121
+ assert.equal(buttons.length, 1)
1122
+ assert.ok(!rpcCalls.some(row => ['listEntities', 'suggestEntityMerges', 'getAnchorCandidates', 'mergeEntities'].includes(row.endpoint)))
1123
+ globalThis.window.open = url => { opened.push(url); return { focus() {} } }
1124
+ buttons[0].props.onClick()
1125
+ assert.match(opened[0], /[?&]libraryId=lib-b(?:&|#)/)
1126
+ assert.ok(opened[0].endsWith('#/settings/graph'))
1127
+ } finally { globalThis.window.open = savedOpen }
1128
+ })
1129
+
976
1130
  test('the sidebar and the settings page hand out the same WebUI button', async () => {
977
1131
  // Two spellings of one action is how the panes drift: the sidebar used to label
978
1132
  // this button openSettingsShort while the settings page used openWebUi. Both
@@ -1623,6 +1777,9 @@ test('the memory wall global block bulk-archives and the drawer deletes global e
1623
1777
  const archivedTab = view.tabs.find((node) => String(node.props?.children || '').startsWith('browseArchivedTab'))
1624
1778
  archivedTab.props.onClick()
1625
1779
  view = collect((await renderPage(settings.component, props, 9)).tree)
1780
+ for (const effect of effects) effect.fn()
1781
+ await tick(); await tick()
1782
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1626
1783
  assert.equal(view.cards.length, 1)
1627
1784
  view.cards[0].props.onClick()
1628
1785
  await tick(); await tick()
@@ -1911,8 +2068,7 @@ test('a failed first fetch turns into a retry card, not an endless skeleton', as
1911
2068
  assert.ok(!text.includes('initMemory'), 'a failed read must not be reported as "no memory library"')
1912
2069
  })
1913
2070
 
1914
- // offset 分页按 updatedAt 排序:两批之间有人写入/归档时,后一批会重复上一批已经出现
1915
- // 过的条目。首批 60 之后必然要拉第二批,所以去重是必需的不是优化。
2071
+ // Snapshot-change, duplicate-page and observer behavior lives in client-pagination.test.mjs.
1916
2072
 
1917
2073
  // Exercise the real async closures with controlled replies, without mounting unrelated hooks.
1918
2074
  function reviewClientClosure(start, end, dependencies, callback = false) {
@@ -1924,21 +2080,12 @@ function reviewClientClosure(start, end, dependencies, callback = false) {
1924
2080
  return new Function(...Object.keys(dependencies), 'return ' + source.slice(from + start.length, to).trim().replace(/;$/, '') + (callback ? '\n}' : ''))(...Object.values(dependencies))
1925
2081
  }
1926
2082
 
1927
- test('wall pagination consumes raw rows and continues past a fully duplicate page', async () => {
1928
- const rows = Array.from({ length: 300 }, (_, n) => ({ id: 'review-' + n, libraryId: 'lib-1' }))
1929
- const tail = { id: 'review-tail', libraryId: 'lib-1' }
1930
- const calls = [], snapshots = []
1931
- const pages = new Map([[0, rows.slice(0, 60)], [60, rows], [360, rows], [660, [tail]]])
1932
- const stream = reviewClientClosure('const stream = ', ' const load = async', {
1933
- call: async (_method, args) => { calls.push(args); return { total: 661, items: pages.get(args.offset) || [] } },
1934
- current: () => true, setData: value => snapshots.push(value), setError: () => {}, wallDomain: '',
1935
- })
1936
- await stream('lib-1')
1937
- assert.deepEqual(calls.map(row => row.offset), [0, 60, 360, 660])
1938
- assert.deepEqual(calls.map(row => row.limit), [60, 300, 300, 300])
1939
- assert.equal(snapshots.at(-1).items.length, 301)
1940
- assert.ok(snapshots.at(-1).items.some(row => row.id === tail.id), 'tail after duplicate page must be present')
1941
- assert.equal(new Set(snapshots.at(-1).items.map(row => row.libraryId + ':' + row.id)).size, 301)
2083
+ test('wall paging uses shared snapshot controls instead of draining a background stream', () => {
2084
+ const source = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
2085
+ const wall = source.slice(source.indexOf(' function MemoryWallPanel('), source.indexOf(' function LexiconPanel('))
2086
+ assert.match(wall, /useMemoryPages\(\{ call, method: 'browseWall'/)
2087
+ assert.match(wall, /h\(MemoryPageMore, \{ pager, loaded: items.length, t \}\)/)
2088
+ assert.ok(!wall.includes('const stream ='), 'the wall cannot loop through all pages on mount')
1942
2089
  })
1943
2090
 
1944
2091
  function reviewRefresh(sessionId, overrides = {}) {
@@ -1951,6 +2098,54 @@ function reviewRefresh(sessionId, overrides = {}) {
1951
2098
  }, true)
1952
2099
  }
1953
2100
 
2101
+ function curationSubmit(overrides = {}) {
2102
+ const owner = overrides.curationOwner || { key: 'selection-a' }
2103
+ return reviewClientClosure('const startSelectedCuration = ', ' const setSetting = ', {
2104
+ curationOwner: owner, curationSelection: { current: owner }, curationPending: { current: false },
2105
+ curationParent: '', sessions: [{ id: 'first-live', live: true }, { id: 'chosen-live', live: true }, { id: 'cold', live: false }],
2106
+ selected: ['source-only'], setBusy() {}, setError() {}, setJob() {}, setSelected() {}, refresh: async () => {},
2107
+ t: key => key, call: async () => ({ id: 'job', status: 'running' }), ...overrides,
2108
+ })
2109
+ }
2110
+
2111
+ test('global curation requires an explicitly selected live executor separate from its sources', async () => {
2112
+ const calls = [], errors = []
2113
+ const deps = { call: async (method, payload) => { calls.push({ method, payload }); return { id: 'job' } }, setError: error => errors.push(error) }
2114
+ await curationSubmit(deps)()
2115
+ await curationSubmit({ ...deps, curationParent: 'cold' })()
2116
+ assert.equal(calls.length, 0, 'neither an empty nor an offline executor falls back to the first live session')
2117
+ assert.deepEqual(errors, ['curationExecutorPick', 'curationExecutorPick'])
2118
+ await curationSubmit({ ...deps, curationParent: 'chosen-live' })()
2119
+ assert.deepEqual(calls, [{ method: 'generateGlobal', payload: { sessionId: 'chosen-live', sessionIds: ['source-only'] } }])
2120
+ })
2121
+
2122
+ test('queued global curation captures executor and sources and cannot clear a later selection', async () => {
2123
+ let release
2124
+ const reply = new Promise(resolve => { release = resolve }), calls = [], published = []
2125
+ const owner = { key: 'selection-a' }, selection = { current: owner }, pending = { current: false }, sources = ['source-only']
2126
+ const submit = curationSubmit({ curationParent: 'chosen-live', selected: sources, curationOwner: owner, curationSelection: selection, curationPending: pending,
2127
+ call: (method, payload) => { calls.push({ method, payload }); return reply }, setJob: value => published.push(value),
2128
+ setSelected: value => published.push(value), refresh: async () => published.push('refresh') })
2129
+ const saving = submit()
2130
+ await submit()
2131
+ sources.push('later-source'); selection.current = { key: 'selection-a' }
2132
+ release({ id: 'old-job' }); await saving
2133
+ assert.deepEqual(calls, [{ method: 'generateGlobal', payload: { sessionId: 'chosen-live', sessionIds: ['source-only'] } }])
2134
+ assert.deepEqual(published, [], 'the previous executor completion does not overwrite the new source draft or job')
2135
+ assert.equal(pending.current, false)
2136
+ })
2137
+
2138
+ test('a stale curation submit or error cannot address a newly selected executor', async () => {
2139
+ let reject
2140
+ const owner = { key: 'selection-a' }, reply = new Promise((_resolve, no) => { reject = no }), selection = { current: owner }, errors = [], calls = []
2141
+ const submit = curationSubmit({ curationParent: 'chosen-live', curationOwner: owner, curationSelection: selection,
2142
+ call: (_method, payload) => { calls.push(payload); return reply }, setError: value => errors.push(value) })
2143
+ const saving = submit(); selection.current = { key: 'selection-b' }; reject(new Error('old executor failure')); await saving
2144
+ await submit()
2145
+ assert.equal(calls.length, 1)
2146
+ assert.deepEqual(errors, [])
2147
+ })
2148
+
1954
2149
  test('a late sidebar response cannot publish under a different current conversation', async () => {
1955
2150
  let release
1956
2151
  const reply = new Promise(resolve => { release = resolve })
@@ -13,6 +13,7 @@ process.env.DSH_MEMU_MEMORY_HOME = home
13
13
  const state = await import('../lib/state.js')
14
14
  const activity = await import('../lib/activity-log.js')
15
15
  const ledger = await import('../lib/consolidation-ledger.js')
16
+ const graph = await import('../lib/graph.js')
16
17
  const forkModel = await import('../lib/fork-model.js')
17
18
  const { dataDir, setWarnSink } = await import('../lib/paths.js')
18
19
  const { retireWorker } = await import('../lib/worker-pool.js')
@@ -64,7 +65,7 @@ function assertHostCreateAccepts(spec = {}) {
64
65
  }
65
66
  }
66
67
 
67
- function host({ live = false, whenIdle = null, parentOptions = { provider: 'test-provider', model: 'test-model' }, requestConfig = null, extraEvents = [], transcriptSize = 0, turnReason = { kind: 'completed' }, emitTurnEnd = true, headerTools = null, childCtxFactory = null, llm = null, presets = null, cwd = path.join(home, 'proj') } = {}) {
68
+ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test-provider', model: 'test-model' }, requestConfig = null, extraEvents = [], transcriptSize = 0, turnReason = { kind: 'completed' }, emitTurnEnd = true, headerTools = null, childCtxFactory = null, llm = null, presets = null, followupError = null, wrapupError = null, cwd = path.join(home, 'proj') } = {}) {
68
69
  const rec = { liveFollowups: [], created: [], forkFollowups: [], disposed: [], sessionHandlers: [], workerToolRegistrations: [], workerToolDisposals: [], mountedPresets: [], forkLogLines: [] }
69
70
  // agents.get 返回裸 agent;dispose 注销活句柄,但会话 id 仍在磁盘上占用。
70
71
  const childAgents = new Map()
@@ -119,6 +120,8 @@ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test
119
120
  ctx: childCtxFactory?.(),
120
121
  dispose,
121
122
  followup: (message) => {
123
+ const failure = followupError || (rec.forkFollowups.length > 0 ? wrapupError : null)
124
+ if (failure) return Promise.reject(new Error(failure))
122
125
  rec.forkFollowups.push({ child: spec.sessionId, message })
123
126
  if (emitTurnEnd) {
124
127
  const reason = typeof turnReason === 'function' ? turnReason(spec) : turnReason
@@ -172,6 +175,86 @@ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test
172
175
  return ctx
173
176
  }
174
177
 
178
+ for (const runner of ['fork', 'worker']) test(`${runner} entity review inherits its conversation model and verifies decisions without moving transcript state`, async () => {
179
+ state.updateSettings({ consolidationRunner: runner, consolidationModelMode: 'host', consolidationModel: 'maintenance/other', consolidationReasoningEffort: 'low' })
180
+ const id = 'entity-model-' + runner
181
+ const binding = state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
182
+ const source = graph.createEntity({ libraryId: binding.libraryId, name: 'Harbor Lin' })
183
+ const target = graph.createEntity({ libraryId: binding.libraryId, name: 'Harbor Lin Mian' })
184
+ state.savePrivateIndex(binding.libraryId, { entries: { evidence: { content: 'Identity evidence remains ambiguous.', title: 'Identity',
185
+ visibility: 'shared', status: 'active', links: [{ to: source.id }, { to: target.id }] } } })
186
+ const pairs = graph.suggestEntityMerges({ libraryId: binding.libraryId }).items
187
+ state.setSessionBinding(id, { lastSleepSeq: 2 })
188
+ ledger.noteEvidence({ sessionId: id, throughSeq: 50 })
189
+ const before = ledger.sessionState(id)
190
+ let decide = false
191
+ const route = { provider: 'parent-provider-' + runner, model: 'parent-model', reasoningEffort: 'high', maxTokens: 4096 }
192
+ const ctx = host({ live: true, requestConfig: route, turnReason: spec => {
193
+ if (decide) graph.holdEntityMergeReview({ libraryId: binding.libraryId, ...pairs[0],
194
+ exec: { agent: { session: { header: { id: spec.sessionId } } } }, reason: 'The visible evidence does not establish identity.', confidence: .6 })
195
+ return { kind: 'completed' }
196
+ } })
197
+ try {
198
+ const empty = await requestPrivateConsolidation(ctx, id, { entityReviewOnly: true, entityReviewPairs: pairs })
199
+ assert.equal(empty.ok, false, 'a completed model turn without a persisted decision is not success')
200
+ assert.equal(empty.reasonCode, 'entity-review-not-settled')
201
+ decide = true
202
+ const done = await requestPrivateConsolidation(ctx, id, { entityReviewOnly: true, entityReviewPairs: pairs })
203
+ assert.equal(done.ok, true, done.error)
204
+ assert.equal(done.settled, true)
205
+ assert.equal(done.processed, 1)
206
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, 2)
207
+ assert.deepEqual(ledger.sessionState(id).pending, before.pending)
208
+ assert.deepEqual(ledger.sessionState(id).checked, before.checked)
209
+ assert.deepEqual(ledger.sessionState(id).operations, before.operations)
210
+ assert.equal(ctx.rec.liveFollowups.length, 0)
211
+ assert.ok(ctx.rec.created.length >= 1)
212
+ assert.deepEqual(ctx.rec.created[0].agentOptions, route)
213
+ assert.match(JSON.stringify(ctx.rec.forkFollowups), /实体候选自动裁决/)
214
+ assert.equal(graph.suggestEntityMerges({ libraryId: binding.libraryId, reviewState: 'model' }).items.length, 0)
215
+ } finally {
216
+ const worker = state.getSessionBinding(id)?.workerEpoch?.forkSessionId
217
+ if (worker) await retireWorker(ctx, worker, 'test-cleanup', { handoff: false })
218
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'inherit', consolidationModel: '', consolidationReasoningEffort: 'inherit' })
219
+ }
220
+ })
221
+
222
+ test('an asynchronously rejected primary followup is caught and never credited as dispatch', async () => {
223
+ const id = 'fork-followup-rejected'
224
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
225
+ let idleCalls = 0
226
+ const ctx = host({ live: true, followupError: 'synthetic async dispatch rejection', whenIdle: async () => { idleCalls++ } })
227
+ const result = await requestPrivateConsolidation(ctx, id)
228
+ assert.equal(result.ok, false)
229
+ assert.match(result.error, /synthetic async dispatch rejection/)
230
+ assert.equal(result.measurement.dispatched.followups, 0)
231
+ assert.equal(result.measurement.dispatched.inputChars, 0)
232
+ assert.equal(idleCalls, 0)
233
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, undefined)
234
+ assert.equal(ctx.rec.disposed.length, 1)
235
+ })
236
+
237
+ test('a rejected asynchronous wrapup is caught and omitted from successful dispatch accounting', async () => {
238
+ const { WORKER_WRAPUP_ROUND } = await import('../lib/consolidation-worker.js')
239
+ assert.ok(Number.isSafeInteger(WORKER_WRAPUP_ROUND))
240
+ const id = 'fork-wrapup-rejected'
241
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
242
+ let ctx
243
+ ctx = host({ live: true, wrapupError: 'synthetic async wrapup rejection', whenIdle: async () => {
244
+ const child = ctx.get('agents').get(ctx.rec.created[0].sessionId)
245
+ for (let i = 0; i < WORKER_WRAPUP_ROUND; i++) {
246
+ for (const handler of [...ctx.rec.sessionHandlers]) handler(child.session, { type: 'tool/call', seq: 200 + i,
247
+ data: { id: 'wrapup-call-' + i, name: 'read', arguments: {} } })
248
+ }
249
+ await Promise.resolve()
250
+ await Promise.resolve()
251
+ } })
252
+ const result = await requestPrivateConsolidation(ctx, id)
253
+ assert.equal(result.ok, true, result.error || '')
254
+ assert.equal(result.measurement.dispatched.followups, 1)
255
+ assert.equal(result.measurement.dispatched.wrapupChars, 0)
256
+ })
257
+
175
258
  test('enabling local or remote vectors does not opt into remote summary', async () => {
176
259
  const originalFetch = globalThis.fetch
177
260
  let fetches = 0
@@ -793,14 +876,14 @@ test('a PTC session (run_code only header) is consolidated and the worker gets w
793
876
  assert.equal(ctx.rec.created.length, 1, 'the fork is created for the PTC conversation')
794
877
  // 只挂 worker 真正用到的写面(remember/batch/update + link/link_suggest 裁决两件);
795
878
  // lexicon、archive/delete/unpin 这些用不到或破坏性的工具不进 worker 面。
796
- assert.deepEqual([...registered].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
879
+ assert.deepEqual([...registered].sort(), ['memu_private_entity_merge_decide', 'memu_private_entity_merge_suggest', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
797
880
  // 整理结束(finally)必须卸载挂载,不能给这条一次性 worker 留常驻注册。
798
- assert.deepEqual([...disposals].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
881
+ assert.deepEqual([...disposals].sort(), ['memu_private_entity_merge_decide', 'memu_private_entity_merge_suggest', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
799
882
  // 全量挂载的活动元数据:attached=实际子集(此处=完整 wanted)、requested=完整 wanted、
800
883
  // partial=false。三件一起钉住"成功路径不再含糊"。
801
884
  const started = startedEntryFor(ctx, 'fork-ptc')
802
- assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
803
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
885
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_entity_merge_decide', 'memu_private_entity_merge_suggest', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
886
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_entity_merge_decide', 'memu_private_entity_merge_suggest', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
804
887
  assert.equal(started.detail.workerToolsPartial, false, 'a full mount is not partial')
805
888
  const followup = ctx.rec.forkFollowups[0]?.message
806
889
  const brief = Array.isArray(followup?.content)
@@ -842,14 +925,14 @@ test('a host registry refusing one write tool leaves a structured partial mount
842
925
  const result = await requestPrivateConsolidation(ctx, 'fork-ptc-partial')
843
926
  assert.equal(result.ok, true, String(result.error || ''))
844
927
  assert.equal(result.settled, true)
845
- assert.deepEqual([...registered].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
928
+ assert.deepEqual([...registered].sort(), ['memu_private_entity_merge_decide', 'memu_private_entity_merge_suggest', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
846
929
  'exactly the tools that actually registered are mounted')
847
- assert.deepEqual([...disposals].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
930
+ assert.deepEqual([...disposals].sort(), ['memu_private_entity_merge_decide', 'memu_private_entity_merge_suggest', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
848
931
  'dispose unmounts exactly what was mounted')
849
932
  const started = startedEntryFor(ctx, 'fork-ptc-partial')
850
- assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
933
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_entity_merge_decide', 'memu_private_entity_merge_suggest', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_remember_batch', 'memu_private_update'],
851
934
  'the log records the actual subset, not the full wanted list')
852
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
935
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_entity_merge_decide', 'memu_private_entity_merge_suggest', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
853
936
  assert.equal(started.detail.workerToolsPartial, true)
854
937
  // 挂载为部分子集时任务书仍带 PTC 调用形态:worker 知道写记忆走 run_code 的 SDK 绑定。
855
938
  const followup = ctx.rec.forkFollowups[0]?.message
@@ -870,7 +953,7 @@ test('a fork context without a tools service records a null mount, the request a
870
953
  assert.equal(result.ok, true, String(result.error || ''))
871
954
  const started = startedEntryFor(ctx, 'fork-ptc-notools')
872
955
  assert.equal(started.detail.workerToolsAttached, null, 'no mount completed, so the log must not claim one')
873
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
956
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_entity_merge_decide', 'memu_private_entity_merge_suggest', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
874
957
  assert.equal(started.detail.workerToolsPartial, true)
875
958
  })
876
959
 
@@ -47,6 +47,22 @@ test('a job holds a lease and a second job is refused while it is live', () => {
47
47
  assert.equal(second.jobId, 'job-1')
48
48
  })
49
49
 
50
+ test('entity-only leases cannot advance or fail the transcript cursor, including restart recovery', () => {
51
+ for (const action of ['release', 'fail', 'recover']) {
52
+ const sessionId = 'entity-lease-' + action
53
+ ledger.noteEvidence({ sessionId, throughSeq: 80 })
54
+ const before = ledger.sessionState(sessionId)
55
+ ledger.beginJob({ sessionId, jobId: 'entity-job', kind: 'entity-review', snapshot: snapshot(20), binding: binding(), now: 100, leaseMs: 100 })
56
+ assert.equal(ledger.completeJob({ sessionId, jobId: 'entity-job', snapshot: snapshot(20), covered: { fromSeq: 0, throughSeq: 20 }, status: 'completed', now: 101 }).advanced, false)
57
+ if (action === 'release') ledger.releaseEntityReviewJob({ sessionId, jobId: 'entity-job' })
58
+ if (action === 'fail') ledger.failJob({ sessionId, jobId: 'entity-job', error: 'model failed' })
59
+ if (action === 'recover') ledger.recoverStaleJobs({ now: 201 })
60
+ const after = ledger.sessionState(sessionId)
61
+ for (const key of ['checked', 'pending', 'attempts', 'retryAt', 'operations']) assert.deepEqual(after[key], before[key], action + ': ' + key)
62
+ assert.equal(after.inflight, null)
63
+ }
64
+ })
65
+
50
66
  test('evidence advances the pending boundary only, never the checked one', () => {
51
67
  const sessionId = 'led-pending'
52
68
  const first = ledger.noteEvidence({ sessionId, fromSeq: 0, throughSeq: 12 })
@@ -387,4 +403,4 @@ test('carry candidates survive the ledger round-trip and stay bounded', () => {
387
403
  assert.equal(ledger.readCarryCandidates('carry-1').length, ledger.CARRY_LIMIT, 'the carry list is capped')
388
404
  ledger.setCarryCandidates('carry-1', [])
389
405
  assert.deepEqual(ledger.readCarryCandidates('carry-1'), [], 'a covered window clears the carry')
390
- })
406
+ })
@@ -0,0 +1,54 @@
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
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-diagnostic-entity-candidates-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+ process.env.DSH_MEMU_MEMORY_HOME = home
10
+
11
+ const diagnostics = await import('../lib/diagnostics.js')
12
+ const environment = await import('../lib/environment-check.js')
13
+
14
+ test.after(() => fs.rmSync(home, { recursive: true, force: true }))
15
+
16
+ test('entity-fragment diagnostics persist and display only aggregate counts', () => {
17
+ const candidateDetail = {
18
+ similar: 2,
19
+ libraries: 1,
20
+ entityMergeCandidates: {
21
+ candidates: [{
22
+ source: { name: 'private-source-name', kind: 'person', id: 'ent-source-private' },
23
+ target: { name: 'private-target-name', kind: 'person', id: 'ent-target-private' },
24
+ }],
25
+ },
26
+ listEntityMergeReviews: {
27
+ items: [{ source: 'private-source-name', target: 'private-target-name', reviewToken: 'private-review-token' }],
28
+ },
29
+ }
30
+ const expected = { similar: 2, libraries: 1 }
31
+
32
+ assert.deepEqual(diagnostics.shapeDetail(candidateDetail, 'ENTITY_FRAGMENT_SUSPECTED'), expected)
33
+
34
+ diagnostics.recordDiagnostic({
35
+ level: 'warn', scope: 'graph', code: 'ENTITY_FRAGMENT_SUSPECTED',
36
+ message: 'similar entity candidates need review', detail: candidateDetail,
37
+ source: 'entity-repair',
38
+ })
39
+ const file = path.join(home, 'diagnostics', 'events.jsonl')
40
+ const persisted = fs.readFileSync(file, 'utf8')
41
+ const rows = diagnostics.listDiagnostics()
42
+ const report = environment.collectDiagnosticReport()
43
+ const entry = rows.items.find(item => item.code === 'ENTITY_FRAGMENT_SUSPECTED')
44
+ const reportEntry = report.diagnostics.items.find(item => item.code === 'ENTITY_FRAGMENT_SUSPECTED')
45
+
46
+ assert.deepEqual(entry.detail, expected)
47
+ assert.deepEqual(reportEntry.detail, expected)
48
+ for (const output of [persisted, JSON.stringify(rows), report.text]) {
49
+ for (const forbidden of [
50
+ 'private-source-name', 'private-target-name', 'ent-source-private', 'ent-target-private',
51
+ 'private-review-token', 'entityMergeCandidates', 'listEntityMergeReviews',
52
+ ]) assert.ok(!output.includes(forbidden), forbidden)
53
+ }
54
+ })