dsh-memu-memory 1.4.3 → 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 (183) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +34 -15
  4. package/README.zh.md +35 -13
  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/preset-mount.js +13 -7
  63. package/lib/private.js +47 -21
  64. package/lib/recall-cache.js +20 -34
  65. package/lib/retention.js +173 -0
  66. package/lib/rpc.js +135 -52
  67. package/lib/rt-index/builder.js +209 -0
  68. package/lib/rt-index/format.js +231 -0
  69. package/lib/rt-index/manifest.js +105 -0
  70. package/lib/rt-index/reader.js +673 -0
  71. package/lib/rt-index-retention.js +151 -0
  72. package/lib/rt-index-service.js +283 -0
  73. package/lib/rt-index-worker.js +21 -0
  74. package/lib/salient-wake.js +55 -4
  75. package/lib/state.js +195 -24
  76. package/lib/temporal.js +39 -13
  77. package/lib/token-measurement.js +126 -0
  78. package/lib/tools.js +101 -6
  79. package/lib/turn-log.js +108 -3
  80. package/lib/webui/graph-layout-worker.js +68 -0
  81. package/lib/webui/graph-local-physics.js +390 -0
  82. package/lib/webui/graph-spatial-grid.js +64 -0
  83. package/lib/webui/graph-view.bundle.js +6 -1
  84. package/lib/webui/graph-view.js +478 -135
  85. package/lib/webui/graph-webgl-renderer.js +74 -0
  86. package/lib/webui/standalone.js +1 -1
  87. package/lib/worker-pool.js +38 -7
  88. package/package.json +3 -2
  89. package/scripts/acceptance-local.mjs +4 -10
  90. package/scripts/bench-all-libraries.mjs +47 -0
  91. package/scripts/check-classic-graph-browser.mjs +189 -0
  92. package/scripts/check-client-browser.mjs +929 -0
  93. package/scripts/check-graph-browser.mjs +6 -0
  94. package/scripts/check-graph-elastic-browser.mjs +139 -0
  95. package/scripts/check-memory-review-browser.mjs +124 -0
  96. package/scripts/entity-dedupe.mjs +19 -3
  97. package/scripts/graph-artifact-provenance.mjs +30 -0
  98. package/scripts/graph-freeze-manifest.mjs +129 -0
  99. package/scripts/graph-geometry-fixture.mjs +40 -0
  100. package/scripts/graph-physics-bench.mjs +218 -0
  101. package/scripts/graph-scale-bench.mjs +213 -0
  102. package/scripts/graph-scale-memory.mjs +48 -0
  103. package/scripts/graph-service-bench.mjs +72 -0
  104. package/scripts/make-readme-shots.mjs +17 -5
  105. package/scripts/preview.mjs +1 -0
  106. package/scripts/rebuild-rt.mjs +18 -0
  107. package/scripts/scale-bench.mjs +183 -0
  108. package/scripts/simulate-injection.mjs +47 -8
  109. package/scripts/verify-host-fixtures.mjs +108 -0
  110. package/scripts/verify-host-recovery.mjs +565 -0
  111. package/scripts/verify-vector-recovery.mjs +740 -0
  112. package/tests/auto-link-candidates.test.mjs +20 -0
  113. package/tests/browser.test.mjs +16 -2
  114. package/tests/client-export.test.mjs +16 -1
  115. package/tests/client-pagination.test.mjs +1495 -0
  116. package/tests/client-render.test.mjs +223 -28
  117. package/tests/consolidation-fork.test.mjs +97 -13
  118. package/tests/consolidation-ledger.test.mjs +17 -1
  119. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  120. package/tests/diagnostic-report.test.mjs +429 -0
  121. package/tests/diagnostic-wiring.test.mjs +88 -0
  122. package/tests/diagnostics.test.mjs +27 -0
  123. package/tests/embedding-download.test.mjs +44 -0
  124. package/tests/engine-source-settings.test.mjs +69 -0
  125. package/tests/engine-sources.test.mjs +145 -0
  126. package/tests/entity-dedupe.test.mjs +143 -0
  127. package/tests/entity-merge-review.test.mjs +363 -0
  128. package/tests/entity-merge.test.mjs +12 -4
  129. package/tests/entity-review.test.mjs +87 -0
  130. package/tests/environment-check.test.mjs +51 -1
  131. package/tests/feedback.test.mjs +95 -0
  132. package/tests/graph-adjacency-index.test.mjs +536 -0
  133. package/tests/graph-cascade.test.mjs +229 -0
  134. package/tests/graph-import-diagnostic.test.mjs +25 -0
  135. package/tests/graph-overview.test.mjs +709 -0
  136. package/tests/graph-session-authorization.test.mjs +419 -0
  137. package/tests/graph-view-geometry.test.mjs +426 -0
  138. package/tests/graph-view-scale.test.mjs +88 -0
  139. package/tests/graph-view.test.mjs +444 -5
  140. package/tests/graph.test.mjs +43 -0
  141. package/tests/help-page.test.mjs +128 -54
  142. package/tests/inbound.test.mjs +19 -0
  143. package/tests/index-pagination.test.mjs +113 -0
  144. package/tests/index-read-view.test.mjs +212 -0
  145. package/tests/inject-guide.test.mjs +9 -0
  146. package/tests/injection-dedupe.test.mjs +213 -0
  147. package/tests/lexicon-recall.test.mjs +641 -0
  148. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  149. package/tests/lexicon-rt.test.mjs +468 -0
  150. package/tests/local-embedding-worker.test.mjs +38 -0
  151. package/tests/local-vector-service.test.mjs +32 -3
  152. package/tests/maintenance-compat.test.mjs +128 -0
  153. package/tests/maintenance-settlement.test.mjs +1003 -0
  154. package/tests/managed-memory.test.mjs +39 -11
  155. package/tests/managed-runtime.test.mjs +109 -0
  156. package/tests/memory-fields.test.mjs +24 -12
  157. package/tests/observed-evidence.test.mjs +52 -0
  158. package/tests/port-surface.test.mjs +93 -1
  159. package/tests/preset-mount.test.mjs +12 -4
  160. package/tests/recall-cache.test.mjs +56 -3
  161. package/tests/recall-dedup.test.mjs +63 -2
  162. package/tests/retention.test.mjs +260 -0
  163. package/tests/rt-index-cross-library.test.mjs +230 -0
  164. package/tests/rt-index-integration.test.mjs +194 -0
  165. package/tests/rt-index-retention.test.mjs +552 -0
  166. package/tests/rt-index-scale.test.mjs +204 -0
  167. package/tests/rt-index.test.mjs +705 -0
  168. package/tests/salient-date-boundaries.test.mjs +121 -0
  169. package/tests/salient-wake.test.mjs +29 -0
  170. package/tests/scale-bench.test.mjs +53 -0
  171. package/tests/settings-plumbing.test.mjs +25 -0
  172. package/tests/simulate-injection.test.mjs +15 -1
  173. package/tests/standalone-navigation.test.mjs +44 -0
  174. package/tests/state.test.mjs +51 -0
  175. package/tests/temporal-precision.test.mjs +102 -0
  176. package/tests/temporal.test.mjs +10 -6
  177. package/tests/token-measurement.test.mjs +98 -0
  178. package/tests/tool-schema.test.mjs +41 -5
  179. package/tests/tools.test.mjs +6 -3
  180. package/tests/turn-token-budget.test.mjs +149 -0
  181. package/tests/webui-auth.test.mjs +57 -1
  182. package/tests/webui.test.mjs +40 -15
  183. package/tests/worker-lifecycle.test.mjs +2 -1
@@ -0,0 +1,1495 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import vm from 'node:vm'
5
+ import { buildGraphOverview, selectGraphOverview } from '../lib/graph-overview.js'
6
+
7
+ const source = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
8
+ const tick = () => new Promise(resolve => setTimeout(resolve, 0))
9
+ const defer = () => { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
10
+ const rows = (start, count, prefix = 'm') => Array.from({ length: count }, (_, i) => ({ id: prefix + (start + i), libraryId: 'lib-a', status: 'active', layer: 'long_term' }))
11
+ const managementGraph = (nodes, args, revision = 'r1') => selectGraphOverview(buildGraphOverview({ nodes, edges: [] }, { revision }), args)
12
+ const action = (tree, label) => pick(tree, node => node.type === 'button' && (node.props['aria-label'] === label || node.props.children === label))[0]
13
+ const managerRows = tree => pick(tree, node => node.props?.className?.startsWith('dshm-gs-mgr-row'))
14
+ const pick = (tree, predicate) => {
15
+ const found = []
16
+ const visit = node => {
17
+ if (!node || typeof node !== 'object') return
18
+ if (Array.isArray(node)) { node.forEach(visit); return }
19
+ if (predicate(node)) found.push(node)
20
+ visit(node.props?.children)
21
+ }
22
+ visit(tree)
23
+ return found
24
+ }
25
+
26
+ // Real client closures, with persistent refs, dependency-aware effects and cleanup.
27
+ function client() {
28
+ let active, internals
29
+ const slot = initial => {
30
+ const owner = active, index = owner.cursor++
31
+ if (!owner.hooks[index]) owner.hooks[index] = { value: typeof initial === 'function' ? initial() : initial }
32
+ return [owner.hooks[index], owner]
33
+ }
34
+ const same = (a, b) => a && b && a.length === b.length && a.every((value, i) => Object.is(value, b[i]))
35
+ const React = {
36
+ createElement: (type, props, ...children) => ({ type, props: { ...props, children: children.length === 1 ? children[0] : children } }),
37
+ Fragment: Symbol('Fragment'), memo: value => value,
38
+ useState(initial) {
39
+ const [state, owner] = slot(initial)
40
+ return [state.value, value => { state.value = typeof value === 'function' ? value(state.value) : value; owner.dirty = true }]
41
+ },
42
+ useRef(value) { return slot(() => ({ current: value }))[0].value },
43
+ useMemo(fn, deps) { const [state] = slot(null); if (!same(state.deps, deps)) { state.value = fn(); state.deps = deps } return state.value },
44
+ useCallback(fn, deps) { return React.useMemo(() => fn, deps) },
45
+ useEffect(fn, deps) { const [state, owner] = slot(null); if (!same(state.deps, deps)) owner.pending.push(() => { state.cleanup?.(); state.deps = deps; state.cleanup = fn() }) },
46
+ useLayoutEffect(fn, deps) { React.useEffect(fn, deps) },
47
+ useSyncExternalStore(_subscribe, get) { return get() },
48
+ }
49
+ const observers = []
50
+ class Observer {
51
+ constructor(callback, options) { Object.assign(this, { callback, options, disconnected: false }); observers.push(this) }
52
+ observe(node) { this.node = node }
53
+ disconnect() { this.disconnected = true }
54
+ }
55
+ const context = {
56
+ console, setTimeout, clearTimeout, setInterval, clearInterval, URLSearchParams, URL,
57
+ IntersectionObserver: Observer,
58
+ document: { querySelector: () => null, addEventListener() {}, removeEventListener() {}, body: { style: {} } },
59
+ window: { addEventListener() {}, removeEventListener() {}, location: { hash: '', search: '' },
60
+ __ModuleLoader__: { load: ({ factory }) => { internals = factory(name => { if (name === 'react') return React; throw new Error(name) }).__test } } },
61
+ }
62
+ vm.runInNewContext(source.replace('return module.exports', 'exports.__test = { useMemoryPages, useDebouncedValue, MemoryPageMore, MemoryWallPanel, EntityMergeReviewPanel, LexiconPanel, GraphStudioPanel, GraphCanvas, GraphActionsPanel, SessionActionsPanel, PipIndexesInput, BrowserMemoryCard }; return module.exports'), context)
63
+ const render = (component, initialProps) => {
64
+ const owner = { hooks: [], pending: [], dirty: false, cursor: 0, props: initialProps, value: null }
65
+ owner.draw = (props = owner.props) => {
66
+ owner.props = props; owner.cursor = 0; owner.pending = []; owner.dirty = false
67
+ active = owner
68
+ owner.value = component(props)
69
+ for (const node of pick(owner.value, node => node.props?.ref)) node.props.ref.current = node.props.ref.current || { scrollTop: 450 }
70
+ return owner.value
71
+ }
72
+ owner.flush = async () => {
73
+ for (let i = 0; i < 5; i++) {
74
+ owner.draw()
75
+ for (const effect of owner.pending) effect()
76
+ await tick()
77
+ if (!owner.dirty) break
78
+ }
79
+ return owner.draw()
80
+ }
81
+ owner.close = () => { for (const hook of owner.hooks) hook?.cleanup?.() }
82
+ owner.draw()
83
+ return owner
84
+ }
85
+ return { ...internals, render, observers, context }
86
+ }
87
+
88
+ test('the unified graph inherits a browser entry library before its first read', async () => {
89
+ const ui = client(), calls = []
90
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, libraries: [{ id: 'lib-a' }, { id: 'lib-b' }], initialLibraryId: 'lib-b',
91
+ call: async (method, args) => { calls.push({ method, args }); return { nodes: [], edges: [], overview: true, mode: 'clusters', total: { nodes: 0, edges: 0 } } } })
92
+ const tree = await panel.flush()
93
+ assert.equal(pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.value, 'lib-b')
94
+ assert.equal(calls.filter(row => row.method === 'getGraph').length, 1)
95
+ assert.ok(calls.filter(row => row.method === 'getGraph').every(row => row.args.libraryId === 'lib-b' && row.args.overview === true))
96
+ assert.ok(!calls.some(row => ['listEntities', 'suggestEntityMerges', 'getAnchorCandidates'].includes(row.method)))
97
+ panel.close()
98
+ })
99
+
100
+ test('entity review panel shows pending pair evidence, marks inexact totals and scopes reads by library', async () => {
101
+ const ui = client(), calls = []
102
+ const candidate = {
103
+ id: 'review-1', status: 'pending', sourceId: 'sibling-a', targetId: 'sibling-b',
104
+ sourceName: '林澄', targetName: '林澈', sourceType: 'person', targetType: 'person',
105
+ reason: 'edit-distance', reasonDetail: '名字接近,但关系与身份仍需核对', reviewToken: 'a'.repeat(64),
106
+ sourceEvidence: [{ id: 'ma', title: '合租的哥哥', summary: '林澄是林澈的哥哥。' }],
107
+ targetEvidence: [{ id: 'mb', title: '妹妹的生日', summary: '林澈提到自己的妹妹。' }],
108
+ }
109
+ const panel = ui.render(ui.EntityMergeReviewPanel, { libraries: [{ id: 'lib-a', name: 'RP' }], t: key => key,
110
+ call: async (method, args) => {
111
+ calls.push({ method, args })
112
+ return { items: [candidate], total: 3, totalExact: false, nextCursor: 'next-page' }
113
+ } })
114
+ let tree = await panel.flush()
115
+ assert.deepEqual(calls.map(row => row.method), ['listEntityMergeReviews'])
116
+ assert.equal(calls[0].args.libraryId, 'lib-a')
117
+ assert.equal(calls[0].args.limit, 20)
118
+ assert.ok(pick(tree, node => node.props?.children === 'entityReviewCountApprox').length)
119
+ assert.ok(!pick(tree, node => node.props?.children === 'entityReviewCountExact').length)
120
+ for (const text of ['林澄', '林澈', 'person', '名字接近,但关系与身份仍需核对', '林澄是林澈的哥哥。', '林澈提到自己的妹妹。']) {
121
+ assert.ok(JSON.stringify(tree).includes(text), `missing candidate detail: ${text}`)
122
+ }
123
+ assert.equal(pick(tree, node => node.type?.name === 'Button' && node.props.children === 'entityMergeAction').length, 1)
124
+ assert.equal(pick(tree, node => node.type?.name === 'Button' && node.props.children === 'entityReviewExclude').length, 1)
125
+ assert.equal(calls.some(row => ['mergeEntities', 'setEntityMergeRejection'].includes(row.method)), false, 'rendering a candidate never writes')
126
+ panel.close()
127
+ })
128
+
129
+ test('entity review panel suppresses AI-resolved candidates and refuses writes without a review token', async () => {
130
+ const ui = client(), calls = []
131
+ const pending = { id: 'pending', sourceId: 's', targetId: 't', sourceName: 'A', targetName: 'B', status: 'pending' }
132
+ const resolved = { id: 'resolved', sourceId: 'x', targetId: 'y', sourceName: 'X', targetName: 'Y', status: 'merged', pending: false }
133
+ const panel = ui.render(ui.EntityMergeReviewPanel, { libraries: [{ id: 'lib-a' }], t: key => key,
134
+ call: async (method, args) => {
135
+ calls.push({ method, args })
136
+ return { items: [pending, resolved], total: 1, totalExact: true }
137
+ } })
138
+ let tree = await panel.flush()
139
+ assert.ok(JSON.stringify(tree).includes('entityReviewModel'))
140
+ assert.ok(!JSON.stringify(tree).includes('resolved'), 'AI-resolved entries are not shown to the user')
141
+ const buttons = []
142
+ const visit = node => {
143
+ if (!node) return
144
+ if (Array.isArray(node)) { node.forEach(visit); return }
145
+ if (typeof node !== 'object') return
146
+ if (typeof node.type === 'function') { visit(node.type(node.props)); return }
147
+ if (node.type === 'button') buttons.push(node)
148
+ visit(node.props?.children)
149
+ }
150
+ visit(tree)
151
+ assert.equal(buttons.filter(node => node.props.children === 'entityMergeAction').length, 1)
152
+ assert.equal(buttons.filter(node => node.props.children === 'entityReviewExclude').length, 1)
153
+ assert.ok(buttons.filter(node => ['entityMergeAction', 'entityReviewExclude'].includes(node.props.children))
154
+ .every(node => node.props.disabled), 'missing review tokens disable both destructive decisions')
155
+ assert.ok(!calls.some(row => ['mergeEntities', 'setEntityMergeRejection'].includes(row.method)))
156
+ panel.close()
157
+ })
158
+
159
+ test('entity merge and exclusion require matching second clicks and send the review token', async () => {
160
+ const ui = client(), calls = []
161
+ const candidate = { source: { id: 'source', name: 'Mira', type: 'person', evidence: ['called Mira the older sister'] },
162
+ target: { id: 'target', name: 'Mira Chen', type: 'person', evidence: ['Mira Chen is the younger sister'] },
163
+ reason: 'containment', reviewToken: 'b'.repeat(64) }
164
+ const panel = ui.render(ui.EntityMergeReviewPanel, { libraries: [{ id: 'lib-rp' }], t: key => key,
165
+ call: async (method, args) => {
166
+ calls.push({ method, args })
167
+ if (method === 'listEntityMergeReviews') return { items: [candidate], total: 1, totalExact: true }
168
+ if (method === 'setEntityMergeRejection') return { ok: true, rejected: true }
169
+ return { remappedLinks: 2 }
170
+ } })
171
+ let tree = await panel.flush()
172
+ const button = (label) => {
173
+ let found
174
+ const visit = node => {
175
+ if (!node || found) return
176
+ if (Array.isArray(node)) { node.forEach(visit); return }
177
+ if (typeof node !== 'object') return
178
+ if (typeof node.type === 'function') { visit(node.type(node.props)); return }
179
+ if (node.type === 'button' && node.props.children === label) found = node
180
+ visit(node.props?.children)
181
+ }
182
+ visit(tree)
183
+ return found
184
+ }
185
+ button('entityMergeAction').props.onClick()
186
+ tree = await panel.flush()
187
+ assert.equal(calls.filter(row => row.method === 'mergeEntities').length, 0)
188
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'entityMergeConfirm')[0].props.onClick()
189
+ tree = await panel.flush()
190
+ const merge = calls.find(row => row.method === 'mergeEntities')
191
+ assert.equal(merge.args.libraryId, 'lib-rp')
192
+ assert.equal(merge.args.targetId, 'target')
193
+ assert.deepEqual(Array.from(merge.args.sourceIds), ['source'])
194
+ assert.equal(merge.args.reviewToken, candidate.reviewToken)
195
+
196
+ button('entityReviewExclude').props.onClick()
197
+ tree = await panel.flush()
198
+ assert.equal(calls.filter(row => row.method === 'setEntityMergeRejection').length, 0)
199
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'entityReviewExcludeConfirm')[0].props.onClick()
200
+ await panel.flush()
201
+ const exclusion = calls.find(row => row.method === 'setEntityMergeRejection')
202
+ assert.equal(exclusion.args.libraryId, 'lib-rp')
203
+ assert.equal(exclusion.args.sourceId, 'source')
204
+ assert.equal(exclusion.args.targetId, 'target')
205
+ assert.equal(exclusion.args.reviewToken, candidate.reviewToken)
206
+ assert.equal(exclusion.args.rejected, true)
207
+ assert.equal(exclusion.args.confirmed, true)
208
+ panel.close()
209
+ })
210
+
211
+ test('wall and library fetch one first page and only continue at a real bottom intersection', async () => {
212
+ for (const [method, rowsKey, nextLimit] of [['browseWall', 'items', 300], ['browseLibrary', 'files', 120]]) {
213
+ const ui = client(), calls = []
214
+ const pager = ui.render(ui.useMemoryPages, { method, rowsKey, nextLimit, payload: { libraryId: 'lib-a' },
215
+ call: async (_method, args) => { calls.push(args); return { [rowsKey]: rows(args.offset, Math.min(args.limit, 500 - args.offset)), total: 500, snapshotRevision: 'r1' } } })
216
+ let value = await pager.flush()
217
+ assert.equal(calls.length, 1, method + ' must not drain the library in the background')
218
+ assert.equal(value.data[rowsKey].length, 60)
219
+ const first = value.data[rowsKey][0]
220
+ const more = ui.render(ui.MemoryPageMore, { pager: value, loaded: 60, t: key => key })
221
+ await more.flush()
222
+ assert.equal(more.value.props.key, JSON.stringify([value.pageKey, 0, 60]), 'the sentinel must not become a moving browser scroll anchor')
223
+ const observer = ui.observers.at(-1), node = observer.node
224
+ assert.equal(observer.options.rootMargin, '0px')
225
+ observer.callback([{ isIntersecting: false }])
226
+ await tick()
227
+ assert.equal(calls.length, 1)
228
+ observer.callback([{ isIntersecting: true }]); observer.callback([{ isIntersecting: true }])
229
+ value = await pager.flush()
230
+ assert.equal(calls.length, 2, 'overlapping intersections share one in-flight request')
231
+ assert.equal(calls[1].offset, 60)
232
+ assert.equal(calls[1].limit, nextLimit)
233
+ assert.equal(calls[1].snapshotRevision, 'r1')
234
+ assert.equal(value.data[rowsKey][0], first, 'appending preserves existing card objects and keys')
235
+ assert.equal(node.scrollTop, 450, 'appending never changes the scroll container')
236
+ assert.equal(more.draw({ pager: value, loaded: value.data[rowsKey].length, t: key => key }).props.key,
237
+ JSON.stringify([value.pageKey, 0, 60 + nextLimit]))
238
+ observer.callback([{ isIntersecting: true }])
239
+ await tick()
240
+ assert.equal(calls.length, 2, 'queued notifications from the previous sentinel cannot drain another page')
241
+ more.close(); pager.close()
242
+ assert.equal(observer.disconnected, true)
243
+ }
244
+ })
245
+
246
+ test('pagination has no 40-page or 12000-row cap', async () => {
247
+ const ui = client(), calls = [], total = 12361
248
+ const pager = ui.render(ui.useMemoryPages, { method: 'browseWall', rowsKey: 'items', payload: {},
249
+ call: async (_method, args) => { calls.push(args); return { items: rows(args.offset, Math.min(args.limit, total - args.offset)), total, snapshotRevision: 'stable' } } })
250
+ let value = await pager.flush()
251
+ while (value.hasMore) { await value.more(); value = pager.draw() }
252
+ assert.equal(value.data.items.length, total)
253
+ assert.equal(new Set(value.data.items.map(row => row.id)).size, total)
254
+ assert.ok(calls.length > 40)
255
+ assert.equal(calls.at(-1).snapshotRevision, 'stable')
256
+ pager.close()
257
+ })
258
+
259
+ test('a restarted snapshot requires a fresh bottom entry instead of following browser scroll anchoring', async () => {
260
+ const ui = client()
261
+ let reads = 0
262
+ const panel = ui.render(ui.MemoryPageMore, { pager: { pageKey: 'same', generation: 1, hasMore: true,
263
+ loading: false, data: { total: 100 }, more: () => { reads++ } }, loaded: 60, t: key => key })
264
+ await panel.flush()
265
+ const observer = ui.observers.at(-1)
266
+ observer.callback([{ isIntersecting: true }])
267
+ assert.equal(reads, 0, 'a layout-clamped scroll position is not another user continuation')
268
+ observer.callback([{ isIntersecting: false }]); observer.callback([{ isIntersecting: true }])
269
+ assert.equal(reads, 1)
270
+ panel.close()
271
+ })
272
+
273
+ test('MEMORY_CHANGED discards every old row before restarting and bounds restarts across pages', async () => {
274
+ for (const failure of [() => Object.assign(new Error('changed'), { code: 'MEMORY_CHANGED' }), () => new Error('rpc: MEMORY_CHANGED: changed')]) {
275
+ const ui = client(), calls = []
276
+ let generation = 0
277
+ const pager = ui.render(ui.useMemoryPages, { method: 'browseWall', rowsKey: 'items', payload: {},
278
+ call: async (_method, args) => {
279
+ calls.push(args)
280
+ if (args.offset) throw failure()
281
+ return { items: rows(0, 60, 'generation-' + ++generation + '-'), total: 100, snapshotRevision: 'r' + generation }
282
+ } })
283
+ let value = await pager.flush()
284
+ await value.more(); value = pager.draw()
285
+ assert.ok(value.data.items.every(row => row.id.startsWith('generation-2-')), 'no row from the abandoned snapshot may survive')
286
+ assert.equal(calls[2].offset, 0)
287
+ assert.equal(calls[2].snapshotRevision, undefined)
288
+ assert.equal(value.generation, 1, 'even equal-sized restart pages replace the browser scroll anchor')
289
+ await value.more(); value = pager.draw()
290
+ await value.more(); value = pager.draw()
291
+ assert.equal(generation, 3, 'only two automatic first-page restarts per query')
292
+ assert.equal(value.error, 'MEMORY_CHANGED')
293
+ assert.equal(value.data.items.length, 0)
294
+ const before = calls.length
295
+ await value.more()
296
+ assert.equal(calls.length, before, 'a stopped pager cannot restart from another observer callback')
297
+ await value.reload(); value = pager.draw()
298
+ assert.equal(generation, 4, 'an explicit reload begins a fresh retry budget')
299
+ pager.close()
300
+ }
301
+ })
302
+
303
+ test('duplicate rows, changed revisions and empty intermediate pages restart instead of hiding gaps', async () => {
304
+ for (const malformed of [
305
+ { items: rows(0, 20), total: 100, snapshotRevision: 'r1' },
306
+ { items: rows(60, 20), total: 100, snapshotRevision: 'r2' },
307
+ { items: [], total: 100, snapshotRevision: 'r1' },
308
+ { items: rows(60, 20), total: 101, snapshotRevision: 'r1' },
309
+ { items: rows(60, 20), total: 100, snapshotRevision: 'r1', offset: 61 },
310
+ ]) {
311
+ const ui = client(), calls = []
312
+ const pager = ui.render(ui.useMemoryPages, { method: 'browseWall', rowsKey: 'items', payload: {},
313
+ call: async (_method, args) => { calls.push(args); return args.offset ? malformed : { items: rows(0, 60), total: 100, snapshotRevision: 'r1' } } })
314
+ const value = await pager.flush()
315
+ await value.more()
316
+ assert.deepEqual(calls.map(args => args.offset), [0, 60, 0])
317
+ assert.equal(pager.draw().data.items.length, 60)
318
+ pager.close()
319
+ }
320
+ })
321
+
322
+ test('switching filters invalidates a pending response before effects commit, including unmount', async () => {
323
+ const ui = client(), old = defer(), next = defer(), calls = []
324
+ const props = { method: 'browseLibrary', rowsKey: 'files', payload: { libraryId: 'old' },
325
+ call: async (_method, args) => { calls.push(args); return args.libraryId === 'old' ? old.promise : next.promise } }
326
+ const pager = ui.render(ui.useMemoryPages, props)
327
+ await pager.flush()
328
+ pager.draw({ ...props, payload: { libraryId: 'new', query: 'unloaded body', domain: 'rp', status: 'archived' } })
329
+ old.resolve({ files: rows(0, 1, 'stale'), total: 1, snapshotRevision: 'old' })
330
+ await tick()
331
+ assert.equal(pager.draw().data.files.length, 0, 'old data is never published under the new selector')
332
+ await pager.flush()
333
+ assert.equal(calls.at(-1).query, 'unloaded body')
334
+ assert.equal(calls.at(-1).offset, 0)
335
+ pager.close()
336
+ next.resolve({ files: rows(0, 1, 'after-unmount'), total: 1, snapshotRevision: 'new' })
337
+ await tick()
338
+ assert.equal(pager.draw().data.files.length, 0)
339
+ })
340
+
341
+ test('search uses trailing debounce and cancels an obsolete timer', async () => {
342
+ const ui = client(), search = ui.render(props => ui.useDebouncedValue(props.value), { value: '' })
343
+ await search.flush()
344
+ search.draw({ value: 'first' }); await search.flush()
345
+ search.draw({ value: 'final' }); await search.flush()
346
+ assert.equal(search.value, '')
347
+ await new Promise(resolve => setTimeout(resolve, 280))
348
+ assert.equal(search.draw(), 'final')
349
+ search.close()
350
+ })
351
+
352
+ test('manual paging and observable errors remain usable without IntersectionObserver', async () => {
353
+ const ui = client()
354
+ delete ui.context.IntersectionObserver
355
+ let more = 0, reload = 0
356
+ const pager = { hasMore: true, loading: false, data: { total: 100 }, more: () => { more++ }, reload: () => { reload++ } }
357
+ const control = ui.render(ui.MemoryPageMore, { pager, loaded: 60, t: key => key })
358
+ let tree = await control.flush()
359
+ pick(tree, node => node.type?.name === 'Button')[0].props.onClick()
360
+ assert.equal(more, 1)
361
+ tree = control.draw({ pager: { ...pager, error: 'MEMORY_CHANGED' }, loaded: 0, t: key => key })
362
+ assert.equal(tree.props.role, 'alert')
363
+ assert.equal(tree.props.children[0], 'memoryPageChanged')
364
+ pick(tree, node => node.type?.name === 'Button')[0].props.onClick()
365
+ assert.equal(reload, 1)
366
+ control.close()
367
+ })
368
+
369
+ test('wall search is server-side even when the matching text is beyond its preview', async () => {
370
+ const ui = client(), calls = []
371
+ const props = { t: key => key, libraries: [{ id: 'lib-a' }], onOpen() {},
372
+ call: async (method, args) => {
373
+ calls.push({ method, args })
374
+ return { items: args.query ? [{ ...rows(0, 1)[0], title: 'short title', preview: 'unrelated first 180 characters', domain: 'rp' }] : rows(0, 60),
375
+ total: args.query ? 1 : 1000, snapshotRevision: args.query || 'all', domains: ['rp', 'coding'] }
376
+ } }
377
+ const wall = ui.render(ui.MemoryWallPanel, props)
378
+ let tree = await wall.flush()
379
+ assert.equal(calls.length, 1)
380
+ pick(tree, node => node.type === 'input' && node.props.type === 'search')[0].props.onChange({ target: { value: 'body-tail-needle' } })
381
+ await wall.flush()
382
+ assert.equal(calls.length, 1, 'no RPC on each keystroke')
383
+ await new Promise(resolve => setTimeout(resolve, 280))
384
+ tree = await wall.flush()
385
+ assert.equal(calls.at(-1).args.query, 'body-tail-needle')
386
+ assert.equal(pick(tree, node => node.props?.className === 'dshm-wall-item').length, 1, 'the client must not filter away a server hit by its preview')
387
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'wallFilterDomain')[0].props.onChange({ target: { value: 'rp' } })
388
+ tree = await wall.flush()
389
+ assert.equal(calls.at(-1).args.domain, 'rp')
390
+ assert.equal(calls.at(-1).args.offset, 0)
391
+ pick(tree, node => node.type === 'button' && String(node.props.children).startsWith('browseArchivedTab'))[0].props.onClick()
392
+ await wall.flush()
393
+ assert.equal(calls.at(-1).args.status, 'archived')
394
+ wall.close()
395
+ })
396
+
397
+ test('wall aggregate 403 falls back once to the first library and keeps the aggregate choice disabled', async () => {
398
+ const ui = client(), calls = []
399
+ const wall = ui.render(ui.MemoryWallPanel, { t: key => key, libraries: [{ id: 'lib-a' }], onOpen() {},
400
+ call: async (_method, args) => {
401
+ calls.push(args)
402
+ if (!args.libraryId) throw new Error('403 forbidden')
403
+ return { items: rows(0, 1), total: 1, snapshotRevision: 'single' }
404
+ } })
405
+ const tree = await wall.flush()
406
+ assert.deepEqual(calls.map(row => row.libraryId), [null, 'lib-a'])
407
+ assert.ok(calls.every(row => row.sessionId === undefined), 'aggregate and fallback retain management authorization')
408
+ const library = pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0]
409
+ assert.equal(library.props.value, 'lib-a')
410
+ assert.equal(pick(library, node => node.type === 'option' && node.props.value === '')[0].props.disabled, true)
411
+ assert.equal(pick(tree, node => node.props?.className === 'dshm-wall-item').length, 1)
412
+ wall.close()
413
+ })
414
+
415
+ test('lexicon domain selection keeps aggregate authorization and routes writes to the source book', async () => {
416
+ const ui = client(), calls = [], entry = { id: 'term-a', term: 'a', kind: 'term', meaning: 'meaning', domain: 'rp', libraryId: 'lib-b', status: 'active' }
417
+ const props = { t: key => key, sessionId: 'session-a', libraries: [{ id: 'lib-a' }, { id: 'lib-b' }],
418
+ call: async (method, args) => { calls.push({ method, args }); return method === 'lexiconList'
419
+ ? { items: [entry], total: 1, page: 1, pages: 1, domains: ['rp', 'coding'], domainCounts: { rp: 1, coding: 2 } } : {} } }
420
+ const panel = ui.render(ui.LexiconPanel, props)
421
+ let tree = await panel.flush()
422
+ pick(tree, node => node.type === 'select' && node.props.value === 'lib-a')[0].props.onChange({ target: { value: 'all' } })
423
+ tree = await panel.flush()
424
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'wallFilterDomain')[0].props.onChange({ target: { value: 'rp' } })
425
+ tree = await panel.flush()
426
+ const request = calls.filter(row => row.method === 'lexiconList').at(-1).args
427
+ assert.equal(request.libraryId, 'all')
428
+ assert.equal(request.sessionId, undefined)
429
+ assert.equal(request.domain, 'rp')
430
+ assert.equal(request.page, 1)
431
+ const domain = pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'wallFilterDomain')[0]
432
+ assert.equal(pick(domain, node => node.type === 'option').length, 3, 'domain candidates survive narrowing')
433
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'lexiconArchive')[0].props.onClick()
434
+ await tick()
435
+ const write = calls.find(row => row.method === 'lexiconArchive')
436
+ assert.equal(write.args.libraryId, 'lib-b')
437
+ assert.equal(write.args.sessionId, undefined)
438
+ panel.close()
439
+ })
440
+
441
+ test('lexicon ignores an old domain reply before effects commit and keeps the new request busy', async () => {
442
+ const ui = client(), old = defer(), next = defer(), calls = []
443
+ const answer = domain => ({ items: [{ id: domain, term: domain, kind: 'term', status: 'active', domain }],
444
+ total: 1, page: 1, pages: 1, domains: ['old', 'new'] })
445
+ const panel = ui.render(ui.LexiconPanel, { t: key => key, libraries: [{ id: 'lib-a' }],
446
+ call: async (_method, args) => { calls.push(args); return args.domain === 'old' ? old.promise : args.domain === 'new' ? next.promise : answer('initial') } })
447
+ let tree = await panel.flush()
448
+ const domain = () => pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'wallFilterDomain')[0]
449
+ domain().props.onChange({ target: { value: 'old' } })
450
+ tree = await panel.flush()
451
+ domain().props.onChange({ target: { value: 'new' } })
452
+ tree = panel.draw()
453
+ old.resolve(answer('old'))
454
+ await tick()
455
+ tree = await panel.flush()
456
+ assert.equal(calls.at(-1).domain, 'new')
457
+ assert.ok(!pick(tree, node => node.type === 'strong').some(node => node.props.children === 'old'), 'an old domain cannot repaint the new selector')
458
+ assert.equal(pick(tree, node => node.type?.name === 'Button' && node.props.children === 'logRefresh')[0].props.disabled, true,
459
+ 'the old finally block cannot release the new request busy state')
460
+ next.resolve(answer('new'))
461
+ await tick()
462
+ tree = await panel.flush()
463
+ assert.ok(pick(tree, node => node.type === 'strong').some(node => node.props.children === 'new'))
464
+ panel.close()
465
+ })
466
+
467
+ test('graph overview stays bounded, expands clusters with their library and domain, and returns to overview', async () => {
468
+ const ui = client(), calls = []
469
+ const props = { t: key => key, libraries: [{ id: 'lib-a' }],
470
+ call: async (method, args) => {
471
+ calls.push({ method, args })
472
+ if (method !== 'getGraph') return { items: [] }
473
+ return { overview: true, mode: args.clusterId ? 'detail' : 'clusters', revision: 'r1',
474
+ nodes: args.clusterId ? rows(0, 2) : [{ id: args.offset ? 'cluster-b' : 'cluster-a',
475
+ clusterId: args.offset ? 'cluster-b' : 'cluster-a', kind: 'cluster', count: 1000, title: 'representative' }],
476
+ edges: [], domains: ['rp'], totals: { nodes: 10000, edges: 9000, clusters: 10 }, nextOffset: args.clusterId || args.offset ? null : 200 }
477
+ } }
478
+ const graph = ui.render(ui.GraphStudioPanel, props)
479
+ let tree = await graph.flush()
480
+ assert.equal(calls.filter(row => row.method === 'getGraph').length, 1)
481
+ assert.equal(calls[0].args.overview, true)
482
+ assert.equal(calls[0].args.limit, 3000)
483
+ assert.equal(calls.filter(row => row.method === 'listEntities').length, 0, 'overview must not fetch the full entity sidecar')
484
+ const first = pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.nodes[0]
485
+ assert.equal(pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.overview, true, 'the renderer receives overview metadata')
486
+ pick(tree, node => node.type === 'button' && node.props.title === 'browseLoadMore')[0].props.onClick()
487
+ tree = await graph.flush()
488
+ assert.equal(calls.at(-1).args.offset, 200)
489
+ assert.equal(pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.nodes.length, 2)
490
+ assert.equal(pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.nodes[0], first, 'graph continuation retains existing nodes')
491
+ pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: ' RP ' } })
492
+ tree = await graph.flush()
493
+ pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.onFocus('cluster-a')
494
+ tree = await graph.flush()
495
+ const detail = calls.filter(row => row.method === 'getGraph').at(-1).args
496
+ assert.equal(detail.clusterId, 'cluster-a')
497
+ assert.equal(detail.libraryId, 'lib-a')
498
+ assert.equal(detail.domain, 'rp')
499
+ assert.equal(detail.limit, 3000)
500
+ const footer = pick(tree, node => node.type === 'footer')[0]
501
+ assert.ok(pick(footer, node => node.type === 'b').some(node => node.props.children === '10000'), 'full graph totals are not replaced by two loaded nodes')
502
+ pick(tree, node => node.type === 'button' && node.props.title === 'gsOverview')[0].props.onClick()
503
+ tree = await graph.flush()
504
+ assert.equal(calls.filter(row => row.method === 'getGraph').at(-1).args.clusterId, undefined)
505
+ assert.equal(pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.nodes[0].kind, 'cluster')
506
+ graph.close()
507
+ })
508
+
509
+ test('classic canvas automatically completes pages and keeps the full graph while zooming', async () => {
510
+ const ui = client(), calls = []
511
+ const nodes = Array.from({ length: 3405 }, (_, i) => ({ id: `classic-${i}`, title: `Memory ${i}`, kind: 'memory' }))
512
+ const edges = nodes.slice(1).map((node, i) => ({ from: nodes[i].id, to: node.id, kind: 'relation' }))
513
+ const model = buildGraphOverview({ nodes, edges, domains: ['rp'] }, { revision: 'complete-r1' })
514
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, libraries: [{ id: 'lib-a' }], sessionId: 'classic-session',
515
+ call: async (method, args) => {
516
+ calls.push({ method, args })
517
+ assert.equal(method, 'getGraph'); assert.equal(args.layout, 'classic'); assert.equal(args.sessionId, 'classic-session')
518
+ return selectGraphOverview(model, args)
519
+ } })
520
+ let tree = await panel.flush()
521
+ const canvas = () => pick(tree, node => node.type?.name === 'GraphCanvas')[0]
522
+ assert.equal(canvas().props.graph.mode, 'classic')
523
+ assert.equal(canvas().props.graph.nodes.length, 3405)
524
+ assert.equal(canvas().props.graph.edges.length, 3404)
525
+ assert.equal(canvas().props.graph.nextOffset, null)
526
+ assert.deepEqual(calls.map(row => row.args.offset), [0, 3000])
527
+ const count = calls.length
528
+ canvas().props.onViewport({ zoom: 2, bbox: { minX: 0, minY: 0, maxX: 100, maxY: 100 } })
529
+ await new Promise(resolve => setTimeout(resolve, 280))
530
+ tree = await panel.flush()
531
+ assert.equal(calls.length, count, 'zoom must not fetch and replace the complete graph with a viewport subset')
532
+ assert.equal(canvas().props.graph.nodes.length, 3405)
533
+ panel.close()
534
+ })
535
+
536
+ test('classic all-library and global views complete their pages and preserve node ownership', async () => {
537
+ const nodes = rows(0, 205), edges = nodes.slice(1).map((node, i) => ({ from: nodes[i].id, to: node.id, kind: 'relation' }))
538
+ const model = buildGraphOverview({ nodes, edges }, { revision: 'all-pages-r1' })
539
+ for (const libraries of [[], [{ id: 'lib-a' }, { id: 'lib-b' }]]) {
540
+ const ui = client(), calls = []
541
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, libraries, initialLibraryId: '__global__',
542
+ sessionId: 'aggregate-session', call: async (method, args) => {
543
+ calls.push({ method, args })
544
+ assert.equal(method, 'getGraph'); assert.equal(args.layout, 'classic')
545
+ if (libraries.length) assert.equal(args.sessionId, undefined, 'aggregate reads use management authorization')
546
+ else assert.equal(args.scope, 'global')
547
+ return selectGraphOverview(model, args)
548
+ } })
549
+ const tree = await panel.flush(), data = pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph
550
+ assert.equal(data.mode, 'classic'); assert.equal(data.nextOffset, null)
551
+ assert.equal(data.nodes.length, 205 * (libraries.length || 1))
552
+ assert.equal(data.edges.length, 204 * (libraries.length || 1))
553
+ assert.equal(new Set(data.nodes.map(node => node.id)).size, data.nodes.length)
554
+ assert.ok(data.nodes.every(node => !Number.isFinite(node.x) && !Number.isFinite(node.y)))
555
+ for (const library of libraries) {
556
+ assert.equal(data.nodes.filter(node => node.libraryId === library.id).length, 205)
557
+ assert.ok(data.nodes.filter(node => node.libraryId === library.id).every(node => node.id === JSON.stringify([library.id, node.rawId])))
558
+ assert.deepEqual(calls.filter(row => row.args.libraryId === library.id).map(row => row.args.offset), [0])
559
+ }
560
+ panel.close()
561
+ }
562
+ })
563
+
564
+ test('merged overview expands a cluster in its source library and ignores old filter replies', async () => {
565
+ const ui = client(), pending = defer(), calls = []
566
+ const props = { t: key => key, libraries: [{ id: 'lib-a' }, { id: 'lib-b' }],
567
+ call: async (method, args) => {
568
+ calls.push({ method, args })
569
+ if (args.domain === 'old') return pending.promise
570
+ return { overview: true, mode: args.clusterId ? 'detail' : 'clusters', revision: 'r1',
571
+ nodes: [{ id: 'shared', clusterId: 'shared', kind: args.clusterId ? 'memory' : 'cluster', title: 'new-domain', x: 0, y: 0,
572
+ bbox: { minX: -50, maxX: 50, minY: -50, maxY: 50 } }],
573
+ edges: [], domains: ['old', 'new'], bbox: { minX: -100, maxX: 100, minY: -100, maxY: 100 },
574
+ totals: { nodes: 1000, edges: 900, clusters: 1 }, nextOffset: null }
575
+ } }
576
+ const graph = ui.render(ui.GraphStudioPanel, props)
577
+ let tree = await graph.flush()
578
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: '__global__' } })
579
+ tree = await graph.flush()
580
+ const canvas = () => pick(tree, node => node.type?.name === 'GraphCanvas')[0]
581
+ assert.equal(canvas().props.graph.nodes.length, 2)
582
+ const [a, b] = canvas().props.graph.nodes
583
+ assert.ok(a.bbox.maxX < b.bbox.minX, 'different libraries cannot share an overlapping world origin')
584
+ canvas().props.onFocus(b.id)
585
+ tree = await graph.flush()
586
+ assert.equal(calls.at(-1).args.libraryId, 'lib-b')
587
+ assert.equal(calls.at(-1).args.clusterId, 'shared', 'namespaced canvas ids never leak into cluster RPCs')
588
+ pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: 'old' } })
589
+ tree = await graph.flush()
590
+ pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: 'new' } })
591
+ graph.draw()
592
+ pending.resolve({ overview: true, mode: 'clusters', nodes: [{ id: 'stale', title: 'stale-domain' }], edges: [], domains: [] })
593
+ await tick()
594
+ tree = await graph.flush()
595
+ assert.ok(canvas().props.graph.nodes.every(node => node.title === 'new-domain'))
596
+ assert.equal(calls.at(-1).args.domain, 'new')
597
+ graph.close()
598
+ })
599
+
600
+ test('graph viewport reads debounce, preserve credentials and reject replies as soon as another gesture starts', async () => {
601
+ const ui = client(), pending = defer(), calls = []
602
+ const response = args => ({ overview: true, mode: args.zoom >= 1 ? 'detail' : 'clusters', revision: 'r1',
603
+ nodes: [{ id: args.bbox ? 'viewport-' + args.bbox.minX : 'cluster', kind: args.zoom >= 1 ? 'memory' : 'cluster', x: 0, y: 0 }],
604
+ edges: [], domains: ['general'], totals: { nodes: 10000, edges: 9000 }, nextOffset: args.bbox ? 3000 : null })
605
+ const props = { t: key => key, sessionId: 'bound-session', libraries: [{ id: 'lib-a' }],
606
+ call: async (method, args) => { calls.push({ method, args }); return args.bbox?.minX === 20 ? pending.promise : response(args) } }
607
+ const panel = ui.render(ui.GraphStudioPanel, props)
608
+ let tree = await panel.flush()
609
+ const canvas = () => pick(tree, node => node.type?.name === 'GraphCanvas')[0]
610
+ const move = (minX, zoom = 2) => canvas().props.onViewport({ zoom, bbox: { minX, minY: -50, maxX: minX + 100, maxY: 50 } })
611
+ move(10); move(20)
612
+ await panel.flush()
613
+ assert.equal(calls.length, 1, 'camera events wait for the trailing edge')
614
+ await new Promise(resolve => setTimeout(resolve, 280))
615
+ tree = await panel.flush()
616
+ assert.equal(calls.length, 2, 'a burst sends only its latest bbox')
617
+ assert.equal(calls[1].args.bbox.minX, 20)
618
+ assert.equal(calls[1].args.sessionId, 'bound-session')
619
+ assert.equal(calls[1].args.libraryId, 'lib-a')
620
+ assert.equal(calls[1].args.limit, 3000)
621
+ move(30)
622
+ panel.draw({ ...props, stamp: 'heartbeat-during-gesture' })
623
+ await panel.flush()
624
+ assert.equal(calls.length, 2, 'a heartbeat inside the debounce window cannot refetch the old viewport')
625
+ pending.resolve(response({ zoom: 2, bbox: { minX: 20 } }))
626
+ await tick()
627
+ tree = await panel.flush()
628
+ assert.ok(!canvas().props.graph.nodes.some(node => node.id === 'viewport-20'), 'a newer gesture invalidates old data before its timer fires')
629
+ await new Promise(resolve => setTimeout(resolve, 280))
630
+ tree = await panel.flush()
631
+ assert.equal(canvas().props.graph.nodes[0].id, 'viewport-30')
632
+ assert.equal(canvas().props.graph.nextOffset, null, 'near views stay bounded instead of accumulating every viewport page')
633
+ const before = calls.length
634
+ await panel.flush(); await new Promise(resolve => setTimeout(resolve, 280)); await panel.flush()
635
+ assert.equal(calls.length, before, 'publishing data cannot schedule another camera read')
636
+ move(30, .5)
637
+ await new Promise(resolve => setTimeout(resolve, 280))
638
+ tree = await panel.flush()
639
+ assert.equal(canvas().props.graph.mode, 'clusters')
640
+ assert.equal(calls.at(-1).args.limit, 3000)
641
+ move(50)
642
+ panel.close()
643
+ await new Promise(resolve => setTimeout(resolve, 280))
644
+ assert.equal(calls.length, before + 1, 'unmount cancels a pending camera timer')
645
+ })
646
+
647
+ test('merged viewport converts world coordinates back to each source book and shares a 3000 node budget', async () => {
648
+ const ui = client(), calls = []
649
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, sessionId: 'single-book-credential', libraries: [{ id: 'lib-a' }, { id: 'lib-b' }],
650
+ call: async (_method, args) => { calls.push(args); return { overview: true, mode: args.zoom >= 1 ? 'detail' : 'clusters', revision: 'r1',
651
+ nodes: [{ id: 'same', kind: args.zoom >= 1 ? 'memory' : 'cluster', x: 0, y: 0 }], edges: [], domains: ['general'],
652
+ bbox: { minX: -100, maxX: 100, minY: -100, maxY: 100 }, totals: { nodes: 1000, edges: 900 }, nextOffset: null } } })
653
+ let tree = await panel.flush()
654
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: '__global__' } })
655
+ tree = await panel.flush()
656
+ const canvas = () => pick(tree, node => node.type?.name === 'GraphCanvas')[0]
657
+ const b = canvas().props.graph.nodes.find(node => node.libraryId === 'lib-b')
658
+ const shift = b.x
659
+ canvas().props.onViewport({ zoom: 2, bbox: { minX: shift - 90, maxX: shift + 50, minY: -50, maxY: 50 } })
660
+ await new Promise(resolve => setTimeout(resolve, 280))
661
+ tree = await panel.flush()
662
+ assert.equal(calls.at(-1).libraryId, 'lib-b', 'an offscreen book does not get a detail read')
663
+ assert.equal(calls.at(-1).bbox.minX, -90)
664
+ assert.equal(calls.at(-1).bbox.maxX, 50)
665
+ assert.equal(calls.at(-1).sessionId, undefined, 'aggregate management reads never borrow single-book credentials')
666
+ assert.equal(canvas().props.graph.nodes[0].x, shift, 'the result is translated back into the unchanged merged world')
667
+ assert.equal(canvas().props.graph.totals.nodes, 2000, 'offscreen libraries retain their full-graph totals')
668
+ canvas().props.onViewport({ zoom: 2, bbox: { minX: 0, maxX: 700, minY: -50, maxY: 50 } })
669
+ await new Promise(resolve => setTimeout(resolve, 280))
670
+ tree = await panel.flush()
671
+ assert.equal(calls.at(-1).limit + calls.at(-2).limit, 3000)
672
+ assert.equal(calls.at(-1).bbox.minX, -shift)
673
+ panel.close()
674
+ })
675
+
676
+ test('GraphCanvas does not echo programmatic update or navigation fit as a user viewport gesture', async () => {
677
+ const ui = client(), gestures = [], updates = []
678
+ let handlers
679
+ ui.context.window.DshMemuGraph = { createGraphView(_canvas, options) {
680
+ handlers = options
681
+ return { update(value) { updates.push(value); options.onViewport({ zoom: 2, bbox: { minX: 0, minY: 0, maxX: 100, maxY: 100 } }) },
682
+ configure() {}, fit() { options.onViewport({ zoom: .5, bbox: { minX: 0, minY: 0, maxX: 200, maxY: 200 } }) }, dispose() {} }
683
+ } }
684
+ const props = { graph: { nodes: [], edges: [], fitKey: 'overview' }, focus: '', onFocus() {}, t: key => key, onViewport: value => gestures.push(value) }
685
+ const canvas = ui.render(ui.GraphCanvas, props)
686
+ pick(canvas.value, node => node.type === 'canvas')[0].props.ref.current = { getContext() {} }
687
+ await canvas.flush()
688
+ assert.ok(updates.length > 0)
689
+ assert.equal(gestures.length, 0)
690
+ canvas.draw({ ...props, graph: { nodes: [], edges: [], fitKey: 'cluster' } })
691
+ await canvas.flush()
692
+ assert.equal(gestures.length, 0, 'navigation fit must not turn cluster expansion into a bbox request')
693
+ handlers.onViewport({ zoom: 3, bbox: { minX: 1, minY: 2, maxX: 3, maxY: 4 } })
694
+ assert.equal(gestures.length, 1, 'actual camera events are forwarded')
695
+ canvas.close()
696
+ })
697
+
698
+ test('graph search debounces RPC, drops old raw-query replies and searches beyond the current viewport', async () => {
699
+ const ui = client(), oldRead = defer(), calls = []
700
+ const response = args => ({ overview: true, mode: args.query || args.bbox ? 'detail' : 'clusters', revision: 'r1',
701
+ nodes: args.query ? [{ id: 'source-' + args.offset, kind: 'memory', title: 'Unmatched endpoint' },
702
+ { id: 'target-' + args.offset, kind: 'person', title: 'Another endpoint' }] : [{ id: 'cluster', kind: 'cluster', clusterId: 'cluster' }],
703
+ edges: args.query ? [{ from: 'source-' + args.offset, to: 'target-' + args.offset, kind: 'event', note: args.query }] : [],
704
+ domains: ['general'], nextOffset: args.query && !args.offset ? 3000 : null })
705
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, sessionId: 'session-a', libraries: [{ id: 'lib-a' }],
706
+ call: async (method, args) => { calls.push({ method, args }); return args.query === 'old' ? oldRead.promise : response(args) } })
707
+ let tree = await panel.flush()
708
+ const canvas = () => pick(tree, node => node.type?.name === 'GraphCanvas')[0]
709
+ const search = value => pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsSearch')[0].props.onChange({ target: { value } })
710
+ assert.equal(pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsSearch')[0].props.maxLength, 256)
711
+ canvas().props.onViewport({ zoom: .5, bbox: { minX: 10, minY: 20, maxX: 110, maxY: 120 } })
712
+ await new Promise(resolve => setTimeout(resolve, 280)); tree = await panel.flush()
713
+ const cameraScope = canvas().props.graph.cameraScope, oldFitKey = canvas().props.graph.fitKey
714
+ search('old'); await panel.flush()
715
+ assert.equal(calls.at(-1).args.query, undefined)
716
+ await new Promise(resolve => setTimeout(resolve, 280)); tree = await panel.flush()
717
+ const oldArgs = calls.at(-1).args
718
+ assert.equal(oldArgs.query, 'old')
719
+ assert.equal(oldArgs.limit, 3000)
720
+ assert.equal(oldArgs.sessionId, 'session-a')
721
+ for (const key of ['bbox', 'zoom', 'clusterId']) assert.equal(oldArgs[key], undefined, key + ' cannot hide a search match')
722
+ search('new'); tree = await panel.flush()
723
+ oldRead.resolve({ ...response({ query: 'old', offset: 0 }), nodes: [{ id: 'stale', kind: 'memory' }] })
724
+ await tick(); tree = await panel.flush()
725
+ assert.equal(canvas().props.graph.nodes.some(node => node.id === 'stale'), false, 'raw input invalidates the old result before the new debounce expires')
726
+ assert.equal(calls.filter(row => row.args.query).length, 1)
727
+ await new Promise(resolve => setTimeout(resolve, 280)); tree = await panel.flush()
728
+ assert.equal(calls.at(-1).args.query, 'new')
729
+ assert.equal(canvas().props.graph.edges.length, 1, 'edge-note matches keep endpoints with nonmatching titles')
730
+ assert.equal(canvas().props.graph.cameraScope, cameraScope)
731
+ assert.notEqual(canvas().props.graph.fitKey, oldFitKey)
732
+ const before = calls.length
733
+ canvas().props.onViewport({ zoom: 3, bbox: { minX: 999, minY: 999, maxX: 1000, maxY: 1000 } })
734
+ await new Promise(resolve => setTimeout(resolve, 280)); tree = await panel.flush()
735
+ assert.equal(calls.length, before, 'search result fitting and gestures never start viewport reads')
736
+ pick(tree, node => node.type === 'button' && node.props.title === 'browseLoadMore')[0].props.onClick()
737
+ tree = await panel.flush()
738
+ assert.equal(calls.at(-1).args.query, 'new')
739
+ assert.equal(calls.at(-1).args.offset, 3000)
740
+ assert.equal(canvas().props.graph.nodes.length, 4)
741
+ search(''); await panel.flush()
742
+ await new Promise(resolve => setTimeout(resolve, 280)); tree = await panel.flush()
743
+ assert.equal(calls.at(-1).args.query, undefined)
744
+ assert.equal(calls.at(-1).args.offset, 0)
745
+ assert.equal(calls.at(-1).args.bbox.minX, 10, 'clearing search restores the prior viewport instead of the search camera')
746
+ assert.equal(canvas().props.graph.fitKey, oldFitKey)
747
+ assert.equal(canvas().props.graph.cameraScope, cameraScope)
748
+ panel.close()
749
+ })
750
+
751
+ test('merged graph search leaves an expanded library branch and shares the detail budget without session credentials', async () => {
752
+ const ui = client(), calls = []
753
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, sessionId: 'single-book-only', libraries: [{ id: 'lib-a' }, { id: 'lib-b' }],
754
+ call: async (method, args) => { calls.push({ method, args }); return { overview: true, revision: 'r1', mode: args.query ? 'detail' : 'clusters',
755
+ nodes: [{ id: 'cluster', kind: 'cluster', clusterId: 'cluster', x: 0, y: 0 }], edges: [], domains: [],
756
+ bbox: { minX: -10, maxX: 10, minY: -10, maxY: 10 }, nextOffset: null } } })
757
+ let tree = await panel.flush()
758
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: '__global__' } })
759
+ tree = await panel.flush()
760
+ const canvas = () => pick(tree, node => node.type?.name === 'GraphCanvas')[0]
761
+ canvas().props.onFocus(canvas().props.graph.nodes.find(node => node.libraryId === 'lib-b').id)
762
+ tree = await panel.flush()
763
+ const before = calls.length
764
+ pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsSearch')[0].props.onChange({ target: { value: 'evidence' } })
765
+ await panel.flush(); await new Promise(resolve => setTimeout(resolve, 280)); tree = await panel.flush()
766
+ const reads = calls.slice(before)
767
+ assert.deepEqual(reads.map(row => row.args.libraryId).sort(), ['lib-a', 'lib-b'])
768
+ assert.equal(reads.reduce((sum, row) => sum + row.args.limit, 0), 3000)
769
+ assert.ok(reads.every(row => row.args.query === 'evidence' && !row.args.clusterId && !row.args.bbox && !row.args.sessionId))
770
+ panel.close()
771
+ })
772
+
773
+ test('GraphCanvas saves the overview camera before search and restores it without echoing a viewport request', async () => {
774
+ const ui = client(), restored = [], gestures = []
775
+ const viewport = { zoom: .45, bbox: { minX: -100, minY: -50, maxX: 300, maxY: 250 } }
776
+ let fits = 0
777
+ ui.context.window.DshMemuGraph = { createGraphView(_canvas, options) {
778
+ return { update() {}, configure() {}, viewport: () => viewport, fit() { fits++ },
779
+ setViewport(value) { restored.push(value); options.onViewport(value) }, dispose() {} }
780
+ } }
781
+ const props = { graph: { nodes: [], edges: [], fitKey: 'overview', cameraScope: 'library-domain' },
782
+ focus: '', onFocus() {}, t: key => key, onViewport: value => gestures.push(value) }
783
+ const canvas = ui.render(ui.GraphCanvas, props)
784
+ pick(canvas.value, node => node.type === 'canvas')[0].props.ref.current = { getContext() {} }
785
+ await canvas.flush()
786
+ canvas.draw({ ...props, graph: { ...props.graph, fitKey: 'query-a', searchActive: true } }); await canvas.flush()
787
+ canvas.draw({ ...props, graph: { ...props.graph, fitKey: 'query-b', searchActive: true } }); await canvas.flush()
788
+ canvas.draw(props); await canvas.flush()
789
+ assert.equal(fits, 2, 'each distinct search fits its matches')
790
+ assert.deepEqual(restored, [viewport])
791
+ assert.equal(gestures.length, 0)
792
+ canvas.close()
793
+ })
794
+
795
+ test('graph management reloads a committed archive even when permanent deletion is denied', async () => {
796
+ const ui = client(), calls = [], deletion = defer()
797
+ let archived = false
798
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, libraries: [{ id: 'lib-a' }],
799
+ call: async (method, args) => {
800
+ calls.push({ method, args })
801
+ if (method === 'getGraph') return managementGraph([{ id: 'memory-a', kind: 'memory', status: archived ? 'archived' : 'active' }], args, archived ? 'r2' : 'r1')
802
+ if (method === 'archiveMemory') { archived = true; return { ok: true } }
803
+ if (method === 'deleteMemory') return deletion.promise
804
+ return {}
805
+ } })
806
+ let tree = await panel.flush()
807
+ action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
808
+ const reads = calls.filter(row => row.method === 'getGraph' && Object.hasOwn(row.args, 'includeOrphans')).length
809
+ managerRows(tree)[0].props.onClick()
810
+ tree = await panel.flush()
811
+ pick(tree, node => node.type === 'button' && node.props['aria-label'] === 'gsRemoveNode')[0].props.onClick()
812
+ tree = await panel.flush()
813
+ assert.equal(calls.filter(row => row.method === 'archiveMemory').length, 0, 'first confirmation cannot archive')
814
+ pick(tree, node => node.type === 'button' && node.props['aria-label'] === 'gsRemoveNode')[0].props.onClick()
815
+ tree = await panel.flush()
816
+ assert.equal(archived, true)
817
+ assert.deepEqual(calls.filter(row => ['archiveMemory', 'deleteMemory'].includes(row.method)).map(row => row.method), ['archiveMemory', 'deleteMemory'])
818
+ assert.ok(calls.filter(row => row.method === 'getGraph' && Object.hasOwn(row.args, 'includeOrphans')).length > reads,
819
+ 'the committed archive refreshes bounded manager data before delete completes')
820
+ assert.deepEqual(managerRows(tree).map(row => row.props.key), ['memory-a'], 'management retains archived history')
821
+ assert.equal(pick(managerRows(tree), node => node.type === 'span' && node.props.children === 'stArchived').length, 1)
822
+ deletion.reject(new Error('delete forbidden')); await tick(); tree = await panel.flush()
823
+ assert.deepEqual(managerRows(tree).map(row => row.props.key), ['memory-a'])
824
+ assert.equal(pick(managerRows(tree), node => node.type === 'span' && node.props.children === 'stArchived').length, 1)
825
+ assert.ok(pick(tree, node => node.props?.children === 'delete forbidden').length, 'the second-step failure remains visible')
826
+ assert.equal(action(tree, 'gsRemoveNode').props.disabled, false, 'the failed delete releases its own busy state')
827
+ panel.close()
828
+ })
829
+
830
+ test('bounded manager displays memory lifecycle status without treating it as entity confirmation', async () => {
831
+ const ui = client()
832
+ const statuses = ['active', 'archived', 'suppressed', 'superseded', 'pending_review', 'expired']
833
+ const labels = ['stActive', 'stArchived', 'stSuppressed', 'stSuperseded', 'stPendingReview', 'stExpired']
834
+ const nodes = statuses.map(status => ({ id: 'memory-' + status, kind: 'memory', status }))
835
+ nodes.push({ id: 'memory-legacy', kind: 'memory' }, { id: 'entity-confirmed', kind: 'person', status: 'confirmed' })
836
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, libraries: [{ id: 'lib-a' }],
837
+ call: async (method, args) => method === 'getGraph' ? managementGraph(nodes, args) : {} })
838
+ let tree = await panel.flush()
839
+ action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
840
+ for (const [index, status] of statuses.entries()) {
841
+ const row = managerRows(tree).find(row => row.props.key === 'memory-' + status)
842
+ assert.equal(pick(row, node => node.type === 'span' && node.props.children === labels[index]).length, 1, status)
843
+ assert.equal(pick(row, node => node.props?.children === 'gsConfirmed').length, 0, status + ' is not an entity confirmation')
844
+ }
845
+ const legacy = managerRows(tree).find(row => row.props.key === 'memory-legacy')
846
+ assert.equal(pick(legacy, node => node.type === 'span' && node.props.children === 'stActive').length, 1)
847
+ const entity = managerRows(tree).find(row => row.props.key === 'entity-confirmed')
848
+ assert.equal(pick(entity, node => node.type === 'span' && node.props.children === 'gsConfirmed').length, 1)
849
+ panel.close()
850
+ })
851
+
852
+ test('graph edit reads cannot reopen after selection, library, add-form changes or unmount', async () => {
853
+ for (const change of ['selection', 'library', 'add', 'unmount']) {
854
+ const ui = client(), gate = defer(), calls = []
855
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, libraries: [{ id: 'lib-a' }, { id: 'lib-b' }],
856
+ call: async (method, args) => {
857
+ calls.push({ method, args })
858
+ if (method === 'getGraph') return managementGraph(['a', 'b'].map(id => ({ id, kind: 'memory' })), args)
859
+ if (method === 'getMemory') return gate.promise
860
+ return {}
861
+ } })
862
+ let tree = await panel.flush()
863
+ action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
864
+ const manageRow = id => pick(tree, node => node.props?.className?.startsWith('dshm-gs-mgr-row') && node.props.key === id)[0]
865
+ manageRow('a').props.onClick(); tree = await panel.flush()
866
+ pick(tree, node => node.type === 'button' && node.props['aria-label'] === 'gsEditNode')[0].props.onClick()
867
+ tree = await panel.flush()
868
+ assert.equal(calls.filter(row => row.method === 'getMemory').length, 1)
869
+ if (change === 'selection') manageRow('b').props.onClick()
870
+ if (change === 'library') pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: 'lib-b' } })
871
+ if (change === 'add') pick(tree, node => node.type === 'button' && node.props.title === 'gsAddNode')[0].props.onClick()
872
+ if (change === 'unmount') panel.close()
873
+ else tree = panel.draw()
874
+ gate.resolve({ entry: { title: 'OLD A', content: 'Old complete body', layer: 'long_term' } })
875
+ await tick()
876
+ if (change === 'unmount') {
877
+ assert.equal(panel.dirty, false, 'an unmounted read must not schedule state updates')
878
+ continue
879
+ }
880
+ tree = await panel.flush()
881
+ assert.equal(pick(tree, node => node.type === 'button' && node.props.children === 'save').length, 0, change + ' cancels the stale save target')
882
+ assert.equal(pick(tree, node => node.type === 'input' && node.props.value === 'OLD A').length, 0)
883
+ panel.close()
884
+ }
885
+ })
886
+
887
+ test('an old graph save completion cannot close a new node draft or release its busy state', async () => {
888
+ const ui = client(), gate = defer(), writes = []
889
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, libraries: [{ id: 'lib-a' }],
890
+ call: async (method, args) => {
891
+ if (method === 'getGraph') return managementGraph(['a', 'b'].map(id => ({ id, kind: 'memory' })), args)
892
+ if (method === 'getMemory') return { entry: { title: args.id, content: 'Full body ' + args.id, layer: 'long_term' } }
893
+ if (method === 'updateMemory') { writes.push(args); return gate.promise }
894
+ return {}
895
+ } })
896
+ let tree = await panel.flush()
897
+ action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
898
+ const row = id => pick(tree, node => node.props?.className?.startsWith('dshm-gs-mgr-row') && node.props.key === id)[0]
899
+ const edit = () => pick(tree, node => node.type === 'button' && node.props['aria-label'] === 'gsEditNode')[0].props.onClick()
900
+ row('a').props.onClick(); tree = await panel.flush()
901
+ edit(); tree = await panel.flush()
902
+ pick(tree, node => node.type === 'button' && node.props.children === 'save')[0].props.onClick()
903
+ tree = await panel.flush()
904
+ row('b').props.onClick(); tree = await panel.flush()
905
+ edit(); tree = await panel.flush()
906
+ pick(tree, node => node.type === 'textarea' && node.props['aria-label'] === 'memoryContent')[0].props.onChange({ target: { value: 'UNSAVED B' } })
907
+ tree = await panel.flush()
908
+ gate.resolve({ ok: true }); await tick(); tree = await panel.flush()
909
+ assert.deepEqual(writes.map(args => args.id), ['a'])
910
+ assert.equal(pick(tree, node => node.type === 'textarea' && node.props['aria-label'] === 'memoryContent')[0].props.value, 'UNSAVED B')
911
+ assert.equal(pick(tree, node => node.type === 'button' && node.props.children === 'save')[0].props.disabled, false)
912
+ panel.close()
913
+ })
914
+
915
+ test('unlinked entities remain discoverable, editable and explicitly deletable without entering the default canvas', async () => {
916
+ const ui = client(), calls = []
917
+ let entity = null
918
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, libraries: [{ id: 'lib-a' }], call: async (method, args) => {
919
+ calls.push({ method, args })
920
+ if (method === 'getGraph') return managementGraph(entity && args.includeOrphans ? [{ ...entity, title: entity.name, degree: 0 }] : [], args)
921
+ if (method === 'createEntity') return entity = { id: 'ent-unique', name: args.name, kind: 'person', status: 'confirmed', aliases: ['Existing alias'] }
922
+ if (method === 'listEntities') { assert.equal(args.entityId, entity.id); return { items: [entity], total: 1 } }
923
+ if (method === 'renameEntity') { entity = { ...entity, name: args.name, aliases: args.aliases }; return entity }
924
+ if (method === 'deleteEntity') { assert.equal(args.entityId, entity.id); entity = null; return { ok: true } }
925
+ throw new Error(method)
926
+ } })
927
+ let tree = await panel.flush()
928
+ assert.equal(calls.length, 1, 'folded management performs no additional reads')
929
+ action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
930
+ assert.equal(managerRows(tree).length, 0)
931
+ assert.equal(pick(tree, node => node.props?.role === 'note' && node.props.children === 'orphanPruneHint').length, 0)
932
+ action(tree, 'gsAddNode').props.onClick(); tree = await panel.flush()
933
+ action(tree, 'gsNodeEntity').props.onClick(); tree = await panel.flush()
934
+ pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'entityName')[0].props.onChange({ target: { value: 'Unique orphan' } })
935
+ tree = await panel.flush(); action(tree, 'add').props.onClick(); tree = await panel.flush()
936
+ assert.equal(managerRows(tree).length, 1)
937
+ assert.equal(managerRows(tree)[0].props.key, 'ent-unique')
938
+ assert.equal(pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsIncludeOrphans')[0].props.checked, true)
939
+ assert.equal(pick(tree, node => node.props?.role === 'note' && node.props.children === 'orphanPruneHint').length, 1)
940
+ assert.ok(calls.some(row => row.method === 'getGraph' && row.args.focusId === 'ent-unique' && row.args.depth === 0))
941
+ assert.equal(pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.nodes.length, 0)
942
+ action(tree, 'refresh').props.onClick(); tree = await panel.flush()
943
+ assert.equal(managerRows(tree)[0].props.key, entity.id, 'refresh reads the persisted ID rather than an optimistic row')
944
+ action(tree, 'gsEditNode').props.onClick(); tree = await panel.flush()
945
+ assert.equal(pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'entityAliases')[0].props.value, 'Existing alias')
946
+ pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'entityName')[0].props.onChange({ target: { value: 'Renamed orphan' } })
947
+ tree = await panel.flush(); action(tree, 'save').props.onClick(); tree = await panel.flush()
948
+ assert.equal(entity.name, 'Renamed orphan')
949
+ assert.deepEqual(Array.from(entity.aliases), ['Existing alias'])
950
+ assert.equal(action(tree, 'gsRemoveNode').props.disabled, false)
951
+ action(tree, 'gsRemoveNode').props.onClick(); tree = await panel.flush()
952
+ assert.equal(calls.filter(row => row.method === 'deleteEntity').length, 0)
953
+ action(tree, 'gsRemoveNode').props.onClick(); tree = await panel.flush()
954
+ assert.equal(calls.filter(row => row.method === 'deleteEntity').length, 1)
955
+ assert.equal(managerRows(tree).length, 0)
956
+ assert.equal(pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.nodes.length, 0)
957
+ panel.close()
958
+ })
959
+
960
+ test('management replaces 60 row pages, restarts a changed revision and stops after two automatic restarts', async () => {
961
+ const ui = client(), calls = [], all = rows(0, 125).map(row => ({ ...row, kind: 'memory', title: row.id }))
962
+ let revision = 'r1', changeOnNext = false, churn = false, serial = 0
963
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, libraries: [{ id: 'lib-a' }], call: async (method, args) => {
964
+ calls.push({ method, args })
965
+ if (changeOnNext && args.offset === 60) { changeOnNext = false; revision = 'r2' }
966
+ return managementGraph(all, args, churn ? 'churn-' + serial++ : revision)
967
+ } })
968
+ let tree = await panel.flush()
969
+ action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
970
+ assert.equal(managerRows(tree).length, 60)
971
+ const firstIds = managerRows(tree).map(row => row.props.key)
972
+ const before = calls.length
973
+ await tick(); tree = await panel.flush(); assert.equal(calls.length, before, 'no background draining')
974
+ action(tree, 'gsManagerNext').props.onClick(); tree = await panel.flush()
975
+ assert.equal(managerRows(tree).length, 60)
976
+ assert.ok(managerRows(tree).every(row => !firstIds.includes(row.props.key)))
977
+ action(tree, 'gsManagerPrevious').props.onClick(); tree = await panel.flush()
978
+ assert.deepEqual(managerRows(tree).map(row => row.props.key), firstIds)
979
+ changeOnNext = true
980
+ action(tree, 'gsManagerNext').props.onClick(); tree = await panel.flush()
981
+ assert.deepEqual(managerRows(tree).map(row => row.props.key), firstIds, 'changed revisions restart at zero instead of blending snapshots')
982
+ assert.equal(action(tree, 'gsManagerPrevious').props.disabled, true)
983
+ assert.ok(calls.filter(row => Object.hasOwn(row.args, 'includeOrphans')).every(row => row.args.limit === 1 || row.args.limit === 60))
984
+ churn = true
985
+ const churnStart = calls.length
986
+ action(tree, 'refresh').props.onClick(); tree = await panel.flush()
987
+ assert.equal(calls.length - churnStart, 6, 'metadata/detail attempts stop after the initial attempt plus two restarts')
988
+ assert.equal(managerRows(tree).length, 0)
989
+ assert.ok(pick(tree, node => node.props?.role === 'alert' && node.props.children.includes('gsManagerChanged')).length)
990
+ panel.close()
991
+ })
992
+
993
+ test('exact entity editing accepts missing legacy aliases but refuses malformed aliases without a destructive save', async () => {
994
+ for (const aliases of [undefined, null, 'broken']) {
995
+ const ui = client(), calls = [], entity = { id: 'ent-legacy', name: 'Legacy', kind: 'person', ...(aliases === undefined ? {} : { aliases }) }
996
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, libraries: [{ id: 'lib-a' }], call: async (method, args) => {
997
+ calls.push({ method, args })
998
+ if (method === 'getGraph') return managementGraph([{ ...entity, title: entity.name }], args)
999
+ if (method === 'listEntities') return { items: [entity], total: 1 }
1000
+ return { ok: true }
1001
+ } })
1002
+ let tree = await panel.flush()
1003
+ action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
1004
+ managerRows(tree)[0].props.onClick(); tree = await panel.flush()
1005
+ action(tree, 'gsEditNode').props.onClick(); tree = await panel.flush()
1006
+ if (aliases === undefined) {
1007
+ assert.equal(pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'entityAliases')[0].props.value, '')
1008
+ action(tree, 'save').props.onClick(); tree = await panel.flush()
1009
+ assert.deepEqual(Array.from(calls.find(row => row.method === 'renameEntity').args.aliases), [])
1010
+ } else {
1011
+ assert.equal(pick(tree, node => node.type === 'button' && node.props.children === 'save').length, 0)
1012
+ assert.equal(calls.filter(row => row.method === 'renameEntity').length, 0)
1013
+ }
1014
+ assert.equal(calls.find(row => row.method === 'listEntities').args.entityId, 'ent-legacy')
1015
+ panel.close()
1016
+ }
1017
+ })
1018
+
1019
+ test('all-library manager pages across libraries, namespaces duplicate ids and edits the owning library', async () => {
1020
+ const ui = client(), calls = []
1021
+ const libraries = [{ id: 'lib-a', name: 'Library A' }, { id: 'lib-b', name: 'Library B' }]
1022
+ const all = rows(0, 35).map(row => ({ ...row, kind: 'memory', title: 'Shared title ' + row.id }))
1023
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, sessionId: 'session-a', libraries,
1024
+ call: async (method, args) => {
1025
+ calls.push({ method, args })
1026
+ if (method === 'getGraph') return managementGraph(all, args, args.libraryId + '-r1')
1027
+ if (method === 'getMemory') return { entry: { title: 'Full B', content: 'Complete B body' } }
1028
+ return { ok: true }
1029
+ } })
1030
+ let tree = await panel.flush()
1031
+ action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
1032
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'gsManagerScope')[0].props.onChange({ target: { value: 'all' } })
1033
+ tree = await panel.flush()
1034
+ assert.equal(managerRows(tree).length, 60)
1035
+ assert.equal(new Set(managerRows(tree).map(row => row.props.key)).size, 60)
1036
+ assert.equal(pick(tree, node => node.props?.className === 'dshm-gs-mgr-library').length, 60)
1037
+ const b = managerRows(tree).find(row => JSON.parse(row.props.key)[0] === 'lib-b')
1038
+ const rawId = JSON.parse(b.props.key)[1]
1039
+ b.props.onClick(); tree = await panel.flush()
1040
+ action(tree, 'gsEditNode').props.onClick(); tree = await panel.flush()
1041
+ assert.deepEqual(JSON.parse(JSON.stringify(calls.find(row => row.method === 'getMemory').args)), { libraryId: 'lib-b', id: rawId })
1042
+ action(tree, 'save').props.onClick(); tree = await panel.flush()
1043
+ assert.equal(calls.find(row => row.method === 'updateMemory').args.libraryId, 'lib-b')
1044
+ assert.equal(calls.find(row => row.method === 'updateMemory').args.id, rawId)
1045
+ const page1 = new Set(managerRows(tree).map(row => row.props.key))
1046
+ action(tree, 'gsManagerNext').props.onClick(); tree = await panel.flush()
1047
+ assert.equal(managerRows(tree).length, 10)
1048
+ assert.ok(managerRows(tree).every(row => !page1.has(row.props.key)))
1049
+ assert.equal(action(tree, 'gsManagerNext').props.disabled, true)
1050
+ assert.ok(calls.filter(row => Object.hasOwn(row.args, 'includeOrphans')).every(row => row.args.libraryId !== 'all' && row.args.limit <= 60))
1051
+ panel.close()
1052
+ })
1053
+
1054
+ test('merged management opens all libraries and rejects stale page and creation completions', async () => {
1055
+ const ui = client(), calls = [], oldPage = defer(), oldCreate = defer()
1056
+ const all = rows(0, 70).map(row => ({ ...row, kind: 'memory', title: row.id }))
1057
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, sessionId: 'session-a', libraries: [{ id: 'lib-a' }, { id: 'lib-b' }], call: async (method, args) => {
1058
+ calls.push({ method, args })
1059
+ if (method === 'createEntity') return oldCreate.promise
1060
+ if (Object.hasOwn(args, 'includeOrphans') && args.libraryId === 'lib-a' && args.offset === 60) return oldPage.promise
1061
+ return managementGraph(args.libraryId === 'lib-a' ? all : [{ id: 'b', title: 'B', kind: 'memory' }], args)
1062
+ } })
1063
+ let tree = await panel.flush()
1064
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: '__global__' } })
1065
+ tree = await panel.flush(); const before = calls.length
1066
+ action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
1067
+ assert.ok(calls.length > before)
1068
+ assert.equal(managerRows(tree).length, 60)
1069
+ assert.equal(action(tree, 'gsAddNode').props.disabled, false)
1070
+ assert.ok(calls.filter(row => Object.hasOwn(row.args, 'includeOrphans')).every(row => row.args.sessionId === undefined))
1071
+ const choose = value => pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'gsManagerScope')[0].props.onChange({ target: { value } })
1072
+ choose('lib-a'); tree = await panel.flush()
1073
+ action(tree, 'gsManagerNext').props.onClick(); tree = await panel.flush()
1074
+ choose('lib-b'); tree = await panel.flush()
1075
+ oldPage.resolve(managementGraph(all, { overview: true, bbox: { minX: -1e5, minY: -1e5, maxX: 1e5, maxY: 1e5 }, zoom: 1, offset: 60, limit: 60 }))
1076
+ tree = await panel.flush()
1077
+ assert.deepEqual(managerRows(tree).map(row => row.props.key), ['b'])
1078
+ choose('lib-a'); tree = await panel.flush()
1079
+ action(tree, 'gsAddNode').props.onClick(); tree = await panel.flush()
1080
+ action(tree, 'gsNodeEntity').props.onClick(); tree = await panel.flush()
1081
+ pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'entityName')[0].props.onChange({ target: { value: 'A only' } })
1082
+ tree = await panel.flush(); action(tree, 'add').props.onClick(); tree = await panel.flush()
1083
+ choose('lib-b'); tree = await panel.flush()
1084
+ oldCreate.resolve({ id: 'ent-a', name: 'A only' }); tree = await panel.flush()
1085
+ assert.equal(pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'gsManagerScope')[0].props.value, 'lib-b')
1086
+ assert.ok(!managerRows(tree).some(row => row.props.key === 'ent-a'))
1087
+ assert.equal(calls.find(row => row.method === 'createEntity').args.libraryId, 'lib-a')
1088
+ assert.ok(calls.filter(row => Object.hasOwn(row.args, 'includeOrphans') && row.args.libraryId === 'lib-b').every(row => row.args.sessionId === undefined))
1089
+ panel.close()
1090
+ })
1091
+
1092
+ test('orphan focus never removes domain or session restrictions and disables unavailable edits', async () => {
1093
+ const ui = client(), calls = []
1094
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, sessionId: 'restricted', libraries: [{ id: 'lib-a' }], call: async (method, args) => {
1095
+ calls.push({ method, args })
1096
+ if (method === 'createEntity') return { id: 'ent-invisible', name: args.name }
1097
+ return managementGraph([], args)
1098
+ } })
1099
+ let tree = await panel.flush()
1100
+ pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: 'coding' } })
1101
+ tree = await panel.flush(); action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
1102
+ action(tree, 'gsAddNode').props.onClick(); tree = await panel.flush()
1103
+ action(tree, 'gsNodeEntity').props.onClick(); tree = await panel.flush()
1104
+ pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'entityName')[0].props.onChange({ target: { value: 'Invisible entity' } })
1105
+ tree = await panel.flush(); action(tree, 'add').props.onClick(); tree = await panel.flush()
1106
+ assert.equal(managerRows(tree).length, 0)
1107
+ assert.equal(action(tree, 'gsEditNode').props.disabled, true)
1108
+ assert.equal(action(tree, 'gsRemoveNode').props.disabled, true)
1109
+ assert.ok(pick(tree, node => node.props?.role === 'alert' && node.props.children.includes('gsManagerUnavailable')).length)
1110
+ assert.ok(calls.filter(row => row.args.focusId).every(row => row.args.domain === 'coding' && row.args.sessionId === 'restricted'))
1111
+ assert.ok(!calls.some(row => row.method === 'listEntities'))
1112
+ panel.close()
1113
+ })
1114
+
1115
+ test('manager search debounces server queries and ignores old replies and unmounted reads', async () => {
1116
+ const ui = client(), calls = [], old = defer(), leaving = defer()
1117
+ const all = rows(0, 130).map(row => ({ ...row, kind: 'memory', title: 'Other ' + row.id }))
1118
+ all.push({ id: 'ent-last', kind: 'person', title: 'Target outside the first page' })
1119
+ const panel = ui.render(ui.GraphStudioPanel, { t: key => key, sessionId: 'session-a', libraries: [{ id: 'lib-a' }], call: async (method, args) => {
1120
+ calls.push({ method, args })
1121
+ if (Object.hasOwn(args, 'includeOrphans') && args.query === 'old') return old.promise
1122
+ if (Object.hasOwn(args, 'includeOrphans') && args.query === 'leaving') return leaving.promise
1123
+ return managementGraph(all, args)
1124
+ } })
1125
+ let tree = await panel.flush()
1126
+ action(tree, 'gsManage').props.onClick(); tree = await panel.flush()
1127
+ const search = text => pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsSearch')[0].props.onChange({ target: { value: text } })
1128
+ search('old'); tree = await panel.flush()
1129
+ assert.equal(managerRows(tree).length, 0, 'raw input immediately invalidates the previous management result')
1130
+ assert.ok(!calls.some(row => row.args.query === 'old'))
1131
+ await new Promise(resolve => setTimeout(resolve, 280)); tree = await panel.flush()
1132
+ assert.ok(calls.some(row => row.args.query === 'old' && Object.hasOwn(row.args, 'includeOrphans')))
1133
+ search('ent-last'); tree = await panel.flush()
1134
+ await new Promise(resolve => setTimeout(resolve, 280)); tree = await panel.flush()
1135
+ assert.deepEqual(managerRows(tree).map(row => row.props.key), ['ent-last'])
1136
+ old.resolve(managementGraph(all, { query: 'Other', limit: 60, offset: 0 })); tree = await panel.flush()
1137
+ assert.deepEqual(managerRows(tree).map(row => row.props.key), ['ent-last'])
1138
+ search('leaving'); tree = await panel.flush()
1139
+ await new Promise(resolve => setTimeout(resolve, 280)); tree = await panel.flush()
1140
+ panel.close(); panel.dirty = false
1141
+ leaving.resolve(managementGraph([], { query: 'leaving' })); await tick()
1142
+ assert.equal(panel.dirty, false)
1143
+ assert.ok(calls.filter(row => Object.hasOwn(row.args, 'includeOrphans')).every(row => row.args.sessionId === 'session-a'))
1144
+ })
1145
+
1146
+ test('graph candidate entry defers candidate and ngram reads until opened and never executes a merge', async () => {
1147
+ const ui = client(), calls = [], summaries = []
1148
+ const pairs = Array.from({ length: 20 }, (_, i) => ({ sourceId: 'entity-' + i, targetId: 'target', reason: 'edit-distance' }))
1149
+ const props = { libraryId: 'lib-a', sessionId: 'credential', open: false, t: key => key,
1150
+ onSummary: value => summaries.push(value), call: async (method, args) => {
1151
+ calls.push({ method, args })
1152
+ return method === 'suggestEntityMerges' ? { items: pairs, total: 37, truncated: true, limit: 20 } : { entities: { provisional: [{ id: 'p', name: 'Pending', kind: 'person' }], confirmed: [] },
1153
+ tiers: { tier1: [{ term: 'Candidate' }, { term: 'Pending', entityId: 'p', entityStatus: 'provisional' }], tier2: [] } }
1154
+ } }
1155
+ const panel = ui.render(ui.GraphActionsPanel, props)
1156
+ await panel.flush()
1157
+ assert.equal(panel.value, null)
1158
+ assert.equal(calls.length, 0, 'the collapsed entry must not start pair scanning or full-body ngram statistics')
1159
+ assert.equal(summaries.at(-1).pending, null, 'not checked must never be represented as an exact zero')
1160
+ panel.draw({ ...props, open: true })
1161
+ let tree = await panel.flush()
1162
+ assert.deepEqual(calls.map(item => item.method), ['suggestEntityMerges', 'getAnchorCandidates'])
1163
+ assert.ok(calls.every(item => item.args.libraryId === 'lib-a' && item.args.sessionId === 'credential'))
1164
+ assert.equal(summaries.at(-1).pending, 39, 'the exact server pair total is counted, and a provisional entity is not counted again as a term candidate')
1165
+ assert.equal(summaries.at(-1).capped, false, 'a known server total is exact even when the visible batch is truncated')
1166
+ assert.equal(summaries.at(-1).loading, false)
1167
+ assert.equal(pick(tree, node => node.type === 'strong' && Array.isArray(node.props.children) && node.props.children.includes('gsReviewPending')).length, 1)
1168
+ assert.equal(pick(tree, node => node.type?.name === 'Button' && node.props.children === 'entityMergeAction').length, 21)
1169
+ assert.equal(calls.length, 2, 'opening or grouping candidates cannot perform writes')
1170
+ panel.draw({ ...props, open: false, refreshKey: 1 }); await panel.flush()
1171
+ assert.equal(calls.length, 2, 'a revision change while collapsed only invalidates the cached count')
1172
+ assert.equal(summaries.at(-1).pending, null)
1173
+ panel.draw({ ...props, open: true, refreshKey: 1 }); tree = await panel.flush()
1174
+ assert.equal(calls.length, 4)
1175
+ panel.close()
1176
+ })
1177
+
1178
+ test('bounded candidate batches are user driven, retain count lower bounds and never claim partial zero is exact', async () => {
1179
+ const ui = client(), calls = [], summaries = []
1180
+ const pair = n => ({ sourceId: 'source-' + n, targetId: 'target-' + n, reviewToken: String(n).repeat(64) })
1181
+ const pages = [
1182
+ { items: [], total: null, totalExact: false, discoveredTotal: 0, scanComplete: false, nextCursor: 'cursor-1', scanStart: 0, scannedPairs: 4096 },
1183
+ { items: [pair(1), pair(2)], total: null, totalExact: false, discoveredTotal: 2, scanComplete: false, nextCursor: 'cursor-2', scanStart: 4096, scannedPairs: 8192 },
1184
+ { items: [pair(3)], total: null, totalExact: false, discoveredTotal: 1, scanComplete: true, nextCursor: null, scanStart: 8192, scannedPairs: 10000 },
1185
+ ]
1186
+ const panel = ui.render(ui.GraphActionsPanel, { libraryId: 'lib-a', open: true, t: key => key,
1187
+ onSummary: value => summaries.push(value), call: async (method, args) => {
1188
+ calls.push({ method, args })
1189
+ return method === 'getAnchorCandidates' ? {} : { ...pages[args.cursor === 'cursor-1' ? 1 : args.cursor === 'cursor-2' ? 2 : 0], pairSpace: 10000, rejectedTotal: 8, limit: 20 }
1190
+ } })
1191
+ let tree = await panel.flush()
1192
+ assert.equal(summaries.at(-1).pending, 0)
1193
+ assert.equal(summaries.at(-1).capped, true, 'a zero-hit batch still has an unknown total')
1194
+ assert.ok(pick(tree, node => node.props?.children === 'gsReviewDiscovered').length)
1195
+ assert.ok(pick(tree, node => node.props?.children === 'gsReviewScanIncomplete').length)
1196
+ assert.equal(calls.filter(row => row.method === 'suggestEntityMerges').length, 1, 'no background scan loop')
1197
+ for (const [cursor, lowerBound, shown] of [['cursor-1', 2, 3], ['cursor-2', 3, 2]]) {
1198
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsReviewContinue')[0].props.onClick()
1199
+ tree = await panel.flush()
1200
+ assert.equal(calls.filter(row => row.method === 'suggestEntityMerges').at(-1).args.cursor, cursor)
1201
+ assert.equal(summaries.at(-1).pending, lowerBound)
1202
+ assert.equal(summaries.at(-1).capped, true, 'reaching the end cannot invent a server exact total')
1203
+ assert.equal(pick(tree, node => node.type?.name === 'Button' && node.props.children === 'entityMergeAction').length, shown, 'only this batch plus the manual form is kept')
1204
+ }
1205
+ assert.equal(calls.filter(row => row.method === 'getAnchorCandidates').length, 1, 'continuations reuse the open panels anchor result')
1206
+ assert.equal(pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsReviewContinue').length, 0)
1207
+ assert.ok(pick(tree, node => node.props?.children === 'gsReviewScanComplete').length)
1208
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsReviewRestart')[0].props.onClick()
1209
+ tree = await panel.flush()
1210
+ assert.equal(calls.filter(row => row.method === 'suggestEntityMerges').at(-1).args.cursor, undefined)
1211
+ assert.equal(summaries.at(-1).pending, 0, 'a restarted scan discards the previous snapshot count')
1212
+ panel.close()
1213
+ })
1214
+
1215
+ test('a stale or failed candidate continuation resets once and stops if the fresh first read also fails', async () => {
1216
+ for (const code of ['ENTITY_MERGE_SCAN_STALE', 'NETWORK_FAILURE']) {
1217
+ const ui = client(), calls = [], summaries = []
1218
+ const panel = ui.render(ui.GraphActionsPanel, { libraryId: 'lib-a', open: true, t: key => key,
1219
+ onSummary: value => summaries.push(value), call: async (method, args) => {
1220
+ calls.push({ method, args })
1221
+ if (method === 'getAnchorCandidates') return {}
1222
+ if (calls.filter(row => row.method === method).length === 1) return { items: [], total: null, totalExact: false,
1223
+ discoveredTotal: 0, scanComplete: false, nextCursor: 'stale-cursor' }
1224
+ throw Object.assign(new Error('scan failed'), { code })
1225
+ } })
1226
+ let tree = await panel.flush()
1227
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsReviewContinue')[0].props.onClick()
1228
+ tree = await panel.flush(); await tick(); tree = await panel.flush()
1229
+ const scans = calls.filter(row => row.method === 'suggestEntityMerges')
1230
+ assert.deepEqual(scans.map(row => row.args.cursor), [undefined, 'stale-cursor', undefined])
1231
+ assert.equal(summaries.at(-1).incomplete, true)
1232
+ assert.equal(summaries.at(-1).capped, true)
1233
+ assert.ok(pick(tree, node => node.props?.role === 'alert').length)
1234
+ assert.equal(pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsReviewContinue').length, 0)
1235
+ panel.close()
1236
+ }
1237
+ })
1238
+
1239
+ test('candidate writes abandon the old cursor and require fresh confirmation after reloading the first batch', async () => {
1240
+ const ui = client(), calls = []
1241
+ const pair = { sourceId: 'source', targetId: 'target', reviewToken: 'd'.repeat(64) }
1242
+ const panel = ui.render(ui.GraphActionsPanel, { libraryId: 'lib-a', open: true, t: key => key, call: async (method, args) => {
1243
+ calls.push({ method, args })
1244
+ if (method === 'getAnchorCandidates') return {}
1245
+ if (method === 'setEntityMergeRejection') return { ok: true, rejected: true }
1246
+ return { items: [pair], total: null, totalExact: false, discoveredTotal: 1, scanComplete: false,
1247
+ nextCursor: args.cursor ? 'cursor-2' : 'cursor-1', rejectedTotal: 0 }
1248
+ } })
1249
+ let tree = await panel.flush()
1250
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsReviewContinue')[0].props.onClick()
1251
+ tree = await panel.flush()
1252
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsRejectMerge')[0].props.onClick()
1253
+ tree = await panel.flush()
1254
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsConfirmAction')[0].props.onClick()
1255
+ tree = await panel.flush()
1256
+ assert.deepEqual(calls.filter(row => row.method === 'suggestEntityMerges').map(row => row.args.cursor), [undefined, 'cursor-1', undefined])
1257
+ assert.equal(pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsConfirmAction').length, 0)
1258
+ assert.equal(calls.filter(row => row.method === 'setEntityMergeRejection').length, 1)
1259
+ panel.close()
1260
+ })
1261
+
1262
+ test('graph pair exclusion and restoration need two clicks and reload authoritative totals', async () => {
1263
+ const ui = client(), calls = [], summaries = []
1264
+ const pair = { sourceId: 'ent-source', targetId: 'ent-target', reason: 'containment', reviewToken: 'a'.repeat(64) }
1265
+ let rejected = false, changed = 0
1266
+ const panel = ui.render(ui.GraphActionsPanel, { libraryId: 'lib-b', open: true, t: key => key,
1267
+ onSummary: value => summaries.push(value), onChanged: () => { changed++ }, call: async (method, args) => {
1268
+ calls.push({ method, args })
1269
+ if (method === 'suggestEntityMerges') return { items: rejected ? [] : [pair], total: rejected ? 40 : 41, truncated: true, limit: 20,
1270
+ rejectedItems: rejected ? [pair] : [], rejectedTotal: Number(rejected), rejectedTruncated: false }
1271
+ if (method === 'getAnchorCandidates') return {}
1272
+ if (method === 'setEntityMergeRejection') { rejected = args.rejected; return { ok: true, ...args } }
1273
+ throw new Error('unexpected write ' + method)
1274
+ } })
1275
+ let tree = await panel.flush()
1276
+ assert.equal(summaries.at(-1).pending, 41)
1277
+ for (const [label, next, total] of [['gsRejectMerge', true, 40], ['gsRestoreMerge', false, 41]]) {
1278
+ const writesBefore = calls.filter(row => row.method === 'setEntityMergeRejection').length
1279
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === label)[0].props.onClick()
1280
+ tree = await panel.flush()
1281
+ assert.equal(calls.filter(row => row.method === 'setEntityMergeRejection').length, writesBefore)
1282
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsConfirmAction')[0].props.onClick()
1283
+ tree = await panel.flush()
1284
+ const write = calls.filter(row => row.method === 'setEntityMergeRejection').at(-1)
1285
+ assert.equal(write.args.libraryId, 'lib-b')
1286
+ assert.equal(write.args.sessionId, undefined)
1287
+ assert.equal(write.args.sourceId, pair.sourceId)
1288
+ assert.equal(write.args.targetId, pair.targetId)
1289
+ assert.equal(write.args.reviewToken, pair.reviewToken)
1290
+ assert.equal(write.args.confirmed, true)
1291
+ assert.equal(write.args.rejected, next)
1292
+ assert.equal(summaries.at(-1).pending, total)
1293
+ assert.equal(changed, writesBefore + 1)
1294
+ assert.equal(pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsRestoreMerge').length, Number(next))
1295
+ }
1296
+ assert.equal(calls.filter(row => row.method === 'suggestEntityMerges').length, 3, 'both writes read fresh server totals')
1297
+ panel.close()
1298
+ })
1299
+
1300
+ test('graph pair rejection failure preserves pending work and never reports success', async () => {
1301
+ const ui = client(), summaries = []
1302
+ let changed = 0
1303
+ const panel = ui.render(ui.GraphActionsPanel, { libraryId: 'lib-a', open: true, t: key => key,
1304
+ onSummary: value => summaries.push(value), onChanged: () => { changed++ }, call: async method => {
1305
+ if (method === 'suggestEntityMerges') return { items: [{ sourceId: 'ent-a', targetId: 'ent-b', reviewToken: 'b'.repeat(64) }], total: 1, limit: 20 }
1306
+ if (method === 'getAnchorCandidates') return {}
1307
+ throw new Error('review permission denied')
1308
+ } })
1309
+ let tree = await panel.flush()
1310
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsRejectMerge')[0].props.onClick()
1311
+ tree = await panel.flush()
1312
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsConfirmAction')[0].props.onClick()
1313
+ tree = await panel.flush()
1314
+ assert.equal(summaries.at(-1).pending, 1)
1315
+ assert.equal(changed, 0)
1316
+ assert.ok(pick(tree, node => node.props?.role === 'status' && node.props.children === 'review permission denied').length)
1317
+ panel.close()
1318
+ })
1319
+
1320
+ test('graph merge needs two matching clicks, routes source library and reports actual RPC impact', async () => {
1321
+ const ui = client(), calls = []
1322
+ let changed = 0
1323
+ const panel = ui.render(ui.GraphActionsPanel, { libraryId: 'lib-b', sessionId: null, open: true,
1324
+ t: key => key === 'entityMergeDone' ? '{from}>{to}:{links}:{aliases}' : key, onChanged: () => { changed++ },
1325
+ call: async (method, args) => {
1326
+ calls.push({ method, args })
1327
+ if (method === 'suggestEntityMerges') return { items: [{ sourceId: 's', targetId: 't', reason: 'containment', reviewToken: 'c'.repeat(64) }] }
1328
+ if (method === 'getAnchorCandidates') return { entities: { confirmed: [{ id: 's', name: 'Source' }, { id: 't', name: 'Target' }] } }
1329
+ return { remappedLinks: 7, aliases: ['alias'], relationships: { conflicts: [] } }
1330
+ } })
1331
+ let tree = await panel.flush()
1332
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'entityMergeAction')[0].props.onClick()
1333
+ tree = await panel.flush()
1334
+ assert.equal(calls.filter(item => item.method === 'mergeEntities').length, 0)
1335
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsConfirmAction')[0].props.onClick()
1336
+ tree = await panel.flush()
1337
+ const write = calls.find(item => item.method === 'mergeEntities')
1338
+ assert.equal(write.args.libraryId, 'lib-b')
1339
+ assert.equal(write.args.sessionId, undefined)
1340
+ assert.deepEqual(Array.from(write.args.sourceIds), ['s'])
1341
+ assert.equal(write.args.targetId, 't')
1342
+ assert.equal(write.args.reviewToken, 'c'.repeat(64))
1343
+ assert.equal(changed, 1)
1344
+ assert.ok(pick(tree, node => node.props?.role === 'status' && node.props.children === 'Source>Target:7:1').length)
1345
+ panel.close()
1346
+ })
1347
+
1348
+ test('graph actions reject old candidate replies and do not repaint a new library after an old write', async () => {
1349
+ const ui = client(), oldRead = defer(), write = defer(), calls = []
1350
+ let changed = 0
1351
+ const props = { libraryId: 'lib-a', open: true, t: key => key, onChanged: () => { changed++ },
1352
+ call: async (method, args) => {
1353
+ calls.push({ method, args })
1354
+ if (method === 'suggestEntityMerges') return args.libraryId === 'lib-a' ? oldRead.promise : { items: [] }
1355
+ if (method === 'getAnchorCandidates') return { entities: { provisional: [{ id: args.libraryId, name: args.libraryId }] } }
1356
+ return write.promise
1357
+ } }
1358
+ const panel = ui.render(ui.GraphActionsPanel, props)
1359
+ await panel.flush()
1360
+ panel.draw({ ...props, libraryId: 'lib-b' })
1361
+ oldRead.resolve({ items: [{ sourceId: 'old', targetId: 'stale' }] })
1362
+ await tick()
1363
+ let tree = await panel.flush()
1364
+ assert.equal(pick(tree, node => node.type?.name === 'Button' && node.props.children === 'entityMergeAction').length, 1, 'only the disabled manual merge remains')
1365
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'anchorConfirm')[0].props.onClick()
1366
+ tree = await panel.flush()
1367
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'gsConfirmAction')[0].props.onClick()
1368
+ await panel.flush()
1369
+ panel.draw({ ...props, libraryId: 'lib-c' })
1370
+ write.resolve({ confirmed: ['lib-b'] })
1371
+ await tick(); tree = await panel.flush()
1372
+ assert.equal(changed, 0, 'the completed old write notifies other views but cannot refresh the new selection')
1373
+ assert.equal(calls.find(item => item.method === 'confirmEntities').args.libraryId, 'lib-b')
1374
+ assert.equal(pick(tree, node => node.props?.role === 'status').length, 0)
1375
+ panel.close()
1376
+ })
1377
+
1378
+ test('graph candidate failures remain incomplete and graph data refresh preserves the camera fit key', async () => {
1379
+ const ui = client(), summaries = []
1380
+ const review = ui.render(ui.GraphActionsPanel, { libraryId: 'lib-a', open: true, t: key => key,
1381
+ onSummary: value => summaries.push(value), call: async method => { if (method === 'suggestEntityMerges') throw new Error('forbidden'); return {} } })
1382
+ const body = await review.flush()
1383
+ assert.equal(summaries.at(-1).incomplete, true)
1384
+ assert.ok(pick(body, node => node.props?.role === 'alert' && node.props.children === 'gsReviewUnavailable').length)
1385
+ review.close()
1386
+ const graph = ui.render(ui.GraphStudioPanel, { t: key => key, libraries: [{ id: 'lib-a' }],
1387
+ call: async () => ({ overview: true, mode: 'clusters', nodes: [], edges: [], domains: [] }) })
1388
+ let tree = await graph.flush()
1389
+ const fitKey = pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.fitKey
1390
+ pick(tree, node => node.type?.name === 'GraphActionsPanel')[0].props.onChanged()
1391
+ tree = await graph.flush()
1392
+ assert.equal(pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.fitKey, fitKey, 'a write must not trigger fit or discard pinned-node coordinates')
1393
+ pick(tree, node => node.type === 'button' && node.props.title === 'gsOverview')[0].props.onClick()
1394
+ tree = await graph.flush()
1395
+ assert.notEqual(pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.fitKey, fitKey, 'explicit overview remains a navigation reset')
1396
+ graph.close()
1397
+ })
1398
+
1399
+ test('standalone session actions require an explicit conversation and verify scope/domain write read-backs', async () => {
1400
+ const ui = client(), calls = []
1401
+ let domain = 'rp', enabled = true
1402
+ const panel = ui.render(ui.SessionActionsPanel, { t: key => key, libraries: [{ id: 'lib-a' }],
1403
+ call: async (method, args) => {
1404
+ calls.push({ method, args })
1405
+ if (method === 'listSessions') return { sessions: [{ id: 'session-a', cwd: 'D:/fixture', title: 'Fixture' }] }
1406
+ if (method === 'setDomain') { domain = args.domain; return {} }
1407
+ if (method === 'setSessionScope') { enabled = args.useLibrary; return {} }
1408
+ return { binding: { libraryId: 'lib-a', memoryContext: {} }, domain, domains: ['rp', 'coding'], folder: { useLibrary: true, useGlobal: true },
1409
+ effective: { useLibrary: enabled, useGlobal: true } }
1410
+ } })
1411
+ let tree = await panel.flush()
1412
+ assert.deepEqual(calls.map(row => row.method), ['listSessions'], 'a standalone page never guesses the active host conversation')
1413
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'sessionActionsPick')[0].props.onChange({ target: { value: 'session-a' } })
1414
+ tree = await panel.flush()
1415
+ for (const label of ['usePrivate', 'useGlobal']) {
1416
+ assert.equal(pick(tree, node => node.type === 'span' && node.props.children === label).length, 1, 'each session scope switch has a visible label')
1417
+ }
1418
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'domain')[0].props.onChange({ target: { value: 'coding' } })
1419
+ tree = await panel.flush()
1420
+ assert.deepEqual(calls.slice(-2).map(row => row.method), ['setDomain', 'getSidebarState'])
1421
+ assert.equal(calls.at(-1).args.sessionId, 'session-a')
1422
+ assert.equal(pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'domain')[0].props.value, 'coding')
1423
+ pick(tree, node => node.type?.name === 'Toggle' && node.props.label === 'usePrivate')[0].props.onChange(false)
1424
+ tree = await panel.flush()
1425
+ assert.equal(pick(tree, node => node.type?.name === 'Toggle' && node.props.label === 'usePrivate')[0].props.checked, false)
1426
+ assert.deepEqual(calls.slice(-2).map(row => row.method), ['setSessionScope', 'getSidebarState'])
1427
+ panel.close()
1428
+ })
1429
+
1430
+ test('standalone session actions ignore an old write after a new conversation is selected', async () => {
1431
+ const ui = client(), pending = defer(), calls = []
1432
+ const panel = ui.render(ui.SessionActionsPanel, { t: key => key, libraries: [{ id: 'lib-a' }],
1433
+ call: async (method, args) => {
1434
+ calls.push({ method, args })
1435
+ if (method === 'listSessions') return { sessions: [{ id: 'a', cwd: 'D:/fixture' }, { id: 'b', cwd: 'D:/other' }] }
1436
+ if (method === 'setDomain') return pending.promise
1437
+ return { binding: { libraryId: 'lib-a' }, domain: args.sessionId === 'b' ? 'general' : 'rp', effective: { useLibrary: true, useGlobal: true } }
1438
+ } })
1439
+ let tree = await panel.flush()
1440
+ const choose = value => pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'sessionActionsPick')[0].props.onChange({ target: { value } })
1441
+ choose('a'); tree = await panel.flush()
1442
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'domain')[0].props.onChange({ target: { value: 'coding' } })
1443
+ choose('b'); panel.draw()
1444
+ pending.resolve({}); await tick(); tree = await panel.flush()
1445
+ assert.equal(pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'domain')[0].props.value, 'general')
1446
+ assert.equal(calls.filter(row => row.method === 'getSidebarState' && row.args.sessionId === 'a').length, 1, 'an old completion must not refresh the old conversation')
1447
+ panel.close()
1448
+ })
1449
+
1450
+ test('standalone session rebind uses setLibrary and a consolidation failure stays a failure', async () => {
1451
+ const ui = client(), calls = []
1452
+ let libraryId = 'lib-a'
1453
+ const panel = ui.render(ui.SessionActionsPanel, { t: key => key, libraries: [{ id: 'lib-a' }, { id: 'lib-b' }],
1454
+ call: async (method, args) => {
1455
+ calls.push({ method, args })
1456
+ if (method === 'listSessions') return { sessions: [{ id: 's', cwd: 'D:/fixture' }] }
1457
+ if (method === 'setLibrary') { libraryId = args.libraryId; return {} }
1458
+ if (method === 'generatePrivate') return { ok: false, error: 'fork unavailable' }
1459
+ return { binding: { libraryId }, domain: 'rp', effective: { useLibrary: true, useGlobal: true } }
1460
+ } })
1461
+ let tree = await panel.flush()
1462
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'sessionActionsPick')[0].props.onChange({ target: { value: 's' } })
1463
+ tree = await panel.flush()
1464
+ pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'sessionActionsLibrary')[0].props.onChange({ target: { value: 'lib-b' } })
1465
+ tree = await panel.flush()
1466
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'sessionActionsBind')[0].props.onClick()
1467
+ tree = await panel.flush()
1468
+ assert.deepEqual(calls.slice(-2).map(row => row.method), ['setLibrary', 'getSidebarState'])
1469
+ assert.equal(libraryId, 'lib-b')
1470
+ pick(tree, node => node.type?.name === 'Button' && node.props.children === 'organize')[0].props.onClick()
1471
+ tree = await panel.flush()
1472
+ assert.equal(pick(tree, node => node.props?.role === 'status')[0].props.children, 'fork unavailable')
1473
+ panel.close()
1474
+ })
1475
+
1476
+ test('package index drafts retain separators and reject credential-bearing or invalid URLs', async () => {
1477
+ const ui = client(), saved = []
1478
+ const panel = ui.render(ui.PipIndexesInput, { values: [], t: key => key, onChange: value => saved.push(Array.from(value)) })
1479
+ let tree = await panel.flush()
1480
+ let input = () => pick(tree, node => node.type === 'input')[0]
1481
+ input().props.onFocus()
1482
+ input().props.onChange({ target: { value: 'https://pypi.org/simple, ' } }); tree = await panel.flush()
1483
+ assert.equal(input().props.value, 'https://pypi.org/simple, ')
1484
+ assert.deepEqual(saved.at(-1), ['https://pypi.org/simple'])
1485
+ for (const value of ['https://user:secret@mirror.invalid/simple', 'https://mirror.invalid/simple?token=secret', 'file:///private', 'unfinished']) {
1486
+ const before = saved.length
1487
+ input().props.onChange({ target: { value } }); tree = await panel.flush()
1488
+ assert.equal(saved.length, before)
1489
+ assert.equal(input().props['aria-invalid'], true)
1490
+ assert.ok(pick(tree, node => node.props?.role === 'alert').length)
1491
+ }
1492
+ input().props.onChange({ target: { value: '' } }); tree = await panel.flush()
1493
+ assert.deepEqual(saved.at(-1), [])
1494
+ panel.close()
1495
+ })