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,565 @@
1
+ #!/usr/bin/env node
2
+ // Local rc.5 acceptance. Production paths are read-only; every output is new.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import crypto from 'node:crypto'
6
+ import assert from 'node:assert/strict'
7
+ import net from 'node:net'
8
+ import os from 'node:os'
9
+ import { spawn, spawnSync, execFileSync } from 'node:child_process'
10
+ import { fileURLToPath, pathToFileURL } from 'node:url'
11
+ import { startMockLlm } from './mock-llm.mjs'
12
+ import { readSessionEvents, locateSessionLog } from './drive-session.mjs'
13
+
14
+ const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
15
+ const options = Object.fromEntries(process.argv.slice(2).map(arg => {
16
+ const split = arg.indexOf('=')
17
+ if (!arg.startsWith('--') || split < 0) throw new Error('use --name=value arguments')
18
+ return [arg.slice(2, split), arg.slice(split + 1)]
19
+ }))
20
+ const PROCESS_CLOSE_TIMEOUT_MS = 5000
21
+ const TASKKILL_TIMEOUT_MS = 10000
22
+
23
+ function taskkillArguments(pid) {
24
+ if (!Number.isSafeInteger(pid) || pid < 1) throw new Error('owned pid must be a positive integer')
25
+ return ['/PID', String(pid), '/T', '/F']
26
+ }
27
+ function isOwnedChild(child, ownedChildren, protectedPid) {
28
+ return Boolean(child && ownedChildren.has(child) && Number.isSafeInteger(child.pid)
29
+ && child.pid > 0 && child.pid !== protectedPid)
30
+ }
31
+ function waitBounded(promise, timeoutMs) {
32
+ let timer
33
+ return Promise.race([promise, new Promise(resolve => {
34
+ timer = setTimeout(() => resolve({ timedOut: true }), timeoutMs)
35
+ })]).finally(() => clearTimeout(timer))
36
+ }
37
+ async function runCleanupSelfTest() {
38
+ assert.deepEqual(taskkillArguments(4321), ['/PID', '4321', '/T', '/F'])
39
+ assert.throws(() => taskkillArguments(0), /positive integer/)
40
+ const child = { pid: 4321 }
41
+ const ownedChildren = new Set([child])
42
+ assert.equal(isOwnedChild(child, ownedChildren, 9999), true)
43
+ assert.equal(isOwnedChild(child, ownedChildren, 4321), false)
44
+ assert.equal(isOwnedChild({ pid: 4321 }, ownedChildren, 9999), false)
45
+ assert.deepEqual(await waitBounded(Promise.resolve({ code: 0 }), 100), { code: 0 })
46
+ assert.deepEqual(await waitBounded(new Promise(() => {}), 5), { timedOut: true })
47
+ console.log(JSON.stringify({ selfTest: 'owned-process-cleanup', ok: true }))
48
+ }
49
+ if (options['self-test'] === 'cleanup') {
50
+ await runCleanupSelfTest()
51
+ process.exit(0)
52
+ }
53
+ if (options['self-test']) throw new Error('unknown self-test')
54
+ if (options.only && options.only !== 'web') throw new Error('--only supports web only')
55
+ const launcher = options.launcher || path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData/Roaming'), 'in.dsh-plug.dsh-launcher')
56
+ const production = path.resolve(options['production-home'] || path.join(launcher, 'homes/0.2.2-rc.5'))
57
+ const installation = path.resolve(options.installation || path.join(launcher, 'versions/0.2.2-rc.5'))
58
+ const hostAnchor = path.join(installation, 'node_modules/@deepseek-ai/dsh/package.json')
59
+ const hostBin = path.join(path.dirname(hostAnchor), 'lib/bin.js')
60
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
61
+ const run = path.resolve(options.out || path.join(repo, 'logs', `recovery-host-${stamp}`))
62
+ const logsRoot = path.join(repo, 'logs') + path.sep
63
+ if (!run.startsWith(logsRoot) || !path.basename(run).startsWith('recovery-host-')) throw new Error('output must be logs/recovery-host-*')
64
+ if (fs.existsSync(run)) throw new Error('output already exists; choose a new run directory')
65
+ fs.mkdirSync(run, { recursive: true, mode: 0o700 })
66
+
67
+ const home = path.join(run, 'home')
68
+ const data = path.join(home, 'dsh-memu-memory')
69
+ const workspace = path.join(run, 'workspace')
70
+ const profileName = 'recovery-host'
71
+ const profile = path.join(home, 'profiles', profileName)
72
+ const snapshot = path.join(profile, 'node_modules/dsh-memu-memory')
73
+ const children = new Set()
74
+ const jobsByChild = new Map()
75
+ const protectedPid = Number(options['protected-pid'] || 22144)
76
+ if (!Number.isSafeInteger(protectedPid) || protectedPid < 1) throw new Error('protected pid must be a positive integer')
77
+ const report = { schema: 1, startedAt: new Date().toISOString(), phase: options.phase || 'pre-freeze', run,
78
+ scope: options.only === 'web' ? 'web-only' : 'all',
79
+ productionHome: production, installation, protectedPid, checks: [], productionWritesByHarness: 0 }
80
+ let mock
81
+ let before = []
82
+ let protectedIdentity
83
+ const watched = new Set()
84
+
85
+ function hash(bytes) { return crypto.createHash('sha256').update(bytes).digest('hex') }
86
+ function output(relative, value) {
87
+ const file = path.resolve(run, relative)
88
+ if (!file.startsWith(run + path.sep)) throw new Error('write outside isolated run')
89
+ fs.mkdirSync(path.dirname(file), { recursive: true })
90
+ fs.writeFileSync(file, typeof value === 'string' ? value : JSON.stringify(value, null, 2) + '\r\n', { mode: 0o600 })
91
+ }
92
+ function check(name, ok, detail = {}) {
93
+ report.checks.push({ name, ok: Boolean(ok), ...detail })
94
+ console.log(JSON.stringify({ check: name, ok: Boolean(ok) }))
95
+ }
96
+ function productionRead(file) {
97
+ const full = fs.realpathSync(file)
98
+ if (!full.startsWith(fs.realpathSync(production) + path.sep)) throw new Error('production read escaped named home')
99
+ watched.add(full)
100
+ return fs.readFileSync(full)
101
+ }
102
+ function fingerprint(file) {
103
+ const stat = fs.statSync(file)
104
+ return { file: path.relative(production, file), sha256: hash(fs.readFileSync(file)), bytes: stat.size,
105
+ mtimeMs: stat.mtimeMs }
106
+ }
107
+ function processIdentity(pid) {
108
+ if (process.platform !== 'win32') { process.kill(pid, 0); return { pid } }
109
+ const script = `$p=Get-Process -Id ${Number(pid)} -ErrorAction Stop; @{pid=$p.Id; name=$p.ProcessName; started=$p.StartTime.ToUniversalTime().ToString('o')} | ConvertTo-Json -Compress`
110
+ return JSON.parse(execFileSync('powershell.exe', ['-NoProfile', '-Command', script], { windowsHide: true, encoding: 'utf8' }))
111
+ }
112
+ function sourceFiles(root, prefix = '') {
113
+ return fs.readdirSync(root, { withFileTypes: true }).flatMap(entry => {
114
+ const relative = path.join(prefix, entry.name)
115
+ return entry.isDirectory() ? sourceFiles(path.join(root, entry.name), relative) : [relative]
116
+ }).sort()
117
+ }
118
+ function copySnapshot() {
119
+ let sourceRoot = repo
120
+ let previous
121
+ if (options['snapshot-from']) {
122
+ const origin = fs.realpathSync(path.resolve(repo, options['snapshot-from']))
123
+ if (!origin.startsWith(logsRoot) || !path.basename(origin).startsWith('recovery-host-')) throw new Error('snapshot origin must be an existing recovery-host run')
124
+ previous = JSON.parse(fs.readFileSync(path.join(origin, 'report.json'), 'utf8'))
125
+ sourceRoot = path.join(origin, 'home/profiles/recovery-host/node_modules/dsh-memu-memory')
126
+ }
127
+ const manifest = []
128
+ for (const root of ['lib', 'assets']) {
129
+ for (const relative of sourceFiles(path.join(sourceRoot, root))) {
130
+ const name = path.join(root, relative)
131
+ const source = fs.readFileSync(path.join(sourceRoot, name))
132
+ const target = path.join(snapshot, name)
133
+ fs.mkdirSync(path.dirname(target), { recursive: true })
134
+ fs.writeFileSync(target, source)
135
+ manifest.push({ file: name.replaceAll('\\', '/'), sha256: hash(source), bytes: source.length })
136
+ }
137
+ }
138
+ for (const name of ['package.json', 'cordis.patch.yml']) {
139
+ const source = fs.readFileSync(path.join(sourceRoot, name))
140
+ fs.writeFileSync(path.join(snapshot, name), source)
141
+ manifest.push({ file: name, sha256: hash(source), bytes: source.length })
142
+ }
143
+ report.source = { gitHead: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repo, encoding: 'utf8' }).trim(),
144
+ snapshotSha256: hash(JSON.stringify(manifest)), files: manifest.length,
145
+ pluginVersion: JSON.parse(fs.readFileSync(path.join(snapshot, 'package.json'), 'utf8')).version }
146
+ if (previous) {
147
+ if (report.source.snapshotSha256 !== previous.source?.snapshotSha256) throw new Error('prior snapshot manifest mismatch')
148
+ report.source.snapshotOriginRun = path.resolve(repo, options['snapshot-from'])
149
+ report.source.gitHead = previous.source.gitHead
150
+ }
151
+ output('source-manifest.json', manifest)
152
+ }
153
+ function cloneFixtures() {
154
+ const productionData = path.join(production, 'dsh-memu-memory')
155
+ const stateFile = path.join(productionData, 'state.json')
156
+ const state = JSON.parse(productionRead(stateFile))
157
+ const candidates = []
158
+ for (const [libraryId, library] of Object.entries(state.libraries || {})) {
159
+ if (!/^lib_[a-z0-9]+$/i.test(libraryId) || library.archived) continue
160
+ const file = path.join(productionData, 'index', libraryId + '.json')
161
+ if (!fs.existsSync(file)) continue
162
+ const raw = productionRead(file)
163
+ const index = JSON.parse(raw)
164
+ const eligible = Object.entries(index.entries || {}).filter(([, e]) => e.content && e.title
165
+ && (!e.status || e.status === 'active') && e.disclosure === 'can_tell' && e.visibility === 'shared'
166
+ && !e.marginalized && (!e.expiresAt || Date.parse(e.expiresAt) > Date.now())
167
+ && !Object.keys(e.context || {}).length)
168
+ if (eligible.length) candidates.push({ libraryId, library, file, raw, eligible })
169
+ }
170
+ const smallest = domain => candidates.filter(c => c.eligible.some(([, e]) => e.domain === domain))
171
+ .sort((a, b) => a.raw.length - b.raw.length)[0]
172
+ const coding = smallest('coding')
173
+ const rp = smallest('rp')
174
+ if (!coding || !rp || coding.libraryId === rp.libraryId) throw new Error('need separate eligible coding/rp libraries')
175
+ const selected = [coding, rp]
176
+ const safeState = { version: 1, settings: { memoryBackend: 'agent', memoryMode: 'local', autoInstallEngine: false,
177
+ sleepConsolidation: false, autoCurateEveryHours: 0, autoRepairEntityFragments: false, salientWake: 'off',
178
+ retentionDryRun: true, crossLibraryRecall: true, newSessionDefault: 'auto', newSessionPromptDismissed: true,
179
+ randomCueChance: 0, habitsInjection: false, relevanceThreshold: 0.01, consolidationTurnLog: 'off',
180
+ visionCaptionEnabled: false, autoLinkMode: 'off' }, libraries: {}, sessions: {}, workspacePolicies: {},
181
+ cycle: { entityRepairVersion: 1 } }
182
+ const fixtures = []
183
+ for (const [i, c] of selected.entries()) {
184
+ const domain = i === 0 ? 'coding' : 'rp'
185
+ const [id, entry] = c.eligible.find(([, e]) => e.domain === domain)
186
+ const scopePath = i === 0 ? workspace : path.join(workspace, 'rp-fixture')
187
+ const scopeKey = scopePath.replaceAll('\\', '/').replace(/\/$/, '').toLowerCase()
188
+ fs.mkdirSync(scopePath, { recursive: true })
189
+ safeState.libraries[c.libraryId] = { name: `Isolated fixture ${domain}`, scopeKey,
190
+ createdAt: c.library.createdAt, lastUsedAt: new Date().toISOString(), archived: false }
191
+ output(path.relative(run, path.join(data, 'index', c.libraryId + '.json')), c.raw.toString('utf8'))
192
+ const sessionId = `recovery-host-${domain}`
193
+ safeState.sessions[sessionId] = { useLibrary: true, useGlobal: false, libraryId: c.libraryId, scopeKey,
194
+ domain, domainOverride: domain, injectedIds: [], injectedAt: {}, lastInjectedTurn: 0, reinjectPending: false }
195
+ safeState.workspacePolicies[scopeKey] = { useLibrary: true, useGlobal: false }
196
+ fixtures.push({ libraryId: c.libraryId, id, domain, sessionId, query: entry.title,
197
+ originalIndexSha256: hash(c.raw), originalEntries: Object.keys(JSON.parse(c.raw).entries).length })
198
+ }
199
+ // A small existing durable log is copied as bytes; it is never resumed or sent to a provider.
200
+ const sessionsRoot = path.join(production, 'sessions')
201
+ const eligibleSessions = Object.keys(state.sessions || {}).map(sessionId => {
202
+ const file = locateSessionLog({ dshHome: production, sessionId })
203
+ return file ? { sessionId, file, bytes: fs.statSync(file).size } : null
204
+ }).filter(item => item && item.bytes > 0).sort((a, b) => a.bytes - b.bytes)
205
+ const preferred = eligibleSessions.filter(item => selected.some(c => state.sessions[item.sessionId]?.libraryId === c.libraryId))
206
+ const session = [...preferred, ...eligibleSessions.filter(item => !preferred.includes(item))].find(item => {
207
+ if (item.bytes < 1000 || item.bytes > 2 * 1024 * 1024) return false
208
+ try { return readSessionEvents(item.file).some(event => event.type === 'user/message' && event.data?.source?.kind !== 'plugin:dsh-memu-memory') } catch { return false }
209
+ })
210
+ if (!session) throw new Error('no bound production session log')
211
+ const sessionRaw = productionRead(session.file)
212
+ const isolatedLog = path.join(run, 'fixtures', 'existing-session.v4.jsonl.zstd')
213
+ fs.mkdirSync(path.dirname(isolatedLog), { recursive: true })
214
+ fs.writeFileSync(isolatedLog, sessionRaw, { mode: 0o600 })
215
+ const events = readSessionEvents(isolatedLog)
216
+ const eventTypes = {}
217
+ for (const event of events) eventTypes[event.type || 'unknown'] = (eventTypes[event.type || 'unknown'] || 0) + 1
218
+ report.existingSession = { sourcePathSha256: hash(path.relative(sessionsRoot, session.file)), bytes: sessionRaw.length,
219
+ sha256: hash(sessionRaw), events: events.length, eventTypes, replayed: false }
220
+ check('existing-session-copy-decodes', events.length > 0, { events: events.length, bytes: sessionRaw.length })
221
+ output('home/dsh-memu-memory/state.json', safeState)
222
+ output('home/dsh-memu-memory/index/global.json', { version: 1, entries: {} })
223
+ output('fixtures/private.json', fixtures)
224
+ report.fixtures = fixtures.map(({ query, ...value }) => value)
225
+ // Watch config and credential bytes without parsing, copying, or printing their values.
226
+ for (const relative of ['profiles/web/package.json', 'profiles/web/cordis.patch.yml', 'cordis.patch.yml', '.credentials.yaml']) {
227
+ const file = path.join(production, relative)
228
+ if (fs.existsSync(file)) watched.add(file)
229
+ }
230
+ before = [...watched].map(fingerprint)
231
+ output('production-before.json', before)
232
+ }
233
+ function loaderSource() {
234
+ return `import { registerHooks, createRequire } from 'node:module'\nimport { pathToFileURL } from 'node:url'\nconst anchors = ${JSON.stringify([hostAnchor, path.join(repo, 'package.json')])}.map(value => createRequire(value))\nconst resolving = new Set()\nregisterHooks({ resolve(specifier, context, next) {\n try { return next(specifier, context) } catch (error) {\n if (error.code !== 'ERR_MODULE_NOT_FOUND' || specifier.startsWith('.') || specifier.startsWith('/') || specifier.includes(':') || resolving.has(specifier)) throw error\n resolving.add(specifier)\n try {\n for (const anchor of anchors) { try { return next(pathToFileURL(anchor.resolve(specifier)).href, context) } catch {} }\n throw error\n } finally { resolving.delete(specifier) }\n }\n} })\n`
235
+ }
236
+ function cleanEnvironment() {
237
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/(?:API[_-]?KEY|TOKEN|SECRET|CREDENTIAL|PASSWORD|^DSH_|^MEMU_|PROXY|^NODE_OPTIONS$|^NODE_PATH$)/i.test(key)))
238
+ return { ...env, DSH_HOME: home, DSH_MEMU_HOME: data, DSH_MEMU_MEMORY_HOME: data,
239
+ DSH_TELEMETRY_DISABLED: '1', DSH_MEMU_RT_INDEX: 'shadow', NO_PROXY: '127.0.0.1,localhost',
240
+ NODE_OPTIONS: `--import=${pathToFileURL(path.join(run, 'runtime-loader.mjs')).href}` }
241
+ }
242
+ function modelPatch(port) {
243
+ return `- id: llm-pi-ai\n name: '@deepseek-ai/dsh-llm-pi-ai'\n config:\n providers:\n memu-mock:\n displayName: Isolated mock\n api: openai-completions\n baseURL: http://127.0.0.1:${port}/v1\n headers:\n Authorization: Bearer local-mock\n models:\n - id: dsh-mock-llm\n name: Isolated mock\n contextWindow: 128000\n maxTokens: 4096\n reasoningEfforts: false\n- id: agent-default-model\n config:\n provider: memu-mock\n model: dsh-mock-llm\n`
244
+ }
245
+ function createProfile(kind, port) {
246
+ output(`home/profiles/${profileName}/package.json`, { name: 'dsh-profile-recovery-host', private: true,
247
+ dependencies: { 'dsh-memu-memory': '1.4.4' }, dsh: { profile: { bundles: ['@deepseek-ai/dsh-base',
248
+ kind === 'web' ? '@deepseek-ai/dsh-web-app' : '@deepseek-ai/dsh-headless', 'dsh-memu-memory'] } } })
249
+ output(`home/profiles/${profileName}/cordis.patch.yml`, modelPatch(port))
250
+ }
251
+ function launch(label, args, env) {
252
+ const stdout = fs.openSync(path.join(run, label + '.stdout.log'), 'wx', 0o600)
253
+ const stderr = fs.openSync(path.join(run, label + '.stderr.log'), 'wx', 0o600)
254
+ const child = spawn(process.execPath, args, { cwd: workspace, env, windowsHide: true, stdio: ['ignore', stdout, stderr] })
255
+ fs.closeSync(stdout)
256
+ fs.closeSync(stderr)
257
+ children.add(child)
258
+ report.launchedProcesses ??= []
259
+ const processRecord = { label, pid: child.pid, closed: false }
260
+ report.launchedProcesses.push(processRecord)
261
+ let resolveCompletion
262
+ const completion = new Promise(resolve => { resolveCompletion = resolve })
263
+ const job = { child, completion, processRecord }
264
+ jobsByChild.set(child, job)
265
+ child.once('error', error => {
266
+ processRecord.errorCode = error.code || error.name
267
+ resolveCompletion({ code: null, errorCode: processRecord.errorCode })
268
+ })
269
+ child.once('close', (code, signal) => {
270
+ children.delete(child)
271
+ processRecord.closed = true
272
+ processRecord.exitCode = code
273
+ processRecord.signal = signal
274
+ resolveCompletion({ code, signal, errorCode: processRecord.errorCode })
275
+ })
276
+ return job
277
+ }
278
+ async function terminateOwnedProcess(job) {
279
+ const child = job?.child
280
+ if (!children.has(child)) return { pid: child?.pid ?? null, closed: true, alreadyClosed: true }
281
+ if (!isOwnedChild(child, children, protectedPid)) {
282
+ return { pid: child?.pid ?? null, closed: false, reason: 'not-an-owned-unprotected-child' }
283
+ }
284
+
285
+ let treeTermination = null
286
+ if (process.platform === 'win32') {
287
+ try {
288
+ const result = spawnSync('taskkill.exe', taskkillArguments(child.pid), {
289
+ windowsHide: true, stdio: 'ignore', timeout: TASKKILL_TIMEOUT_MS,
290
+ })
291
+ treeTermination = { status: result.status, signal: result.signal, errorCode: result.error?.code }
292
+ } catch (error) {
293
+ treeTermination = { status: null, signal: null, errorCode: error.code || error.name }
294
+ }
295
+ } else {
296
+ child.kill('SIGTERM')
297
+ }
298
+
299
+ let closeOutcome = await waitBounded(job.completion, PROCESS_CLOSE_TIMEOUT_MS)
300
+ if (closeOutcome.timedOut && process.platform !== 'win32') {
301
+ child.kill('SIGKILL')
302
+ closeOutcome = await waitBounded(job.completion, PROCESS_CLOSE_TIMEOUT_MS)
303
+ }
304
+ return { pid: child.pid, closed: !closeOutcome.timedOut && !children.has(child),
305
+ treeTermination, closeTimedOut: Boolean(closeOutcome.timedOut) }
306
+ }
307
+ async function bounded(job, timeoutMs = 90000) {
308
+ const outcome = await waitBounded(job.completion, timeoutMs)
309
+ if (outcome.timedOut) {
310
+ return { code: null, ...outcome, termination: await terminateOwnedProcess(job) }
311
+ }
312
+ return outcome
313
+ }
314
+ async function waitFor(predicate, ms = 90000) {
315
+ const deadline = Date.now() + ms
316
+ while (Date.now() < deadline) {
317
+ const result = await predicate()
318
+ if (result) return result
319
+ await new Promise(resolve => setTimeout(resolve, 200))
320
+ }
321
+ throw Object.assign(new Error('isolated host readiness timeout'), { code: 'HOST_READINESS_TIMEOUT' })
322
+ }
323
+ async function freePort() {
324
+ const server = net.createServer()
325
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })
326
+ const port = server.address().port
327
+ await new Promise(resolve => server.close(resolve))
328
+ return port
329
+ }
330
+ async function rpc(base, cookie, method, payload = {}) {
331
+ const rpcId = crypto.randomUUID()
332
+ const response = await fetch(base + '/dsh-memu-memory/' + method, { method: 'POST',
333
+ headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) },
334
+ body: JSON.stringify({ type: 'client-request', rpcId, method, payload }), signal: AbortSignal.timeout(15000) })
335
+ const body = await response.json().catch(() => null)
336
+ return { status: response.status, ok: response.ok && body?.result?.ok === true,
337
+ value: body?.result?.value, code: body?.result?.error?.code,
338
+ notFound: payload.query && body?.result?.error?.message === 'unknown memory: ' + payload.query }
339
+ }
340
+ function verifyDiagnosticReport(response) {
341
+ const value = response.value || {}
342
+ const { text, ...fields } = value
343
+ let copied
344
+ try { copied = JSON.parse(text) } catch {}
345
+ check('web-rpc-diagnostic-report-contract', response.status === 200 && response.ok
346
+ && value.schemaVersion === 1 && value.schema === 'dsh-memu-memory/diagnostic-report@1'
347
+ && value.redacted === true && Number.isFinite(Date.parse(value.generatedAt))
348
+ && typeof text === 'string' && JSON.stringify(copied) === JSON.stringify(fields), { status: response.status })
349
+
350
+ const metadataBytes = fs.readFileSync(hostAnchor)
351
+ const metadata = JSON.parse(metadataBytes)
352
+ const runningEntryMatches = fs.realpathSync(hostBin).startsWith(fs.realpathSync(path.dirname(hostAnchor)) + path.sep)
353
+ const host = value.runtime?.host
354
+ const plugin = value.runtime?.plugin
355
+ const hostMatches = runningEntryMatches && metadata.name === '@deepseek-ai/dsh' && metadata.version === '0.2.2-rc.5'
356
+ && report.host.version === metadata.version && host?.version === metadata.version && host.package === metadata.name
357
+ && host.source === 'running-entry/package.json' && host.status === 'observed'
358
+ const pluginMatches = report.source.pluginVersion === '1.4.4' && plugin?.name === 'dsh-memu-memory'
359
+ && plugin.version === report.source.pluginVersion && plugin.source === 'plugin/package.json'
360
+ check('web-rpc-diagnostic-runtime-identity', hostMatches && pluginMatches, { hostMatches, pluginMatches, runningEntryMatches,
361
+ entryMetadataSha256: hash(metadataBytes) })
362
+
363
+ const names = ['host', 'plugin', 'engine', 'vector', 'state', 'rpc', 'workers']
364
+ const components = value.components || {}
365
+ const statuses = ['observed', 'skipped', 'not-built', 'unknown', 'absent', 'installing', 'error', 'degraded']
366
+ const items = Array.isArray(value.environment?.items) ? value.environment.items : []
367
+ check('web-rpc-diagnostic-seven-layers', Object.keys(components).length === names.length
368
+ && names.every(name => statuses.includes(components[name]?.status) && components[name]?.source === name
369
+ && components[name]?.evidence && typeof components[name].evidence === 'object')
370
+ && items.length === names.length && names.every(name => items.filter(item => item.id === name).length === 1))
371
+ const optionalSkipped = ['engine', 'vector'].every(name => components[name]?.status === 'skipped'
372
+ && components[name]?.evidence?.route === 'lexical' && components[name]?.code === null
373
+ && components[name]?.error === null && items.find(item => item.id === name)?.level === 'skipped')
374
+ check('web-rpc-diagnostic-optional-engine-vector-skipped', optionalSkipped
375
+ && components.engine?.evidence?.required === false && components.engine?.evidence?.affectsCurrentRoute === false
376
+ && components.vector?.evidence?.active === false)
377
+
378
+ const unverified = names.filter(name => ['unknown', 'absent', 'installing'].includes(components[name]?.status))
379
+ const counts = { ok: 0, warn: 0, error: 0, skipped: 0 }
380
+ for (const name of names) {
381
+ const status = components[name]?.status
382
+ counts[status === 'observed' ? 'ok' : status === 'error' ? 'error' : status === 'degraded' ? 'warn' : 'skipped']++
383
+ }
384
+ const health = value.health
385
+ const coverage = health?.coverage
386
+ const expectedStatus = counts.error ? 'error' : counts.warn ? 'degraded' : unverified.length ? 'unknown' : 'observed'
387
+ check('web-rpc-diagnostic-health-coverage', coverage?.total === names.length && coverage?.observed === counts.ok
388
+ && Array.isArray(coverage?.unverified) && JSON.stringify([...coverage.unverified].sort()) === JSON.stringify([...unverified].sort())
389
+ && Object.entries(counts).every(([key, count]) => health?.counts?.[key] === count)
390
+ && health?.status === expectedStatus && health?.ok === (counts.error === 0)
391
+ && typeof health?.attention === 'boolean' && Array.isArray(health?.limitations) && health.limitations.length > 0
392
+ && components.workers?.evidence?.residentPython?.status === 'unknown'
393
+ && components.workers?.evidence?.consolidation?.processHealth === 'unknown'
394
+ && unverified.every(name => items.find(item => item.id === name)?.ok === false))
395
+ // Persist only fixed labels/counts and a digest, never the report or its text.
396
+ report.web.diagnostics = { method: 'getDiagnosticReport', transport: 'same-origin-http',
397
+ hostVersion: hostMatches ? '0.2.2-rc.5' : null, pluginVersion: pluginMatches ? '1.4.4' : null,
398
+ componentStatuses: Object.fromEntries(names.map(name => [name, statuses.includes(components[name]?.status) ? components[name].status : null])),
399
+ coverage: { observed: coverage?.observed === counts.ok ? counts.ok : null, total: names.length, unverified },
400
+ textSha256: typeof text === 'string' ? hash(text) : null }
401
+ }
402
+ async function main() {
403
+ protectedIdentity = processIdentity(protectedPid)
404
+ report.productionProcessBefore = protectedIdentity
405
+ for (const dir of [home, data, workspace, snapshot]) fs.mkdirSync(dir, { recursive: true })
406
+ copySnapshot()
407
+ cloneFixtures()
408
+ output('runtime-loader.mjs', loaderSource())
409
+ const env = cleanEnvironment()
410
+ report.host = { bin: hostBin, binSha256: hash(fs.readFileSync(hostBin)), node: process.version, peerStubs: false }
411
+ const version = await bounded(launch('host-version', [hostBin, '--version'], env))
412
+ const hostVersion = fs.readFileSync(path.join(run, 'host-version.stdout.log'), 'utf8').trim()
413
+ report.host.version = /^\d+\.\d+\.\d+[-.a-z0-9]*$/i.test(hostVersion) ? hostVersion : null
414
+ check('installed-host-version', version.code === 0 && hostVersion === '0.2.2-rc.5', { version: report.host.version })
415
+ mock = await startMockLlm({ port: 0, log: path.join(run, 'mock-llm.jsonl'), reply: 'Isolated host acceptance completed.' })
416
+ createProfile('headless', mock.port)
417
+ const dump = await bounded(launch('dumpconfig', [hostBin, '--profile', profileName, '--dump-config'], env))
418
+ const dumped = fs.readFileSync(path.join(run, 'dumpconfig.stdout.log'), 'utf8')
419
+ check('dumpconfig-plugin-loaded', dump.code === 0 && /name: dsh-memu-memory/.test(dumped), { exitCode: dump.code })
420
+ if (options.only !== 'web') {
421
+ const fixtureRun = await bounded(launch('fixtures', ['--import', pathToFileURL(path.join(run, 'runtime-loader.mjs')).href,
422
+ path.join(repo, 'scripts/verify-host-fixtures.mjs'), '--run=' + run], env))
423
+ check('copied-real-data-and-privacy', fixtureRun.code === 0, { exitCode: fixtureRun.code })
424
+ if (fixtureRun.code !== 0) throw Object.assign(new Error('fixture validation failed'), { code: 'FIXTURE_VALIDATION_FAILED' })
425
+ const task = 'Verify the existing project memory relevant to this isolated acceptance task. Reply briefly.'
426
+ let headlessSessionId
427
+ for (let turn = 1; turn <= 2; turn += 1) {
428
+ const headless = await bounded(launch('headless-' + turn, [hostBin, '--profile', profileName, '--json',
429
+ ...(headlessSessionId ? ['--session-id', headlessSessionId] : []), task], env))
430
+ check('headless-process-' + turn, headless.code === 0, { exitCode: headless.code, timedOut: headless.timedOut || false })
431
+ if (headless.code !== 0) throw Object.assign(new Error('headless host turn failed'), { code: 'HEADLESS_FAILED' })
432
+ if (!headlessSessionId) {
433
+ const lines = fs.readFileSync(path.join(run, 'headless-1.stdout.log'), 'utf8').split(/\r?\n/)
434
+ for (const line of lines) {
435
+ try { const item = JSON.parse(line); if (item.type === 'session') headlessSessionId = item.sessionId } catch {}
436
+ }
437
+ if (!headlessSessionId) throw Object.assign(new Error('headless session event missing'), { code: 'HEADLESS_SESSION_MISSING' })
438
+ }
439
+ }
440
+ const file = locateSessionLog({ dshHome: home, sessionId: headlessSessionId })
441
+ const events = file ? readSessionEvents(file) : []
442
+ const headers = events.filter(event => event.type === 'request/header').map(event => event.data?.header)
443
+ const toolNames = headers.map(header => (header?.tools || []).map(tool => tool.name).filter(name => name?.startsWith('memu_')).sort())
444
+ const pluginMessages = events.filter(event => event.type === 'user/message' && event.data?.source?.kind === 'plugin:dsh-memu-memory')
445
+ const guides = pluginMessages.filter(event => JSON.stringify(event.data).includes('<memory-guide'))
446
+ const guideIds = [...new Set(guides.map(event => event.data?.id || event.seq))]
447
+ const endings = events.filter(event => event.type === 'turn/end').map(event => event.data?.reason?.kind)
448
+ report.headless = { events: events.length, toolNames, guideUniqueIds: guideIds, pluginMessages: pluginMessages.length, endings }
449
+ const expectedNativeTools = new Set([
450
+ 'memu_global_list', 'memu_global_recall', 'memu_lexicon_propose', 'memu_lexicon_search',
451
+ 'memu_private_archive', 'memu_private_entity_merge_decide', 'memu_private_entity_merge_suggest',
452
+ 'memu_private_feedback', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_list',
453
+ 'memu_private_recall', 'memu_private_remember', 'memu_private_remember_batch', 'memu_private_unpin',
454
+ 'memu_private_update', 'memu_status',
455
+ ])
456
+ const nativeToolDiff = names => ({
457
+ missing: [...expectedNativeTools].filter(name => !names.includes(name)),
458
+ extra: names.filter(name => !expectedNativeTools.has(name)),
459
+ })
460
+ check('headless-native-tool-schema', toolNames.length >= 2 && toolNames.every(names => {
461
+ const diff = nativeToolDiff(names)
462
+ return names.length === expectedNativeTools.size && diff.missing.length === 0 && diff.extra.length === 0
463
+ }), {
464
+ counts: toolNames.map(names => names.length),
465
+ toolDiffs: toolNames.map(nativeToolDiff),
466
+ })
467
+ check('headless-main-agent-global-read-only', toolNames.length >= 2 && toolNames.every(names =>
468
+ names.filter(name => name.startsWith('memu_global_')).every(name => ['memu_global_list', 'memu_global_recall'].includes(name))
469
+ && names.includes('memu_private_feedback')))
470
+ check('headless-guide-once-across-two-turns', guideIds.length === 1, { guides: guideIds.length })
471
+ check('headless-turns-completed', endings.length === 2 && endings.every(kind => kind === 'completed'), { endings })
472
+ const mockRecords = fs.readFileSync(path.join(run, 'mock-llm.jsonl'), 'utf8').trim().split(/\r?\n/).map(line => JSON.parse(line))
473
+ report.mock = { requests: mockRecords.length, records: mockRecords.map(item => ({
474
+ type: item.type, model: item.model, markers: item.markers,
475
+ guideInSystem: (item.parts || []).some(part => part.role === 'system' && part.markers?.guide > 0),
476
+ })) }
477
+ check('mock-guide-never-system-prompt', mockRecords.length >= 2 && report.mock.records.every(item => !item.guideInSystem))
478
+ }
479
+ const webPort = await freePort()
480
+ createProfile('web', mock.port)
481
+ const web = launch('web', [hostBin, '--profile', profileName, '--no-open', '--host', '127.0.0.1', '--port', String(webPort)], env)
482
+ const base = 'http://127.0.0.1:' + webPort
483
+ // Launcher stdout is private evidence because it contains a one-use local token.
484
+ const tokenUrl = await waitFor(() => {
485
+ const log = fs.readFileSync(path.join(run, 'web.stdout.log'), 'utf8')
486
+ return log.match(/http:\/\/[^\s]+\?token=[^\s]+/)?.[0]
487
+ })
488
+ if (new URL(tokenUrl).origin !== base) throw Object.assign(new Error('isolated authentication origin mismatch'), { code: 'AUTH_ORIGIN_MISMATCH' })
489
+ report.stage = 'web-authentication'
490
+ const auth = await fetch(tokenUrl, { redirect: 'manual', signal: AbortSignal.timeout(45000) })
491
+ const cookie = auth.headers.getSetCookie().map(item => item.split(';')[0]).join('; ')
492
+ check('web-authentication-cookie', auth.status === 303 && Boolean(cookie), { status: auth.status, cookieObtained: Boolean(cookie) })
493
+ report.web = { base, cookieObtained: Boolean(cookie), credentialsPrinted: false }
494
+ report.stage = 'web-rpc'
495
+ const settings = await rpc(base, cookie, 'getSettingsState')
496
+ check('webui-rpc-settings', settings.ok, { status: settings.status, code: settings.code })
497
+ report.stage = 'web-diagnostic-report'
498
+ verifyDiagnosticReport(await rpc(base, cookie, 'getDiagnosticReport', { limit: 100 }))
499
+ report.stage = 'web-rpc'
500
+ for (const route of ['/dsh-memu-memory/ui', '/dsh-memu-memory/settings', '/dsh-memu-memory/ui-assets/graph-view.js']) {
501
+ const response = await fetch(base + route, { headers: { cookie }, signal: AbortSignal.timeout(5000) })
502
+ const bytes = (await response.arrayBuffer()).byteLength
503
+ check('webui-static-' + route.split('/').at(-1), response.ok && bytes > 0, { status: response.status, bytes })
504
+ }
505
+ const fixtures = JSON.parse(fs.readFileSync(path.join(run, 'fixtures/private.json'), 'utf8'))
506
+ for (const fixture of fixtures) {
507
+ const recall = await rpc(base, cookie, 'testRetrieval', { sessionId: fixture.sessionId, query: fixture.id, scope: 'private' })
508
+ const actualIds = (recall.value?.files || []).map(item => item.id)
509
+ check('web-rpc-real-id-' + fixture.domain, recall.ok && actualIds.includes(fixture.id), { expectedId: fixture.id, actualIds, status: recall.status })
510
+ }
511
+ const cross = await rpc(base, cookie, 'testRetrieval', { sessionId: fixtures[0].sessionId, query: fixtures[1].id, scope: 'private' })
512
+ const crossIds = (cross.value?.files || []).map(item => item.id)
513
+ check('web-rpc-cross-domain-denied', (cross.ok || cross.notFound) && !crossIds.includes(fixtures[1].id),
514
+ { forbiddenId: fixtures[1].id, actualIds: crossIds, deniedAsUnknown: Boolean(cross.notFound) })
515
+ report.webProcessCleanup = await terminateOwnedProcess(web)
516
+ check('web-process-stopped', report.webProcessCleanup.closed, { pid: report.webProcessCleanup.pid })
517
+ report.browserVerification = 'not performed; main agent owns browser verification'
518
+ }
519
+
520
+ try { await main() } catch (error) {
521
+ report.failure = { code: error.code || error.name || 'ERROR', name: error.name, stage: report.stage }
522
+ console.error(JSON.stringify({ failed: true, code: report.failure.code }))
523
+ } finally {
524
+ const cleanupResults = await Promise.all([...children].map(child => terminateOwnedProcess(jobsByChild.get(child))))
525
+ if (mock) await mock.close()
526
+ report.cleanup = { ownChildrenRemaining: children.size, ownChildren: cleanupResults,
527
+ mockClosed: !mock || !mock.server.listening }
528
+ check('owned-processes-cleaned-with-bounded-waits', children.size === 0 && cleanupResults.every(item => item.closed),
529
+ { remaining: children.size, processCount: cleanupResults.length })
530
+ if (before.length) {
531
+ const after = before.map(item => fingerprint(path.join(production, item.file)))
532
+ output('production-after.json', after)
533
+ report.productionAudit = before.map((item, i) => ({ file: item.file, unchanged: item.sha256 === after[i].sha256,
534
+ beforeSha256: item.sha256, afterSha256: after[i].sha256, beforeBytes: item.bytes, afterBytes: after[i].bytes,
535
+ productionRemainedLive: true, harnessWrote: false }))
536
+ check('production-static-config-unchanged', report.productionAudit.filter(item => /(?:package\.json|patch\.yml|credentials\.yaml)$/.test(item.file)).every(item => item.unchanged))
537
+ report.productionDynamicChanges = report.productionAudit.filter(item => !item.unchanged).map(item => item.file)
538
+ }
539
+ if (report.source) {
540
+ const manifest = JSON.parse(fs.readFileSync(path.join(run, 'source-manifest.json'), 'utf8'))
541
+ const changes = manifest.filter(item => {
542
+ const file = path.join(repo, item.file)
543
+ return !fs.existsSync(file) || hash(fs.readFileSync(file)) !== item.sha256
544
+ }).map(item => item.file)
545
+ const known = new Set(manifest.map(item => item.file))
546
+ for (const root of ['lib', 'assets']) {
547
+ for (const relative of sourceFiles(path.join(repo, root))) {
548
+ const file = path.join(root, relative).replaceAll('\\', '/')
549
+ if (!known.has(file)) changes.push(file)
550
+ }
551
+ }
552
+ report.source.currentTreeMatches = changes.length === 0
553
+ report.source.changedFilesDuringRun = changes
554
+ if (report.phase.startsWith('frozen')) check('frozen-source-did-not-drift', changes.length === 0, { changedFiles: changes })
555
+ }
556
+ try {
557
+ report.productionProcessAfter = processIdentity(protectedPid)
558
+ check('production-process-preserved', JSON.stringify(protectedIdentity) === JSON.stringify(report.productionProcessAfter))
559
+ } catch { check('production-process-preserved', false) }
560
+ report.finishedAt = new Date().toISOString()
561
+ report.ok = !report.failure && report.checks.every(item => item.ok)
562
+ output('report.json', report)
563
+ console.log(JSON.stringify({ ok: report.ok, report: path.join(run, 'report.json'), source: report.source?.snapshotSha256 }))
564
+ process.exitCode = report.ok ? 0 : 1
565
+ }