dsh-memu-memory 1.4.4 → 1.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +11 -0
  3. package/README.md +33 -14
  4. package/README.zh.md +34 -12
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/libraries.jpg +0 -0
  7. package/assets/screenshots/mobile.jpg +0 -0
  8. package/assets/screenshots/relations.jpg +0 -0
  9. package/assets/screenshots/settings.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +19 -3
  13. package/docs/contributing.md +4 -2
  14. package/docs/env-and-commands.md +9 -1
  15. package/docs/graph-scale.md +214 -0
  16. package/docs/lexicon-recall.md +100 -0
  17. package/docs/mcp-porting.md +8 -6
  18. package/docs/memory-semantics.md +35 -3
  19. package/docs/pending-work.md +3 -1
  20. package/docs/retention.md +83 -0
  21. package/docs/rt-index.md +452 -0
  22. package/docs/scale-performance.md +101 -0
  23. package/docs/token-budget.md +92 -0
  24. package/docs/troubleshooting.md +50 -11
  25. package/lib/auto-link/apply.js +7 -2
  26. package/lib/auto-link/candidates.js +32 -10
  27. package/lib/backup.js +67 -32
  28. package/lib/binding-diagnostics.js +1 -1
  29. package/lib/bounded-cache.js +80 -0
  30. package/lib/client.js +2096 -409
  31. package/lib/consolidation-ledger.js +21 -4
  32. package/lib/consolidation-worker.js +14 -1
  33. package/lib/cycle.js +16 -11
  34. package/lib/diagnostic-context.js +372 -0
  35. package/lib/diagnostics.js +147 -61
  36. package/lib/embedding-download.js +7 -8
  37. package/lib/engine-sources.js +286 -0
  38. package/lib/engine.js +23 -10
  39. package/lib/entity-repair.js +43 -13
  40. package/lib/entity-review.js +64 -0
  41. package/lib/environment-check.js +348 -36
  42. package/lib/feedback.js +25 -0
  43. package/lib/global-graph.js +46 -2
  44. package/lib/graph-adjacency-index.js +525 -0
  45. package/lib/graph-overview.js +293 -0
  46. package/lib/graph.js +658 -105
  47. package/lib/inbound.js +44 -15
  48. package/lib/index-pages.js +57 -0
  49. package/lib/index.js +44 -6
  50. package/lib/inject.js +119 -50
  51. package/lib/lexicon-rt-source.js +25 -0
  52. package/lib/lexicon-rt-worker.js +26 -0
  53. package/lib/lexicon-rt.js +224 -0
  54. package/lib/lexicon-scope.js +56 -5
  55. package/lib/lexicon.js +143 -54
  56. package/lib/local-vector-service.js +3 -0
  57. package/lib/maintenance-ledger.js +542 -12
  58. package/lib/managed-runtime.js +260 -80
  59. package/lib/media.js +1 -1
  60. package/lib/memory.js +564 -131
  61. package/lib/port-surface.js +96 -11
  62. package/lib/private.js +47 -21
  63. package/lib/recall-cache.js +20 -34
  64. package/lib/retention.js +173 -0
  65. package/lib/rpc.js +135 -52
  66. package/lib/rt-index/builder.js +209 -0
  67. package/lib/rt-index/format.js +231 -0
  68. package/lib/rt-index/manifest.js +105 -0
  69. package/lib/rt-index/reader.js +673 -0
  70. package/lib/rt-index-retention.js +151 -0
  71. package/lib/rt-index-service.js +283 -0
  72. package/lib/rt-index-worker.js +21 -0
  73. package/lib/salient-wake.js +55 -4
  74. package/lib/state.js +195 -24
  75. package/lib/temporal.js +39 -13
  76. package/lib/token-measurement.js +126 -0
  77. package/lib/tools.js +101 -6
  78. package/lib/turn-log.js +108 -3
  79. package/lib/webui/graph-layout-worker.js +68 -0
  80. package/lib/webui/graph-local-physics.js +390 -0
  81. package/lib/webui/graph-spatial-grid.js +64 -0
  82. package/lib/webui/graph-view.bundle.js +6 -1
  83. package/lib/webui/graph-view.js +478 -135
  84. package/lib/webui/graph-webgl-renderer.js +74 -0
  85. package/lib/webui/standalone.js +1 -1
  86. package/lib/worker-pool.js +30 -4
  87. package/package.json +3 -2
  88. package/scripts/acceptance-local.mjs +4 -10
  89. package/scripts/bench-all-libraries.mjs +47 -0
  90. package/scripts/check-classic-graph-browser.mjs +189 -0
  91. package/scripts/check-client-browser.mjs +929 -0
  92. package/scripts/check-graph-browser.mjs +6 -0
  93. package/scripts/check-graph-elastic-browser.mjs +139 -0
  94. package/scripts/check-memory-review-browser.mjs +124 -0
  95. package/scripts/entity-dedupe.mjs +19 -3
  96. package/scripts/graph-artifact-provenance.mjs +30 -0
  97. package/scripts/graph-freeze-manifest.mjs +129 -0
  98. package/scripts/graph-geometry-fixture.mjs +40 -0
  99. package/scripts/graph-physics-bench.mjs +218 -0
  100. package/scripts/graph-scale-bench.mjs +213 -0
  101. package/scripts/graph-scale-memory.mjs +48 -0
  102. package/scripts/graph-service-bench.mjs +72 -0
  103. package/scripts/make-readme-shots.mjs +17 -5
  104. package/scripts/preview.mjs +1 -0
  105. package/scripts/rebuild-rt.mjs +18 -0
  106. package/scripts/scale-bench.mjs +183 -0
  107. package/scripts/simulate-injection.mjs +47 -8
  108. package/scripts/verify-host-fixtures.mjs +108 -0
  109. package/scripts/verify-host-recovery.mjs +565 -0
  110. package/scripts/verify-vector-recovery.mjs +740 -0
  111. package/tests/auto-link-candidates.test.mjs +20 -0
  112. package/tests/browser.test.mjs +16 -2
  113. package/tests/client-export.test.mjs +16 -1
  114. package/tests/client-pagination.test.mjs +1495 -0
  115. package/tests/client-render.test.mjs +223 -28
  116. package/tests/consolidation-fork.test.mjs +93 -10
  117. package/tests/consolidation-ledger.test.mjs +17 -1
  118. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  119. package/tests/diagnostic-report.test.mjs +429 -0
  120. package/tests/diagnostic-wiring.test.mjs +88 -0
  121. package/tests/diagnostics.test.mjs +27 -0
  122. package/tests/embedding-download.test.mjs +44 -0
  123. package/tests/engine-source-settings.test.mjs +69 -0
  124. package/tests/engine-sources.test.mjs +145 -0
  125. package/tests/entity-dedupe.test.mjs +143 -0
  126. package/tests/entity-merge-review.test.mjs +363 -0
  127. package/tests/entity-merge.test.mjs +12 -4
  128. package/tests/entity-review.test.mjs +87 -0
  129. package/tests/environment-check.test.mjs +51 -1
  130. package/tests/feedback.test.mjs +95 -0
  131. package/tests/graph-adjacency-index.test.mjs +536 -0
  132. package/tests/graph-cascade.test.mjs +229 -0
  133. package/tests/graph-import-diagnostic.test.mjs +25 -0
  134. package/tests/graph-overview.test.mjs +709 -0
  135. package/tests/graph-session-authorization.test.mjs +419 -0
  136. package/tests/graph-view-geometry.test.mjs +426 -0
  137. package/tests/graph-view-scale.test.mjs +88 -0
  138. package/tests/graph-view.test.mjs +444 -5
  139. package/tests/graph.test.mjs +43 -0
  140. package/tests/help-page.test.mjs +128 -54
  141. package/tests/inbound.test.mjs +19 -0
  142. package/tests/index-pagination.test.mjs +113 -0
  143. package/tests/index-read-view.test.mjs +212 -0
  144. package/tests/inject-guide.test.mjs +9 -0
  145. package/tests/injection-dedupe.test.mjs +213 -0
  146. package/tests/lexicon-recall.test.mjs +641 -0
  147. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  148. package/tests/lexicon-rt.test.mjs +468 -0
  149. package/tests/local-embedding-worker.test.mjs +38 -0
  150. package/tests/local-vector-service.test.mjs +32 -3
  151. package/tests/maintenance-compat.test.mjs +128 -0
  152. package/tests/maintenance-settlement.test.mjs +1003 -0
  153. package/tests/managed-memory.test.mjs +39 -11
  154. package/tests/managed-runtime.test.mjs +109 -0
  155. package/tests/memory-fields.test.mjs +24 -12
  156. package/tests/observed-evidence.test.mjs +52 -0
  157. package/tests/port-surface.test.mjs +93 -1
  158. package/tests/recall-cache.test.mjs +56 -3
  159. package/tests/recall-dedup.test.mjs +63 -2
  160. package/tests/retention.test.mjs +260 -0
  161. package/tests/rt-index-cross-library.test.mjs +230 -0
  162. package/tests/rt-index-integration.test.mjs +194 -0
  163. package/tests/rt-index-retention.test.mjs +552 -0
  164. package/tests/rt-index-scale.test.mjs +204 -0
  165. package/tests/rt-index.test.mjs +705 -0
  166. package/tests/salient-date-boundaries.test.mjs +121 -0
  167. package/tests/salient-wake.test.mjs +29 -0
  168. package/tests/scale-bench.test.mjs +53 -0
  169. package/tests/settings-plumbing.test.mjs +25 -0
  170. package/tests/simulate-injection.test.mjs +15 -1
  171. package/tests/standalone-navigation.test.mjs +44 -0
  172. package/tests/state.test.mjs +51 -0
  173. package/tests/temporal-precision.test.mjs +102 -0
  174. package/tests/temporal.test.mjs +10 -6
  175. package/tests/token-measurement.test.mjs +98 -0
  176. package/tests/tool-schema.test.mjs +41 -5
  177. package/tests/tools.test.mjs +6 -3
  178. package/tests/turn-token-budget.test.mjs +149 -0
  179. package/tests/webui-auth.test.mjs +57 -1
  180. package/tests/webui.test.mjs +40 -15
@@ -0,0 +1,363 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { createHash } from 'node:crypto'
7
+ import { spawnSync } from 'node:child_process'
8
+
9
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-merge-review-'))
10
+ process.env.DSH_MEMU_HOME = home
11
+ const state = await import('../lib/state.js')
12
+ const graph = await import('../lib/graph.js')
13
+ const { dispatch } = await import('../lib/rpc.js')
14
+ const { indexDir, writeJson } = await import('../lib/paths.js')
15
+ const { registerTools } = await import('../lib/tools.js')
16
+ const activity = await import('../lib/activity-log.js')
17
+ test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
18
+
19
+ function fixture(label) {
20
+ const { id: libraryId } = state.createLibrary({ name: label, cwd: path.join(home, label) })
21
+ const source = graph.createEntity({ libraryId, name: 'Lin', kind: 'person' })
22
+ const target = graph.createEntity({ libraryId, name: 'Lin Mian', kind: 'person' })
23
+ const pair = graph.suggestEntityMerges({ libraryId }).items[0]
24
+ return { libraryId, sourceId: source.id, targetId: target.id, reviewToken: pair.reviewToken }
25
+ }
26
+
27
+ function addEvidence(libraryId, sourceId, targetId, { count = 2, hidden = false } = {}) {
28
+ const entries = {}
29
+ for (let i = 0; i < count; i += 1) {
30
+ const id = `mem-review-${labelId(libraryId)}-${hidden ? 'hidden' : 'visible'}-${i}`
31
+ entries[id] = {
32
+ title: `Evidence ${i} for identity`,
33
+ content: `The story explicitly records the same person at scene ${i}. ${'Visible detail '.repeat(18)}`,
34
+ status: 'active', layer: 'long_term', visibility: hidden ? 'secret' : 'shared', domain: 'rp',
35
+ ...(hidden ? { context: { characterId: 'hidden' } } : {}),
36
+ links: [{ to: sourceId, kind: 'person' }, { to: targetId, kind: 'person' }],
37
+ }
38
+ }
39
+ const file = path.join(indexDir(), `${libraryId}.json`)
40
+ const current = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : { version: 1, entries: {} }
41
+ current.entries = { ...current.entries, ...entries }
42
+ state.savePrivateIndex(libraryId, current)
43
+ }
44
+
45
+ function labelId(value) { return value.replace(/[^a-z0-9]/giu, '').slice(-12) }
46
+
47
+ function entityTools() {
48
+ const tools = []
49
+ const dispose = registerTools({ tools: { register: tool => { tools.push(tool); return () => {} } }, logger: { warn() {} } }, {
50
+ only: ['memu_private_entity_merge_suggest', 'memu_private_entity_merge_decide'],
51
+ })
52
+ return { tools, dispose }
53
+ }
54
+
55
+ function workerExec(libraryId) {
56
+ const sessionId = `entity-merge-worker-${labelId(libraryId)}`
57
+ state.setSessionBinding(sessionId, { libraryId, scopeKey: state.getLibrary(libraryId)?.scopeKey,
58
+ useLibrary: true, useGlobal: false, memoryContext: {} })
59
+ return { agent: { session: { header: { id: sessionId } } } }
60
+ }
61
+
62
+ test('a real RPC decision persists, removes the actual pair and can restore it in reverse order', async () => {
63
+ const args = fixture('persist')
64
+ const before = graph.graphExport(args.libraryId)
65
+ const pair = { sourceId: args.sourceId, targetId: args.targetId, reason: 'containment', reviewToken: args.reviewToken }
66
+ assert.deepEqual(graph.suggestEntityMerges(args).items, [pair])
67
+ await dispatch({}, 'setEntityMergeRejection', { ...args, rejected: true, confirmed: true })
68
+ const reviewed = await dispatch({}, 'suggestEntityMerges', args)
69
+ assert.deepEqual(reviewed.items, [])
70
+ assert.deepEqual(reviewed.rejectedItems, [pair])
71
+ assert.equal(reviewed.total, 0)
72
+ assert.equal(reviewed.rejectedTotal, 1)
73
+ assert.deepEqual(graph.graphExport(args.libraryId), before, 'portable graph export excludes local review preferences')
74
+ state.flushState()
75
+ const moduleUrl = new URL('../lib/graph.js', import.meta.url).href
76
+ const child = spawnSync(process.execPath, ['--input-type=module', '-e',
77
+ `const graph = await import(${JSON.stringify(moduleUrl)}); console.log(JSON.stringify(graph.suggestEntityMerges(${JSON.stringify(args)})))`],
78
+ { env: { ...process.env, DSH_MEMU_HOME: home }, encoding: 'utf8', timeout: 30_000 })
79
+ assert.equal(child.status, 0, child.stderr)
80
+ assert.equal(JSON.parse(child.stdout.trim()).rejectedTotal, 1, 'a fresh process reads the persistent decision')
81
+ await dispatch({}, 'setEntityMergeRejection', { ...args, sourceId: args.targetId, targetId: args.sourceId, rejected: false, confirmed: true })
82
+ assert.deepEqual(graph.suggestEntityMerges(args).items, [pair])
83
+ assert.equal(graph.suggestEntityMerges(args).rejectedTotal, 0)
84
+ })
85
+
86
+ test('detailed review returns names, linked memory summaries, exact evidence count and a bounded preview', () => {
87
+ const args = fixture('detailed-evidence')
88
+ addEvidence(args.libraryId, args.sourceId, args.targetId, { count: 8 })
89
+ const result = graph.suggestEntityMergeReviews(args)
90
+ assert.equal(result.items.length, 1)
91
+ const pair = result.items[0]
92
+ assert.equal(pair.source.name, 'Lin')
93
+ assert.equal(pair.target.name, 'Lin Mian')
94
+ assert.equal(pair.reason, 'containment')
95
+ assert.equal(pair.source.memoryCount, 8, 'total evidence count remains exact despite capped details')
96
+ assert.equal(pair.source.memories.length, 6)
97
+ assert.equal(pair.source.memoriesTruncated, true)
98
+ assert.ok(pair.source.memories.every(memory => memory.preview.length <= 180))
99
+ assert.ok(pair.source.memories[0].preview.includes('same person'))
100
+ assert.equal(pair.reviewToken, args.reviewToken)
101
+ })
102
+
103
+ test('session evidence review omits hidden and context-invisible entity candidates and summaries', () => {
104
+ const { id: libraryId, scopeKey } = state.createLibrary({ name: 'session-evidence', cwd: path.join(home, 'session-evidence') })
105
+ const sessionId = 'merge-review-visible-session'
106
+ state.setSessionBinding(sessionId, { libraryId, scopeKey, useLibrary: true, useGlobal: false,
107
+ memoryContext: { characterId: 'visible' } })
108
+ const visibleA = graph.createEntity({ libraryId, name: 'Visible Rae', kind: 'person' })
109
+ const visibleB = graph.createEntity({ libraryId, name: 'Visible Rae Harbor', kind: 'person' })
110
+ const hiddenA = graph.createEntity({ libraryId, name: 'Secret Rae', kind: 'person' })
111
+ const hiddenB = graph.createEntity({ libraryId, name: 'Secret Rae Harbor', kind: 'person' })
112
+ addEvidence(libraryId, visibleA.id, visibleB.id)
113
+ addEvidence(libraryId, hiddenA.id, hiddenB.id, { hidden: true })
114
+ const result = graph.suggestEntityMergeReviews({ exec: { agent: { session: { header: { id: sessionId } } } }, libraryId })
115
+ const serialized = JSON.stringify(result)
116
+ assert.equal(result.items.length, 1)
117
+ assert.equal(serialized.includes('Secret Rae'), false)
118
+ assert.equal(serialized.includes('same person at scene'), true)
119
+ assert.equal(serialized.includes('mem-review-'), true)
120
+ })
121
+
122
+ test('worker low-confidence merge becomes hold without changing graph and leaves a visible audit signal', async () => {
123
+ const args = fixture('worker-hold')
124
+ addEvidence(args.libraryId, args.sourceId, args.targetId)
125
+ const { tools, dispose } = entityTools()
126
+ try {
127
+ const decide = tools.find(tool => tool.name === 'memu_private_entity_merge_decide')
128
+ const before = graph.graphExport(args.libraryId)
129
+ const reply = JSON.parse(await decide.execute({ source_id: args.sourceId, target_id: args.targetId,
130
+ review_token: args.reviewToken, decision: 'merge', confidence: 0.7,
131
+ reason: 'Evidence is not strong enough to establish identity.' }, workerExec(args.libraryId)))
132
+ assert.equal(reply.decision, 'hold')
133
+ assert.equal(reply.requestedDecision, 'merge')
134
+ assert.equal(reply.pendingUserReview, true)
135
+ assert.deepEqual(graph.graphExport(args.libraryId), before)
136
+ assert.equal(graph.suggestEntityMerges(args).total, 1)
137
+ const event = activity.listEvents({ kind: 'consolidate', libraryId: args.libraryId, limit: 10 })
138
+ .find(row => row.detail?.phase === 'entity-review')
139
+ assert.equal(event?.detail?.actor, 'worker')
140
+ assert.equal(event?.detail?.decision, 'hold')
141
+ } finally { dispose() }
142
+ })
143
+
144
+ test('holds persist only while semantic evidence is unchanged and reject stale credentials', () => {
145
+ const args = fixture('hold-evidence-change')
146
+ addEvidence(args.libraryId, args.sourceId, args.targetId)
147
+ graph.holdEntityMergeReview({ ...args, reason: 'The current evidence is insufficient.', confidence: .5 })
148
+ assert.equal(graph.suggestEntityMerges({ ...args, reviewState: 'model' }).items.length, 0)
149
+ assert.equal(graph.pendingEntityReviewPairs({ ...args, pairs: [args] }).length, 0)
150
+ assert.equal(graph.suggestEntityMergeReviews({ ...args, reviewState: 'human' }).items[0].reviewReason, 'The current evidence is insufficient.')
151
+ state.updatePrivateIndex(args.libraryId, index => {
152
+ for (const entry of Object.values(index.entries)) { entry.recallCount = 15; entry.lastRecalledAt = new Date().toISOString(); entry.updatedAt = new Date().toISOString() }
153
+ })
154
+ assert.equal(graph.suggestEntityMerges({ ...args, reviewState: 'model' }).items.length, 0, 'recall bookkeeping cannot requeue a held pair')
155
+ state.updatePrivateIndex(args.libraryId, index => { Object.values(index.entries)[0].content += ' New identity evidence.' })
156
+ assert.equal(graph.suggestEntityMerges({ ...args, reviewState: 'model' }).items.length, 1)
157
+ assert.equal(graph.suggestEntityMerges({ ...args, reviewState: 'human' }).items.length, 0)
158
+ assert.throws(() => graph.holdEntityMergeReview({ ...args, reviewToken: 'f'.repeat(64), reason: 'Old credentials.', confidence: .4 }), /changed|refresh/)
159
+ })
160
+
161
+ test('worker merges or rejects only through a fresh review token and records its decision', async () => {
162
+ const mergeArgs = fixture('worker-merge')
163
+ addEvidence(mergeArgs.libraryId, mergeArgs.sourceId, mergeArgs.targetId)
164
+ const rejectArgs = fixture('worker-reject')
165
+ addEvidence(rejectArgs.libraryId, rejectArgs.sourceId, rejectArgs.targetId)
166
+ const { tools, dispose } = entityTools()
167
+ try {
168
+ const decide = tools.find(tool => tool.name === 'memu_private_entity_merge_decide')
169
+ const merged = JSON.parse(await decide.execute({ source_id: mergeArgs.sourceId, target_id: mergeArgs.targetId,
170
+ review_token: mergeArgs.reviewToken, decision: 'merge', confidence: 0.92,
171
+ reason: 'Both visible records identify this person as Lin Mian.' }, workerExec(mergeArgs.libraryId)))
172
+ assert.equal(merged.decision, 'merge')
173
+ assert.equal(graph.graphExport(mergeArgs.libraryId).entities[mergeArgs.sourceId], undefined)
174
+ assert.ok(graph.graphExport(mergeArgs.libraryId).entities[mergeArgs.targetId])
175
+
176
+ const rejected = JSON.parse(await decide.execute({ source_id: rejectArgs.sourceId, target_id: rejectArgs.targetId,
177
+ review_token: rejectArgs.reviewToken, decision: 'reject', confidence: 0.91,
178
+ reason: 'Visible evidence identifies two separate people.' }, workerExec(rejectArgs.libraryId)))
179
+ assert.equal(rejected.decision, 'reject')
180
+ assert.equal(graph.suggestEntityMerges(rejectArgs).total, 0)
181
+ assert.equal(graph.suggestEntityMerges(rejectArgs).rejectedTotal, 1)
182
+ } finally { dispose() }
183
+ })
184
+
185
+ test('worker merge rejects a stale token after a candidate rename without deleting either entity', async () => {
186
+ const args = fixture('worker-stale')
187
+ addEvidence(args.libraryId, args.sourceId, args.targetId)
188
+ graph.renameEntity({ libraryId: args.libraryId, entityId: args.targetId, name: 'Renamed Lin' })
189
+ const { tools, dispose } = entityTools()
190
+ try {
191
+ const decide = tools.find(tool => tool.name === 'memu_private_entity_merge_decide')
192
+ const reply = await decide.execute({ source_id: args.sourceId, target_id: args.targetId,
193
+ review_token: args.reviewToken, decision: 'merge', confidence: 0.99,
194
+ reason: 'Both visible records identify the same exact person.' }, workerExec(args.libraryId))
195
+ assert.match(reply, /ENTITY_MERGE_CANDIDATE_CHANGED/)
196
+ assert.ok(graph.graphExport(args.libraryId).entities[args.sourceId])
197
+ assert.ok(graph.graphExport(args.libraryId).entities[args.targetId])
198
+ } finally { dispose() }
199
+ })
200
+
201
+ test('review requires confirmation, a boolean decision, two real same-kind candidates and a known library', async () => {
202
+ const args = fixture('validation')
203
+ for (const patch of [{}, { confirmed: false }, { confirmed: true, rejected: 'true' },
204
+ { confirmed: true, rejected: true, reviewToken: undefined },
205
+ { confirmed: true, rejected: true, targetId: args.sourceId },
206
+ { confirmed: true, rejected: true, sourceId: '__proto__' },
207
+ { confirmed: true, rejected: true, sourceId: 'ent-missing' },
208
+ { confirmed: true, rejected: true, libraryId: 'unknown-library' }]) {
209
+ await assert.rejects(dispatch({}, 'setEntityMergeRejection', { ...args, ...patch }))
210
+ }
211
+ const place = graph.createEntity({ libraryId: args.libraryId, name: 'Lin Road', kind: 'place' })
212
+ assert.throws(() => graph.setEntityMergeRejection({ ...args, targetId: place.id, rejected: true, confirmed: true }), /no longer a merge candidate/)
213
+ assert.equal(graph.suggestEntityMerges(args).total, 1)
214
+ })
215
+
216
+ test('a changed name invalidates a decision, while repeated reads and identical decisions do not write', () => {
217
+ const args = fixture('rename')
218
+ graph.setEntityMergeRejection({ ...args, rejected: true, confirmed: true })
219
+ const file = path.join(indexDir(), `${args.libraryId}.entities.json`)
220
+ const before = fs.readFileSync(file, 'utf8')
221
+ graph.setEntityMergeRejection({ ...args, rejected: true, confirmed: true })
222
+ graph.suggestEntityMerges(args)
223
+ assert.equal(fs.readFileSync(file, 'utf8'), before)
224
+ graph.renameEntity({ libraryId: args.libraryId, entityId: args.targetId, name: 'Lin Miao' })
225
+ assert.equal(graph.suggestEntityMerges(args).total, 1)
226
+ assert.equal(graph.suggestEntityMerges(args).rejectedTotal, 0)
227
+ const renamed = graph.suggestEntityMerges(args).items[0]
228
+ graph.setEntityMergeRejection({ ...args, reviewToken: renamed.reviewToken, rejected: true, confirmed: true })
229
+ graph.mergeEntities({ libraryId: args.libraryId, targetId: args.targetId, sourceIds: [args.sourceId] })
230
+ assert.equal(graph.suggestEntityMerges(args).rejectedTotal, 0, 'deleted merge sources do not leave visible rejections')
231
+ })
232
+
233
+ test('exclusions are library-local and cannot suppress an equal-name pair in another library', () => {
234
+ const first = fixture('scope-a')
235
+ const second = fixture('scope-b')
236
+ graph.setEntityMergeRejection({ ...first, rejected: true, confirmed: true })
237
+ assert.equal(graph.suggestEntityMerges(first).total, 0)
238
+ assert.equal(graph.suggestEntityMerges(second).total, 1)
239
+ })
240
+
241
+ test('the bounded exclusion store refuses new decisions without evicting existing user decisions', () => {
242
+ const { id: libraryId } = state.createLibrary({ name: 'cap', cwd: path.join(home, 'cap') })
243
+ const entities = { 'ent-base': { id: 'ent-base', kind: 'person', name: 'Lin' } }
244
+ const mergeRejections = {}
245
+ for (let i = 0; i <= 1000; i += 1) {
246
+ const id = `ent-pair-${String(i).padStart(4, '0')}`
247
+ const name = `Lin ${i}`
248
+ entities[id] = { id, kind: 'person', name }
249
+ if (i === 1000) continue
250
+ const rows = [['ent-base', 'person', 'lin'], [id, 'person', name.toLowerCase().replace(/\s/g, '')]]
251
+ mergeRejections[JSON.stringify(rows.map(row => row[0]))] = {
252
+ sourceId: 'ent-base', targetId: id,
253
+ signature: createHash('sha256').update(JSON.stringify(rows)).digest('hex'), updatedAt: new Date().toISOString(),
254
+ }
255
+ }
256
+ const file = path.join(indexDir(), `${libraryId}.entities.json`)
257
+ writeJson(file, { version: 1, entities, relationships: {}, mergeRejections })
258
+ const before = fs.readFileSync(file, 'utf8')
259
+ const signature = index => {
260
+ const id = `ent-pair-${String(index).padStart(4, '0')}`
261
+ const pairSignature = createHash('sha256').update(JSON.stringify([['ent-base', 'person', 'lin'], [id, 'person', `lin${index}`]])).digest('hex')
262
+ return createHash('sha256').update(JSON.stringify([libraryId, pairSignature])).digest('hex')
263
+ }
264
+ const args = { libraryId, sourceId: 'ent-base', targetId: 'ent-pair-1000', rejected: true, confirmed: true, reviewToken: signature(1000) }
265
+ assert.throws(() => graph.setEntityMergeRejection(args), /1000-pair limit/)
266
+ assert.equal(fs.readFileSync(file, 'utf8'), before)
267
+ graph.setEntityMergeRejection({ ...args, targetId: 'ent-pair-0000', reviewToken: signature(0), rejected: false })
268
+ graph.setEntityMergeRejection(args)
269
+ const stored = JSON.parse(fs.readFileSync(file, 'utf8')).mergeRejections
270
+ assert.equal(Object.keys(stored).length, 1000)
271
+ assert.equal(Object.values(stored).some(row => row.targetId === 'ent-pair-0000'), false)
272
+ assert.equal(Object.values(stored).some(row => row.targetId === 'ent-pair-1000'), true)
273
+ })
274
+
275
+ test('a queued decision rejects renamed or cross-library candidates and does not sign an unseen identity', async () => {
276
+ const args = fixture('queued-rename')
277
+ await dispatch({}, 'renameEntity', { libraryId: args.libraryId, entityId: args.targetId, name: 'Lin Miao' })
278
+ await assert.rejects(dispatch({}, 'setEntityMergeRejection', { ...args, rejected: true, confirmed: true }), { code: 'ENTITY_MERGE_CANDIDATE_CHANGED' })
279
+ await assert.rejects(dispatch({}, 'mergeEntities', {
280
+ libraryId: args.libraryId, targetId: args.targetId, sourceIds: [args.sourceId], reviewToken: args.reviewToken,
281
+ }), { code: 'ENTITY_MERGE_CANDIDATE_CHANGED' })
282
+ assert.ok(graph.graphExport(args.libraryId).entities[args.sourceId], 'a stale merge must preserve its source entity')
283
+ assert.equal(graph.suggestEntityMerges(args).rejectedTotal, 0)
284
+ const newPair = graph.suggestEntityMerges(args).items[0]
285
+ assert.notEqual(newPair.reviewToken, args.reviewToken)
286
+ await dispatch({}, 'setEntityMergeRejection', { ...args, ...newPair, rejected: true, confirmed: true })
287
+ await dispatch({}, 'renameEntity', { libraryId: args.libraryId, entityId: args.targetId, name: 'Lin Mian' })
288
+ await assert.rejects(dispatch({}, 'setEntityMergeRejection', { ...args, ...newPair, rejected: false, confirmed: true }), { code: 'ENTITY_MERGE_CANDIDATE_CHANGED' })
289
+ const other = fixture('queued-other-library')
290
+ await assert.rejects(dispatch({}, 'setEntityMergeRejection', { ...other, reviewToken: args.reviewToken, rejected: true, confirmed: true }), { code: 'ENTITY_MERGE_CANDIDATE_CHANGED' })
291
+ assert.equal(graph.suggestEntityMerges(other).rejectedTotal, 0)
292
+ })
293
+
294
+ function scanFixture(label, count, name) {
295
+ const { id: libraryId } = state.createLibrary({ name: label, cwd: path.join(home, label) })
296
+ const entities = Object.fromEntries(Array.from({ length: count }, (_, i) => {
297
+ const id = `ent-scan-${String(i).padStart(4, '0')}`
298
+ return [id, { id, name: name(i), kind: 'person', status: 'confirmed' }]
299
+ }))
300
+ const file = path.join(indexDir(), `${libraryId}.entities.json`)
301
+ writeJson(file, { version: 1, entities, relationships: {} })
302
+ return { libraryId, file }
303
+ }
304
+
305
+ test('bounded cursor traversal has no lost or repeated candidate pairs and never claims a partial total is exact', () => {
306
+ const count = 92
307
+ const { libraryId, file } = scanFixture('scan-dense', count, i => `Person ${String(i).padStart(3, '0')}`)
308
+ const before = fs.readFileSync(file)
309
+ let cursor
310
+ let previous = 0
311
+ const pairs = new Set()
312
+ let pages = 0
313
+ for (;;) {
314
+ const page = graph.suggestEntityMerges({ libraryId, cursor })
315
+ assert.equal(page.total, null, 'a traversal batch cannot claim the complete global total')
316
+ assert.equal(page.totalExact, false)
317
+ assert.equal(page.scanStart, previous)
318
+ assert.ok(page.batchComparisons > 0 && page.batchComparisons <= graph.MERGE_SCAN_PAIR_LIMIT)
319
+ assert.equal(page.scannedPairs, previous + page.batchComparisons)
320
+ assert.equal(page.discoveredTotal, page.items.length)
321
+ assert.ok(page.items.length <= 20)
322
+ for (const pair of page.items) {
323
+ const key = JSON.stringify([pair.sourceId, pair.targetId].sort())
324
+ assert.equal(pairs.has(key), false, 'cursor pages must not repeat a pair')
325
+ pairs.add(key)
326
+ }
327
+ previous = page.scannedPairs
328
+ pages += 1
329
+ if (page.scanComplete) { assert.equal(page.nextCursor, null); break }
330
+ assert.ok(page.nextCursor)
331
+ cursor = page.nextCursor
332
+ assert.ok(pages < 300)
333
+ }
334
+ assert.equal(pairs.size, count * (count - 1) / 2, 'all three-digit names in this fixture differ by at most two edits')
335
+ assert.equal(previous, count * (count - 1) / 2)
336
+ assert.ok(pages > 1)
337
+ assert.deepEqual(fs.readFileSync(file), before, 'all scan pages remain read-only')
338
+ })
339
+
340
+ test('an empty partial batch is unknown, and cursors reject malformed, changed or foreign snapshots', () => {
341
+ const fixture = scanFixture('scan-sparse', 96, i => createHash('sha256').update(`unique-${i}`).digest('hex'))
342
+ const first = graph.suggestEntityMerges(fixture)
343
+ assert.deepEqual(first.items, [])
344
+ assert.equal(first.total, null)
345
+ assert.equal(first.totalExact, false)
346
+ assert.equal(first.scanComplete, false)
347
+ assert.equal(first.batchComparisons, graph.MERGE_SCAN_PAIR_LIMIT)
348
+ assert.ok(first.nextCursor)
349
+ for (const cursor of [{}, 'bad', 'x'.repeat(181), first.nextCursor.replace(/\.\d+\.\d+$/, '.99999.0')]) {
350
+ assert.throws(() => graph.suggestEntityMerges({ ...fixture, cursor }), { code: 'ENTITY_MERGE_SCAN_STALE' })
351
+ }
352
+ const other = scanFixture('scan-foreign', 96, i => createHash('sha256').update(`unique-${i}`).digest('hex'))
353
+ assert.throws(() => graph.suggestEntityMerges({ ...other, cursor: first.nextCursor }), { code: 'ENTITY_MERGE_SCAN_STALE' })
354
+ const stored = JSON.parse(fs.readFileSync(fixture.file, 'utf8'))
355
+ stored.entities['ent-scan-0000'].name = 'Renamed'
356
+ writeJson(fixture.file, stored)
357
+ assert.throws(() => graph.suggestEntityMerges({ ...fixture, cursor: first.nextCursor }), { code: 'ENTITY_MERGE_SCAN_STALE' })
358
+ const dense = scanFixture('scan-rejection-change', 96, i => `Person ${String(i).padStart(3, '0')}`)
359
+ const page = graph.suggestEntityMerges(dense)
360
+ graph.setEntityMergeRejection({ ...dense, ...page.items[0], rejected: true, confirmed: true })
361
+ assert.throws(() => graph.suggestEntityMerges({ ...dense, cursor: page.nextCursor }), { code: 'ENTITY_MERGE_SCAN_STALE' })
362
+ assert.equal(graph.suggestEntityMerges(dense).items.some(pair => pair.reviewToken === page.items[0].reviewToken), false)
363
+ })
@@ -207,9 +207,10 @@ test('suggestEntityMerges: near-miss spellings within two edits are candidates,
207
207
  assert.equal(first.items.length, 2)
208
208
  assert.ok(first.items.every(item => item.reason === 'edit-distance'))
209
209
  assert.deepEqual(first.items.find(item => [item.sourceId, item.targetId].includes(kyle.id)),
210
- { sourceId: kile.id, targetId: kyle.id, reason: 'edit-distance' }, 'equal length folds into the older id')
210
+ { sourceId: kile.id, targetId: kyle.id, reason: 'edit-distance', reviewToken: first.items[0].reviewToken }, 'equal length folds into the older id')
211
211
  assert.deepEqual(first.items.find(item => [item.sourceId, item.targetId].includes(marcus.id)),
212
- { sourceId: marcos.id, targetId: marcus.id, reason: 'edit-distance' })
212
+ { sourceId: marcos.id, targetId: marcus.id, reason: 'edit-distance', reviewToken: first.items[1].reviewToken })
213
+ assert.ok(first.items.every(item => /^[a-f0-9]{64}$/.test(item.reviewToken)))
213
214
  })
214
215
 
215
216
  test('suggestEntityMerges: kind mismatch and identical folded names yield no candidates', () => {
@@ -218,7 +219,11 @@ test('suggestEntityMerges: kind mismatch and identical folded names yield no can
218
219
  graph.createEntity({ libraryId, name: 'Ariadne', kind: 'place' })
219
220
  graph.createEntity({ libraryId, name: 'Mika', kind: 'person' })
220
221
  graph.createEntity({ libraryId, name: 'MIKA', kind: 'person' })
221
- assert.deepEqual(graph.suggestEntityMerges({ libraryId }), { items: [] })
222
+ assert.deepEqual(graph.suggestEntityMerges({ libraryId }), {
223
+ items: [], total: 0, totalExact: true, discoveredTotal: 0, scanComplete: true, nextCursor: null,
224
+ scanStart: 0, scannedPairs: 6, batchComparisons: 6, pairSpace: 6,
225
+ truncated: false, rejectedItems: [], rejectedTotal: 0, rejectedTruncated: false, limit: 20,
226
+ })
222
227
  })
223
228
 
224
229
  test('suggestEntityMerges: unrelated names yield an empty list', () => {
@@ -259,6 +264,8 @@ test('suggestEntityMerges caps the list at 20 and never writes', () => {
259
264
  assert.equal(fs.readFileSync(file, 'utf8'), before, 'suggesting is a pure read')
260
265
  assert.deepEqual(second, first)
261
266
  assert.equal(first.items.length, 20)
267
+ assert.ok(first.total > first.items.length)
268
+ assert.equal(first.truncated, true)
262
269
  assert.ok(first.items.every(item => item.sourceId && item.targetId && item.sourceId !== item.targetId))
263
270
  assert.ok(first.items.every(item => item.reason === 'containment' || item.reason === 'edit-distance'))
264
271
  })
@@ -269,7 +276,8 @@ test('the RPC cases take exactly the payload the graph panel sends', async () =>
269
276
  const source = graph.createEntity({ libraryId, name: '林眠', kind: 'person' })
270
277
  const rpc = await import('../lib/rpc.js')
271
278
  const suggested = await rpc.dispatch({}, 'suggestEntityMerges', { libraryId })
272
- assert.deepEqual(suggested.items, [{ sourceId: source.id, targetId: target.id, reason: 'containment' }])
279
+ assert.deepEqual(suggested.items, [{ sourceId: source.id, targetId: target.id, reason: 'containment', reviewToken: suggested.items[0].reviewToken }])
280
+ assert.match(suggested.items[0].reviewToken, /^[a-f0-9]{64}$/)
273
281
  // 面板一次只确认一对:sourceIds 是数组,但 UI 传的就是单个来源。
274
282
  const merged = await rpc.dispatch({}, 'mergeEntities', { libraryId, targetId: target.id, sourceIds: [source.id] })
275
283
  assert.equal(merged.targetId, target.id)
@@ -0,0 +1,87 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-entity-auto-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+ const state = await import('../lib/state.js')
10
+ const graph = await import('../lib/graph.js')
11
+ const { runEntityReviewPass } = await import('../lib/entity-review.js')
12
+ const now = Date.now()
13
+ test.beforeEach(() => {
14
+ for (const binding of state.listSessionBindings()) state.setSessionBinding(binding.sessionId, { useLibrary: false })
15
+ state.updateSettings({ sleepConsolidation: true })
16
+ })
17
+ test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
18
+
19
+ function fixture(sessionId, patch = {}) {
20
+ const binding = state.ensureSession(sessionId, { cwd: path.join(home, sessionId), agentPreset: 'coding' })
21
+ state.setSessionBinding(sessionId, { lastTurnAt: new Date(now - 3_600_000).toISOString(), ...patch })
22
+ const source = graph.createEntity({ libraryId: binding.libraryId, name: 'Harbor Lin', kind: 'person' })
23
+ const target = graph.createEntity({ libraryId: binding.libraryId, name: 'Harbor Lin Mian', kind: 'person' })
24
+ state.savePrivateIndex(binding.libraryId, { entries: { 'memory-evidence': { title: 'Identity', content: 'Lin is Lin Mian.',
25
+ status: 'active', visibility: 'shared', links: [{ to: source.id }, { to: target.id }] } } })
26
+ return { ...binding, sessionId, source, target }
27
+ }
28
+
29
+ test('unreviewed candidates dispatch automatically to the owning session and persisted holds stop repeat calls', async () => {
30
+ const binding = fixture('auto-owner'), calls = []
31
+ const request = async (_ctx, sessionId, options) => {
32
+ calls.push({ sessionId, options })
33
+ for (const pair of options.entityReviewPairs) graph.holdEntityMergeReview({ libraryId: binding.libraryId, ...pair,
34
+ exec: { agent: { session: { header: { id: sessionId } } } }, reason: 'Needs stronger identity evidence.', confidence: .6 })
35
+ return { ok: true, settled: true }
36
+ }
37
+ const result = await runEntityReviewPass({}, { now, request })
38
+ assert.equal(result.ran, 1)
39
+ assert.equal(calls[0].sessionId, binding.sessionId)
40
+ assert.equal(calls[0].options.entityReviewOnly, true)
41
+ assert.equal(calls[0].options.trigger, 'entity-review')
42
+ assert.equal(calls[0].options.entityReviewPairs[0].sourceId, binding.source.id)
43
+ assert.equal(graph.suggestEntityMergeReviews({ libraryId: binding.libraryId, reviewState: 'human' }).items.length, 1)
44
+ await runEntityReviewPass({}, { now: now + 16 * 60_000, request })
45
+ assert.equal(calls.length, 1, 'unchanged held evidence is not sent to the model again')
46
+ assert.equal(state.getSessionBinding(binding.sessionId).lastEntityReviewError, null)
47
+ })
48
+
49
+ test('a silent or unsuccessful model retries with persisted backoff and a redacted error', async () => {
50
+ const binding = fixture('auto-no-progress'), calls = []
51
+ const request = async () => { calls.push(true); return { ok: true, settled: false, error: 'API_KEY=sk-fixture-secret-key-123456' } }
52
+ await runEntityReviewPass({}, { now, request })
53
+ const failed = state.getSessionBinding(binding.sessionId)
54
+ assert.equal(failed.entityReviewAttempts, 1)
55
+ assert.match(failed.lastEntityReviewError, /REDACTED/)
56
+ assert.ok(!failed.lastEntityReviewAt)
57
+ await runEntityReviewPass({}, { now: now + 60_000, request })
58
+ assert.equal(calls.length, 1)
59
+ await runEntityReviewPass({}, { now: now + 3 * 60_000, request })
60
+ assert.equal(calls.length, 2)
61
+ assert.equal(graph.suggestEntityMerges({ libraryId: binding.libraryId, reviewState: 'model' }).items.length, 1)
62
+ })
63
+
64
+ test('disabled, running, recently active and archived sessions never dispatch background reviews', async () => {
65
+ const active = fixture('auto-active', { lastTurnAt: new Date(now - 1000).toISOString() })
66
+ const running = fixture('auto-running'), archived = fixture('auto-archived'), disabled = fixture('auto-disabled', { useLibrary: false })
67
+ state.archiveLibrary(archived.libraryId)
68
+ let calls = 0
69
+ const options = { now, request: async () => { calls++; return { ok: true, settled: true } } }
70
+ await runEntityReviewPass({ get: key => key === 'agents' ? { get: id => id === running.sessionId ? { status: 'running' } : null } : null }, options)
71
+ assert.equal(calls, 0)
72
+ state.updateSettings({ sleepConsolidation: false })
73
+ assert.equal((await runEntityReviewPass({}, options)).skipped, 'disabled')
74
+ assert.ok(active.libraryId && disabled.libraryId)
75
+ })
76
+
77
+ test('batch size and per-pass library budget bound automatic model work', async () => {
78
+ const first = fixture('auto-budget-a'), second = fixture('auto-budget-b')
79
+ for (let i = 0; i < 8; i++) graph.createEntity({ libraryId: first.libraryId, name: 'Harbor Lin Mian ' + i })
80
+ const calls = []
81
+ await runEntityReviewPass({}, { now, limit: 1, request: async (_ctx, id, options) => {
82
+ calls.push({ id, options }); return { ok: true, settled: true }
83
+ } })
84
+ assert.equal(calls.length, 1)
85
+ assert.ok(calls[0].options.entityReviewPairs.length <= 4)
86
+ assert.ok([first.sessionId, second.sessionId].includes(calls[0].id))
87
+ })
@@ -113,7 +113,7 @@ test('a repair that fails is still recorded, with the error', async () => {
113
113
  const failed = diag.listDiagnostics({}).items.find(row => row.code === 'MEMU_DIAGNOSTIC_REPAIR_FAILED')
114
114
  assert.ok(failed, 'a failed repair must not disappear')
115
115
  assert.equal(failed.level, 'error')
116
- assert.equal(failed.detail.action, 'not-a-real-action')
116
+ assert.match(failed.detail.action, /value withheld/, 'unknown caller-supplied actions are not exported as raw text')
117
117
  })
118
118
 
119
119
  test('startup auto-repair only touches the safe list', async () => {
@@ -160,6 +160,56 @@ test('the fragment finding reports, offers a confirmed-only repair, and is idemp
160
160
  assert.equal(graph.listEntities({ libraryId }).items.length, 1)
161
161
  })
162
162
 
163
+ test('large entity planning remains visibly deferred in both the check and confirmed manual repair', async (t) => {
164
+ const state = await import('../lib/state.js')
165
+ const libraryId = state.createLibrary({ name: 'envcheck-large-fragments', cwd: path.join(home, 'large-fragments') }).id
166
+ const file = path.join(paths.indexDir(), `${libraryId}.entities.json`)
167
+ const corpusFile = path.join(paths.indexDir(), `${libraryId}.json`)
168
+ const entities = Object.fromEntries(Array.from({ length: 257 }, (_, i) => {
169
+ const id = `ent-env-large-${i}`
170
+ return [id, { id, name: `Person ${String(i).padStart(4, '0')}`, kind: 'person', status: 'confirmed' }]
171
+ }))
172
+ fs.writeFileSync(file, JSON.stringify({ version: 1, entities, relationships: {} }))
173
+ state.savePrivateIndex(libraryId, { entries: {} })
174
+ const before = fs.readFileSync(file, 'utf8')
175
+ const read = fs.readFileSync.bind(fs)
176
+ let corpusReads = 0
177
+ t.mock.method(fs, 'readFileSync', (target, ...args) => {
178
+ if (typeof target === 'string' && path.resolve(target) === path.resolve(corpusFile)) { corpusReads++; assert.fail('large checks must not traverse the corpus') }
179
+ return read(target, ...args)
180
+ })
181
+ try {
182
+ const finding = env.runEnvironmentCheck().items.find(row => row.id === 'entity-fragments')
183
+ assert.equal(finding.ok, false)
184
+ assert.equal(finding.code, 'ENTITY_REPAIR_DEFERRED')
185
+ assert.equal(finding.partial, true)
186
+ assert.equal(finding.deferred, true)
187
+ assert.ok(finding.totalEntities >= 257)
188
+ assert.equal(finding.entityLimit, 256)
189
+ assert.match(finding.hint, /图管理/)
190
+ assert.equal(finding.repair, null, 'a deferred scan must not advertise a bulk-merge fix')
191
+
192
+ diag.clearDiagnostics()
193
+ const outcome = await env.repairEnvironment({ actions: ['merge-entity-fragments'], confirmed: true })
194
+ assert.equal(outcome.ok, false)
195
+ assert.equal(outcome.results[0].ok, false)
196
+ assert.equal(outcome.results[0].code, 'ENTITY_REPAIR_DEFERRED')
197
+ assert.equal(outcome.results[0].partial, true)
198
+ assert.equal(outcome.results[0].deferred, true)
199
+ assert.ok(outcome.results[0].totalEntities >= 257)
200
+ assert.equal(outcome.results[0].entityLimit, 256)
201
+ assert.match(outcome.results[0].detail, /未完成/)
202
+ assert.match(outcome.results[0].detail, /图管理/)
203
+ const deferred = diag.listDiagnostics().items.find(row => row.code === 'ENTITY_REPAIR_DEFERRED')
204
+ assert.ok(deferred, 'deferred manual planning must remain observable')
205
+ assert.match(deferred.hint, /图管理/)
206
+ assert.ok(!diag.listDiagnostics().items.some(row => row.code === 'MEMU_DIAGNOSTIC_REPAIRED'), 'no false successful-repair event')
207
+ assert.equal(outcome.after.items.find(row => row.id === 'entity-fragments').partial, true)
208
+ assert.equal(fs.readFileSync(file, 'utf8'), before)
209
+ assert.equal(corpusReads, 0)
210
+ } finally { state.archiveLibrary(libraryId) }
211
+ })
212
+
163
213
  // ---------------------------------------------------------------- 运行时目录发现
164
214
 
165
215
  test('the managed runtime root is discovered where the service actually installs it', async () => {