dsh-memu-memory 1.4.3 → 1.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +34 -15
  4. package/README.zh.md +35 -13
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/libraries.jpg +0 -0
  7. package/assets/screenshots/mobile.jpg +0 -0
  8. package/assets/screenshots/relations.jpg +0 -0
  9. package/assets/screenshots/settings.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +19 -3
  13. package/docs/contributing.md +4 -2
  14. package/docs/env-and-commands.md +9 -1
  15. package/docs/graph-scale.md +214 -0
  16. package/docs/lexicon-recall.md +100 -0
  17. package/docs/mcp-porting.md +8 -6
  18. package/docs/memory-semantics.md +35 -3
  19. package/docs/pending-work.md +3 -1
  20. package/docs/retention.md +83 -0
  21. package/docs/rt-index.md +452 -0
  22. package/docs/scale-performance.md +101 -0
  23. package/docs/token-budget.md +92 -0
  24. package/docs/troubleshooting.md +50 -11
  25. package/lib/auto-link/apply.js +7 -2
  26. package/lib/auto-link/candidates.js +32 -10
  27. package/lib/backup.js +67 -32
  28. package/lib/binding-diagnostics.js +1 -1
  29. package/lib/bounded-cache.js +80 -0
  30. package/lib/client.js +2096 -409
  31. package/lib/consolidation-ledger.js +21 -4
  32. package/lib/consolidation-worker.js +14 -1
  33. package/lib/cycle.js +16 -11
  34. package/lib/diagnostic-context.js +372 -0
  35. package/lib/diagnostics.js +147 -61
  36. package/lib/embedding-download.js +7 -8
  37. package/lib/engine-sources.js +286 -0
  38. package/lib/engine.js +23 -10
  39. package/lib/entity-repair.js +43 -13
  40. package/lib/entity-review.js +64 -0
  41. package/lib/environment-check.js +348 -36
  42. package/lib/feedback.js +25 -0
  43. package/lib/global-graph.js +46 -2
  44. package/lib/graph-adjacency-index.js +525 -0
  45. package/lib/graph-overview.js +293 -0
  46. package/lib/graph.js +658 -105
  47. package/lib/inbound.js +44 -15
  48. package/lib/index-pages.js +57 -0
  49. package/lib/index.js +44 -6
  50. package/lib/inject.js +119 -50
  51. package/lib/lexicon-rt-source.js +25 -0
  52. package/lib/lexicon-rt-worker.js +26 -0
  53. package/lib/lexicon-rt.js +224 -0
  54. package/lib/lexicon-scope.js +56 -5
  55. package/lib/lexicon.js +143 -54
  56. package/lib/local-vector-service.js +3 -0
  57. package/lib/maintenance-ledger.js +542 -12
  58. package/lib/managed-runtime.js +260 -80
  59. package/lib/media.js +1 -1
  60. package/lib/memory.js +564 -131
  61. package/lib/port-surface.js +96 -11
  62. package/lib/preset-mount.js +13 -7
  63. package/lib/private.js +47 -21
  64. package/lib/recall-cache.js +20 -34
  65. package/lib/retention.js +173 -0
  66. package/lib/rpc.js +135 -52
  67. package/lib/rt-index/builder.js +209 -0
  68. package/lib/rt-index/format.js +231 -0
  69. package/lib/rt-index/manifest.js +105 -0
  70. package/lib/rt-index/reader.js +673 -0
  71. package/lib/rt-index-retention.js +151 -0
  72. package/lib/rt-index-service.js +283 -0
  73. package/lib/rt-index-worker.js +21 -0
  74. package/lib/salient-wake.js +55 -4
  75. package/lib/state.js +195 -24
  76. package/lib/temporal.js +39 -13
  77. package/lib/token-measurement.js +126 -0
  78. package/lib/tools.js +101 -6
  79. package/lib/turn-log.js +108 -3
  80. package/lib/webui/graph-layout-worker.js +68 -0
  81. package/lib/webui/graph-local-physics.js +390 -0
  82. package/lib/webui/graph-spatial-grid.js +64 -0
  83. package/lib/webui/graph-view.bundle.js +6 -1
  84. package/lib/webui/graph-view.js +478 -135
  85. package/lib/webui/graph-webgl-renderer.js +74 -0
  86. package/lib/webui/standalone.js +1 -1
  87. package/lib/worker-pool.js +38 -7
  88. package/package.json +3 -2
  89. package/scripts/acceptance-local.mjs +4 -10
  90. package/scripts/bench-all-libraries.mjs +47 -0
  91. package/scripts/check-classic-graph-browser.mjs +189 -0
  92. package/scripts/check-client-browser.mjs +929 -0
  93. package/scripts/check-graph-browser.mjs +6 -0
  94. package/scripts/check-graph-elastic-browser.mjs +139 -0
  95. package/scripts/check-memory-review-browser.mjs +124 -0
  96. package/scripts/entity-dedupe.mjs +19 -3
  97. package/scripts/graph-artifact-provenance.mjs +30 -0
  98. package/scripts/graph-freeze-manifest.mjs +129 -0
  99. package/scripts/graph-geometry-fixture.mjs +40 -0
  100. package/scripts/graph-physics-bench.mjs +218 -0
  101. package/scripts/graph-scale-bench.mjs +213 -0
  102. package/scripts/graph-scale-memory.mjs +48 -0
  103. package/scripts/graph-service-bench.mjs +72 -0
  104. package/scripts/make-readme-shots.mjs +17 -5
  105. package/scripts/preview.mjs +1 -0
  106. package/scripts/rebuild-rt.mjs +18 -0
  107. package/scripts/scale-bench.mjs +183 -0
  108. package/scripts/simulate-injection.mjs +47 -8
  109. package/scripts/verify-host-fixtures.mjs +108 -0
  110. package/scripts/verify-host-recovery.mjs +565 -0
  111. package/scripts/verify-vector-recovery.mjs +740 -0
  112. package/tests/auto-link-candidates.test.mjs +20 -0
  113. package/tests/browser.test.mjs +16 -2
  114. package/tests/client-export.test.mjs +16 -1
  115. package/tests/client-pagination.test.mjs +1495 -0
  116. package/tests/client-render.test.mjs +223 -28
  117. package/tests/consolidation-fork.test.mjs +97 -13
  118. package/tests/consolidation-ledger.test.mjs +17 -1
  119. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  120. package/tests/diagnostic-report.test.mjs +429 -0
  121. package/tests/diagnostic-wiring.test.mjs +88 -0
  122. package/tests/diagnostics.test.mjs +27 -0
  123. package/tests/embedding-download.test.mjs +44 -0
  124. package/tests/engine-source-settings.test.mjs +69 -0
  125. package/tests/engine-sources.test.mjs +145 -0
  126. package/tests/entity-dedupe.test.mjs +143 -0
  127. package/tests/entity-merge-review.test.mjs +363 -0
  128. package/tests/entity-merge.test.mjs +12 -4
  129. package/tests/entity-review.test.mjs +87 -0
  130. package/tests/environment-check.test.mjs +51 -1
  131. package/tests/feedback.test.mjs +95 -0
  132. package/tests/graph-adjacency-index.test.mjs +536 -0
  133. package/tests/graph-cascade.test.mjs +229 -0
  134. package/tests/graph-import-diagnostic.test.mjs +25 -0
  135. package/tests/graph-overview.test.mjs +709 -0
  136. package/tests/graph-session-authorization.test.mjs +419 -0
  137. package/tests/graph-view-geometry.test.mjs +426 -0
  138. package/tests/graph-view-scale.test.mjs +88 -0
  139. package/tests/graph-view.test.mjs +444 -5
  140. package/tests/graph.test.mjs +43 -0
  141. package/tests/help-page.test.mjs +128 -54
  142. package/tests/inbound.test.mjs +19 -0
  143. package/tests/index-pagination.test.mjs +113 -0
  144. package/tests/index-read-view.test.mjs +212 -0
  145. package/tests/inject-guide.test.mjs +9 -0
  146. package/tests/injection-dedupe.test.mjs +213 -0
  147. package/tests/lexicon-recall.test.mjs +641 -0
  148. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  149. package/tests/lexicon-rt.test.mjs +468 -0
  150. package/tests/local-embedding-worker.test.mjs +38 -0
  151. package/tests/local-vector-service.test.mjs +32 -3
  152. package/tests/maintenance-compat.test.mjs +128 -0
  153. package/tests/maintenance-settlement.test.mjs +1003 -0
  154. package/tests/managed-memory.test.mjs +39 -11
  155. package/tests/managed-runtime.test.mjs +109 -0
  156. package/tests/memory-fields.test.mjs +24 -12
  157. package/tests/observed-evidence.test.mjs +52 -0
  158. package/tests/port-surface.test.mjs +93 -1
  159. package/tests/preset-mount.test.mjs +12 -4
  160. package/tests/recall-cache.test.mjs +56 -3
  161. package/tests/recall-dedup.test.mjs +63 -2
  162. package/tests/retention.test.mjs +260 -0
  163. package/tests/rt-index-cross-library.test.mjs +230 -0
  164. package/tests/rt-index-integration.test.mjs +194 -0
  165. package/tests/rt-index-retention.test.mjs +552 -0
  166. package/tests/rt-index-scale.test.mjs +204 -0
  167. package/tests/rt-index.test.mjs +705 -0
  168. package/tests/salient-date-boundaries.test.mjs +121 -0
  169. package/tests/salient-wake.test.mjs +29 -0
  170. package/tests/scale-bench.test.mjs +53 -0
  171. package/tests/settings-plumbing.test.mjs +25 -0
  172. package/tests/simulate-injection.test.mjs +15 -1
  173. package/tests/standalone-navigation.test.mjs +44 -0
  174. package/tests/state.test.mjs +51 -0
  175. package/tests/temporal-precision.test.mjs +102 -0
  176. package/tests/temporal.test.mjs +10 -6
  177. package/tests/token-measurement.test.mjs +98 -0
  178. package/tests/tool-schema.test.mjs +41 -5
  179. package/tests/tools.test.mjs +6 -3
  180. package/tests/turn-token-budget.test.mjs +149 -0
  181. package/tests/webui-auth.test.mjs +57 -1
  182. package/tests/webui.test.mjs +40 -15
  183. package/tests/worker-lifecycle.test.mjs +2 -1
@@ -0,0 +1,18 @@
1
+ import { rebuildRt, closeRtIndexService } from '../lib/rt-index-service.js'
2
+ import { listLibrariesAll } from '../lib/state.js'
3
+
4
+ const args = process.argv.slice(2)
5
+ if (!args.includes('--all') && !args.includes('--library') && !args.includes('--global')) {
6
+ console.error('Usage: node scripts/rebuild-rt.mjs --all | --library <id> | --global')
7
+ process.exitCode = 1
8
+ } else {
9
+ const ids = args.includes('--all') ? [...listLibrariesAll().map(item => item.id), null]
10
+ : args.includes('--global') ? [null] : [args[args.indexOf('--library') + 1]]
11
+ let failed = 0
12
+ for (const id of ids) {
13
+ try { if (!rebuildRt(id).ok) failed++ } catch { failed++ }
14
+ }
15
+ console.log(JSON.stringify({ libraries: ids.length, rebuilt: ids.length - failed, failed }))
16
+ process.exitCode = failed ? 1 : 0
17
+ }
18
+ await closeRtIndexService()
@@ -0,0 +1,183 @@
1
+ // Deterministic scale measurements; no production home or network services are used.
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import crypto from 'node:crypto'
6
+ import { fileURLToPath, pathToFileURL } from 'node:url'
7
+ import { spawnSync } from 'node:child_process'
8
+ import { performance } from 'node:perf_hooks'
9
+
10
+ const self = fileURLToPath(import.meta.url)
11
+ const root = path.resolve(path.dirname(self), '..')
12
+ const loader = path.join(root, 'tests/loader-register.mjs')
13
+ const args = process.argv.slice(2)
14
+ const arg = (key, fallback) => args.includes(key) ? args[args.indexOf(key) + 1] : fallback
15
+ const samples = Number(arg('--samples', '7'))
16
+ const seed = Number(arg('--seed', '1444'))
17
+ const operations = arg('--operations', 'all').split(',')
18
+ const rtMode = arg('--rt-mode', process.env.DSH_MEMU_RT_INDEX || 'shadow')
19
+ if (!['off', 'shadow', 'on'].includes(rtMode)) throw new Error('invalid --rt-mode')
20
+ process.env.DSH_MEMU_RT_INDEX = rtMode
21
+ const selected = name => operations.includes('all') || operations.includes(name)
22
+ const timed = (name, fn, count = samples, warm = true) => selected(name)
23
+ ? measure(fn, count, warm) : { unavailable: true, reason: 'not measured: excluded by --operations' }
24
+ const epoch = '2026-11-01T12:00:00.000Z'
25
+ const quantiles = values => {
26
+ const sorted = values.slice().sort((a, b) => a - b)
27
+ const percentile = p => sorted[Math.max(0, Math.ceil(p * sorted.length) - 1)]
28
+ return { samples: values.length, p50Ms: percentile(0.5), p95Ms: percentile(0.95), minMs: sorted[0], maxMs: sorted.at(-1) }
29
+ }
30
+ function randomSource(initial) {
31
+ let value = initial >>> 0
32
+ return () => { value = (Math.imul(value, 1664525) + 1013904223) >>> 0; return value / 2 ** 32 }
33
+ }
34
+ function child(argv, env = {}) {
35
+ const result = spawnSync(process.execPath, ['--import', pathToFileURL(loader).href, self, ...argv], {
36
+ cwd: root, env: { ...process.env, ...env }, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,
37
+ })
38
+ if (result.status !== 0) throw new Error(`benchmark child failed (${result.status}): ${result.stderr}\n${result.stdout}`)
39
+ return JSON.parse(result.stdout)
40
+ }
41
+ async function measure(fn, count = samples, warm = true) {
42
+ let firstCallMs = null
43
+ if (warm) {
44
+ const start = performance.now()
45
+ await fn(-1)
46
+ firstCallMs = performance.now() - start
47
+ }
48
+ const times = []
49
+ for (let i = 0; i < count; i++) {
50
+ const start = performance.now()
51
+ await fn(i)
52
+ times.push(performance.now() - start)
53
+ }
54
+ return { ...quantiles(times), firstCallMs }
55
+ }
56
+
57
+ if (args.includes('--cold')) {
58
+ const state = await import('../lib/state.js')
59
+ const started = performance.now()
60
+ const index = (state.readPrivateIndex || state.loadPrivateIndex)(arg('--library'))
61
+ process.stdout.write(JSON.stringify({ ms: performance.now() - started, count: Object.keys(index.entries).length, rss: process.memoryUsage().rss }))
62
+ } else if (args.includes('--worker')) {
63
+ const count = Number(arg('--count'))
64
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-scale-'))
65
+ process.env.DSH_MEMU_HOME = home
66
+ let rtService
67
+ try {
68
+ const state = await import('../lib/state.js')
69
+ const paths = await import('../lib/paths.js')
70
+ const memory = await import('../lib/memory.js')
71
+ rtService = await import('../lib/rt-index-service.js')
72
+ const { dispatch } = await import('../lib/rpc.js')
73
+ const graph = await import('../lib/graph.js')
74
+ const { recallCache } = await import('../lib/recall-cache.js')
75
+ state.updateSettings({ memoryBackend: 'agent', autoLinkMode: 'off' })
76
+ const lib = state.createLibrary({ name: `scale-${count}`, cwd: path.join(home, 'workspace') })
77
+ const random = randomSource(seed)
78
+ const syllables = [...'今天我们一起回到海边看星星讨论工作学习计划朋友旅行音乐家庭生活记忆城市春天花园雨水故事约定生日咖啡程序测试']
79
+ const domains = ['general', 'work', 'study', 'life', 'rp', 'coding']
80
+ const index = { version: 1, entries: {} }
81
+ const entities = { version: 1, entities: {}, relationships: {} }
82
+ const digest = value => crypto.createHash('sha256').update(String(value)).digest('hex')
83
+ const id = i => `mem-scale-${String(i).padStart(7, '0')}`
84
+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aN2cAAAAASUVORK5CYII=', 'base64')
85
+ const presentSha = crypto.createHash('sha256').update(png).digest('hex')
86
+ for (let i = 0; i < Math.floor(count * 0.3); i++) {
87
+ const entityId = `ent-scale-${i}`
88
+ entities.entities[entityId] = { id: entityId, name: `人物${i}`, kind: 'person', createdAt: epoch, updatedAt: epoch, status: 'confirmed' }
89
+ }
90
+ for (let i = 0; i < count; i++) {
91
+ const length = 40 + Math.floor(random() * 561)
92
+ const cjkRatio = 0.6 + random() * 0.35
93
+ let content = ''
94
+ for (let j = 0; j < length; j++) content += random() < cjkRatio ? syllables[Math.floor(random() * syllables.length)] : ' abcdef0123456789'[Math.floor(random() * 17)]
95
+ const links = [{ to: id((i + 97) % count), kind: 'relation', note: '合成关系', confidence: 0.7 }]
96
+ if (i < Math.floor(count * 0.2)) links.push({ to: `ent-scale-${i}`, kind: 'person', note: '合成人物', confidence: 0.8 })
97
+ index.entries[id(i)] = {
98
+ title: `海边计划 ${i}`, content, domain: domains[i % 6], status: i % 29 === 0 ? 'archived' : 'active',
99
+ visibility: i % 3 === 0 ? 'secret' : 'shared', context: i % 3 === 2 ? { characterId: 'scale-character' } : undefined,
100
+ layer: i % 7 === 0 ? 'short_term' : 'long_term', createdAt: epoch, updatedAt: epoch, strength: 0.8, links,
101
+ attachments: i % 10 === 0 ? [{ sha256: i % 100 < 30 ? digest(`missing-${i}`) : presentSha, kind: 'image' }] : [],
102
+ }
103
+ }
104
+ // Fixtures are intentionally seeded in one real index write, outside all timers.
105
+ state.savePrivateIndex(lib.id, index)
106
+ paths.writeJson(path.join(paths.indexDir(), `${lib.id}.entities.json`), entities)
107
+ const terms = {}
108
+ for (let i = 0; i < 5000; i++) terms[`lex-scale-${i}`] = { id: `lex-scale-${i}`, term: `合成词条${i}`, meaning: `词义${i}`, status: 'active', aliases: [], createdAt: epoch, updatedAt: epoch }
109
+ paths.writeJson(path.join(paths.dataDir(), 'lexicon', `${lib.id}.json`), { version: 1, revision: 1, libraryId: lib.id, terms, rejected: {} })
110
+ const media = path.join(paths.dataDir(), 'attachments', lib.id)
111
+ fs.mkdirSync(media, { recursive: true })
112
+ fs.writeFileSync(path.join(media, presentSha + '.png'), png)
113
+ const blobs = { [presentSha]: { sha256: presentSha, ext: 'png', mime: 'image/png', bytes: png.length, w: 1, h: 1, firstSeenAt: epoch, useCount: 1 } }
114
+ for (let i = 0; i < count; i += 10) if (i % 100 < 30) {
115
+ const sha = digest(`missing-${i}`)
116
+ blobs[sha] = { sha256: sha, ext: 'png', mime: 'image/png', missing: true, bytes: 0 }
117
+ }
118
+ paths.writeJson(path.join(paths.indexDir(), `${lib.id}.media.json`), { version: 1, blobs, totals: { count: 1, bytes: png.length } })
119
+ let rtBuild = { skipped: 'off-or-not-requested' }
120
+ if (args.includes('--build-rt') && rtMode !== 'off') {
121
+ const start = performance.now()
122
+ const result = rtService.rebuildRt(lib.id)
123
+ rtBuild = { ok: result.ok, code: result.code || null, ms: performance.now() - start }
124
+ }
125
+ const cold = []
126
+ if (selected('coldLoad')) for (let i = 0; i < Math.min(samples, 3); i++) cold.push(child(['--cold', '--library', lib.id], { DSH_MEMU_HOME: home }).ms)
127
+ const metrics = { coldLoad: cold.length ? quantiles(cold) : { unavailable: true, reason: 'not measured: excluded by --operations' } }
128
+ const read = state.readPrivateIndex || state.loadPrivateIndex
129
+ metrics.hotRead = await timed('hotRead', () => read(lib.id))
130
+ metrics.hotMutableLoad = await timed('hotMutableLoad', () => state.loadPrivateIndex(lib.id))
131
+ metrics.lexicalRecall = await timed('lexicalRecall', async i => {
132
+ recallCache.clear()
133
+ await memory.privateRecall({ libraryId: lib.id, query: `海边计划 ${i < 0 ? count : i}`, topK: 8 })
134
+ })
135
+ metrics.privateList = await timed('privateList', () => memory.privateList({ libraryId: lib.id, preferIndex: true, limit: 40 }))
136
+ metrics.browseWall = await timed('browseWall', () => dispatch({}, 'browseWall', { libraryId: lib.id, limit: 40, offset: 0 }))
137
+ metrics.getGraph = await timed('getGraph', () => graph.getGraph({ libraryId: lib.id, limit: 200, depth: 1, offset: 0 }))
138
+ metrics.getGraphOverview = typeof graph.getGraphOverview === 'function'
139
+ ? await timed('getGraphOverview', () => graph.getGraphOverview({ libraryId: lib.id }))
140
+ : { unavailable: true, reason: 'getGraphOverview is not implemented' }
141
+ metrics.remember = await timed('remember', async i => {
142
+ const nonce = digest(`${seed}:${count}:write:${i}`)
143
+ const result = await memory.privateRemember({ libraryId: lib.id, title: nonce.slice(0, 24), content: nonce + digest(nonce), domain: 'general', confidence: 0.8 })
144
+ if (!result?.id || result.deduped) throw new Error('remember probe did not insert a real new memory')
145
+ }, samples, false)
146
+ process.stdout.write(JSON.stringify({ count, rtMode, rtBuild, rtService: rtService.rtServiceDiagnostics(), fixture: { seed, epoch, cjkRatio: [0.6, 0.95], length: [40, 600], domains: 6, visibilityBands: ['secret', 'shared', 'shared+character'], attachmentRatio: 0.1, missingAttachmentRatio: 0.3, entities: Math.floor(count * 0.3), edges: count + Math.floor(count * 0.2), lexiconTerms: 5000 }, metrics, rssBytes: process.memoryUsage().rss, peakRssBytes: process.resourceUsage().maxRSS * 1024, cache: { recall: recallCache.stats(), index: state.indexCacheStats?.(), lexical: memory.lexicalCacheStats?.() } }))
147
+ } finally {
148
+ await rtService?.closeRtIndexService()
149
+ // This exact path is created by this process; no caller-supplied home is removed.
150
+ fs.rmSync(home, { recursive: true, force: true })
151
+ }
152
+ } else {
153
+ if (!Number.isInteger(samples) || samples < 3 || !Number.isSafeInteger(seed)) throw new Error('--samples must be >=3; --seed must be an integer')
154
+ const allowed = new Set(['all', 'coldLoad', 'hotRead', 'hotMutableLoad', 'lexicalRecall', 'privateList', 'browseWall', 'getGraph', 'getGraphOverview', 'remember'])
155
+ if (operations.some(name => !allowed.has(name))) throw new Error('invalid --operations')
156
+ const sizes = String(arg('--sizes', '1000,5000,20000,100000')).split(',').map(Number)
157
+ if (sizes.some(n => !Number.isSafeInteger(n) || n < 10 || n > 1_000_000)) throw new Error('invalid --sizes')
158
+ const label = arg('--label', 'scale')
159
+ const output = path.resolve(root, arg('--out', `logs/scale-bench-${label}-${new Date().toISOString().replace(/[:.]/g, '-')}`))
160
+ const provenanceFiles = ['package.json', 'scripts/scale-bench.mjs', ...fs.readdirSync(path.join(root, 'lib'), { recursive: true })
161
+ .filter(file => /\.(?:js|json|md)$/.test(file)).map(file => `lib/${file.replaceAll('\\', '/')}`)].sort()
162
+ const fingerprint = () => {
163
+ const hash = crypto.createHash('sha256')
164
+ for (const file of provenanceFiles) hash.update(file).update('\0').update(fs.readFileSync(path.join(root, file)))
165
+ return hash.digest('hex')
166
+ }
167
+ const result = { label, startedAt: new Date().toISOString(), node: process.version, platform: process.platform, seed, samples, operations, sourceFingerprint: fingerprint(), sourceFiles: provenanceFiles, indexCow: process.env.DSH_MEMU_INDEX_COW ?? 'default', gold: false, notes: ['Synthetic performance only; not retrieval-quality validation.', 'Cold timers include first index read/parse/normalization, exclude module startup; separate process per sample.', 'firstCallMs is the pre-sample call with source already loaded; it is not a cold-process first screen.', 'Recall clears result cache per sample; corpus cache is warm after warmup.', 'remember includes real dedupe, full JSON persistence, sidecars and activity; it is not constant-time.', 'Host imports use repository loader stubs; storage, memory functions and RPC handlers are real.'], results: [] }
168
+ for (const count of sizes) {
169
+ console.error(`scale-bench ${label}: ${count} entries`)
170
+ result.results.push(child(['--worker', '--count', String(count), '--samples', String(samples), '--seed', String(seed), '--operations', operations.join(','), '--rt-mode', rtMode, ...(args.includes('--build-rt') ? ['--build-rt'] : [])]))
171
+ result.sourceFingerprintAfter = fingerprint()
172
+ result.sourceStable = result.sourceFingerprintAfter === result.sourceFingerprint
173
+ fs.mkdirSync(path.dirname(output), { recursive: true })
174
+ fs.writeFileSync(output + '.json', JSON.stringify(result, null, 2) + '\n')
175
+ if (!result.sourceStable) throw new Error('benchmark source changed during measurement; results are not frozen evidence')
176
+ }
177
+ const lines = [`# Scale benchmark: ${label}`, '', `Node ${result.node}; ${result.platform}; seed ${seed}; ${samples} samples; gold: false.`, '', '| N | operation | P50 ms | P95 ms |', '|---:|---|---:|---:|']
178
+ for (const row of result.results) for (const [key, value] of Object.entries(row.metrics)) lines.push(value.unavailable ? `| ${row.count} | ${key} | unavailable | ${value.reason} |` : `| ${row.count} | ${key} | ${value.p50Ms.toFixed(3)} | ${value.p95Ms.toFixed(3)} |`)
179
+ for (const row of result.results) lines.push('', `N=${row.count}: RSS ${(row.rssBytes / 1048576).toFixed(1)} MiB; peak RSS ${(row.peakRssBytes / 1048576).toFixed(1)} MiB.`)
180
+ lines.push('', ...result.notes.map(note => '- ' + note), '')
181
+ fs.writeFileSync(output + '.md', lines.join('\r\n'))
182
+ console.log(JSON.stringify(result, null, 2))
183
+ }
@@ -36,7 +36,7 @@ import { registerHooks } from 'node:module'
36
36
  const REPO_URL = new URL('../', import.meta.url)
37
37
 
38
38
  function parseArgs(argv) {
39
- const options = { turns: 50, home: null, out: null, port: 0, cue: 0, json: false }
39
+ const options = { turns: 50, home: null, out: null, port: 0, cue: 0, toolSteps: 0, json: false }
40
40
  const take = (index) => {
41
41
  const value = argv[index]
42
42
  if (value === undefined || value.startsWith('--')) throw new Error('missing value')
@@ -46,6 +46,7 @@ function parseArgs(argv) {
46
46
  const arg = argv[i]
47
47
  switch (arg) {
48
48
  case '--turns': options.turns = Number(take(++i)); break
49
+ case '--tool-steps': options.toolSteps = Number(take(++i)); break
49
50
  case '--home': options.home = path.resolve(take(++i)); break
50
51
  case '--out': options.out = path.resolve(take(++i)); break
51
52
  case '--port': options.port = Number(take(++i)); break
@@ -56,7 +57,7 @@ function parseArgs(argv) {
56
57
  console.log(`EVALUATION ONLY — offline injection simulator (pairs with scripts/mock-llm.mjs).
57
58
 
58
59
  node scripts/simulate-injection.mjs [--turns 50] [--home <dir>] [--out <dir>]
59
- [--port <n>] [--cue <chance>] [--json]
60
+ [--port <n>] [--cue <chance>] [--tool-steps 0..40] [--json]
60
61
 
61
62
  Drives the real lib/inject.js through registerInjection('agent/pre-step') against a seeded
62
63
  library in a throwaway DSH_MEMU_HOME, and posts every assembled request to a loopback mock
@@ -69,6 +70,7 @@ out of scope.`)
69
70
  }
70
71
  }
71
72
  if (!Number.isInteger(options.turns) || options.turns < 1 || options.turns > 500) throw new Error('--turns must be 1..500')
73
+ if (!Number.isInteger(options.toolSteps) || options.toolSteps < 0 || options.toolSteps > 40) throw new Error('--tool-steps must be 0..40')
72
74
  if (!Number.isFinite(options.cue) || options.cue < 0 || options.cue > 1) throw new Error('--cue must be 0..1')
73
75
  return options
74
76
  }
@@ -108,7 +110,7 @@ const cwd = path.join(work, 'project')
108
110
  const binding = state.ensureSession(SESSION, { cwd, agentPreset: 'rp' })
109
111
  const libraryId = binding.libraryId
110
112
  state.setSessionBinding(SESSION, { useLibrary: true, useGlobal: false })
111
- state.updateSettings({ randomCueChance: parsed.cue })
113
+ state.updateSettings({ randomCueChance: parsed.cue, ...(parsed.toolSteps ? { midTurnCooldownMs: 0 } : {}) })
112
114
 
113
115
  const day = (offset, hour = 12) => {
114
116
  const value = new Date()
@@ -212,6 +214,8 @@ const roundsWithBlock = Object.fromEntries(mock.MARKER_KEYS.map((key) => [key, 0
212
214
  let roundsWithInjection = 0
213
215
  let titleCardBodyLineMax = 0
214
216
  let sendFailures = 0
217
+ let midTurnInjections = 0
218
+ const turnBudgets = []
215
219
 
216
220
  let history = []
217
221
  for (let turn = 1; turn <= parsed.turns; turn += 1) {
@@ -223,8 +227,8 @@ for (let turn = 1; turn <= parsed.turns; turn += 1) {
223
227
  content: [{ type: 'text', text: PROMPTS[(turn - 1) % PROMPTS.length] }],
224
228
  }]
225
229
  const out = await preStep({ agent, turn, step: 1, signal: { aborted: false } }, async () => ({ kind: 'enter', messages: history }))
226
- const messages = Array.isArray(out?.messages) ? out.messages : history
227
- if (messages.length > history.length) roundsWithInjection += 1
230
+ let messages = Array.isArray(out?.messages) ? out.messages : history
231
+ let turnHadInjection = messages.length > history.length
228
232
  for (const message of messages.filter((item) => !known.has(item))) {
229
233
  const analysis = mock.analyzeMessage({ role: 'user', content: textOf(message) })
230
234
  for (const key of mock.MARKER_KEYS) {
@@ -239,6 +243,31 @@ for (let turn = 1; turn <= parsed.turns; turn += 1) {
239
243
  for (const message of messages.filter(item => !known.has(item) && item.role === 'user')) {
240
244
  await handlers.get('session/event')?.(agent.session, { type: 'user/message', data: message })
241
245
  }
246
+ // Explicit long-turn mode drives delta-only tool batches through the same hook.
247
+ // It is still a fixture: no real provider usage or host tokenization is implied.
248
+ for (let step = 2; step <= parsed.toolSteps + 1; step += 1) {
249
+ const toolBatch = Array.from({ length: 3 }, (_, index) => ({
250
+ id: `tool-${turn}-${step}-${index}`, role: 'tool', source: { kind: 'tool' },
251
+ content: [{ type: 'text', text: `检索林眠与老周的咖啡店约定 ${turn}/${step}/${index} ` + 'fixture evidence '.repeat(150) }],
252
+ }))
253
+ const mid = await preStep({ agent, turn, step, signal: { aborted: false } }, async () => ({ kind: 'enter', messages: toolBatch }))
254
+ const additions = (mid?.messages || []).filter(message => message.source?.kind === 'plugin:dsh-memu-memory')
255
+ midTurnInjections += additions.length
256
+ if (additions.length) turnHadInjection = true
257
+ for (const message of additions) {
258
+ const analysis = mock.analyzeMessage({ role: 'user', content: textOf(message) })
259
+ for (const key of mock.MARKER_KEYS) {
260
+ const count = Number(analysis.markers?.[key] || 0)
261
+ deltaTotals[key] += count
262
+ if (count) roundsWithBlock[key] += 1
263
+ }
264
+ titleCardBodyLineMax = Math.max(titleCardBodyLineMax, Number(analysis.context?.bodyLines || 0))
265
+ await handlers.get('session/event')?.(agent.session, { type: 'user/message', data: message })
266
+ }
267
+ messages = [...messages, ...toolBatch, ...additions]
268
+ }
269
+ if (turnHadInjection) roundsWithInjection += 1
270
+ turnBudgets.push(inject.injectionTokenDiagnostics(SESSION, turn))
242
271
  const payload = [
243
272
  { role: 'system', content: SYSTEM_PROMPT },
244
273
  ...messages.map((message) => ({ role: message.role === 'assistant' ? 'assistant' : 'user', content: textOf(message) })),
@@ -250,7 +279,7 @@ for (let turn = 1; turn <= parsed.turns; turn += 1) {
250
279
  })
251
280
  if (!response.ok) sendFailures += 1
252
281
  await response.text()
253
- history = [...history, { id: `a-${turn}`, role: 'assistant', content: [{ type: 'text', text: REPLY }] }]
282
+ history = [...messages, { id: `a-${turn}`, role: 'assistant', content: [{ type: 'text', text: REPLY }] }]
254
283
  }
255
284
 
256
285
  instance.close()
@@ -270,11 +299,18 @@ fs.writeFileSync(snapshotPath, JSON.stringify({
270
299
  dedupeTurns: settings.dedupeTurns, minUserChars: settings.minUserChars, randomCueChance: settings.randomCueChance,
271
300
  openLoopRemindDays: settings.openLoopRemindDays, freshnessHint: settings.freshnessHint, freshnessDays: settings.freshnessDays,
272
301
  salientWake: settings.salientWake,
302
+ midTurnRecall: settings.midTurnRecall, midTurnTokens: settings.midTurnTokens,
303
+ midTurnMaxPerTurn: settings.midTurnMaxPerTurn, midTurnCooldownMs: settings.midTurnCooldownMs,
273
304
  },
274
305
  }, null, 2))
275
306
 
276
307
  const reportPath = path.join(outDir, 'report.md')
277
- fs.writeFileSync(reportPath, mock.renderReport(fs.readFileSync(logPath, 'utf8'), { logPath }))
308
+ const budgetPath = path.join(outDir, 'token-budget.json')
309
+ fs.writeFileSync(budgetPath, JSON.stringify({ evidence: 'offline-fixture', memoryActual: 'unverified', turnBudgets }, null, 2))
310
+ const budgetViolations = turnBudgets.filter(row => row.estimated > row.limit).length
311
+ const maximumTurnEstimated = Math.max(0, ...turnBudgets.map(row => row.estimated))
312
+ fs.writeFileSync(reportPath, mock.renderReport(fs.readFileSync(logPath, 'utf8'), { logPath })
313
+ + `\n\n## Shared turn token budget\n\nTool steps per turn: ${parsed.toolSteps}; mid-turn messages: ${midTurnInjections}; maximum estimated new memory tokens per turn: ${maximumTurnEstimated}; over-budget turns: ${budgetViolations}. Actual memory tokens and calibration remain unverified (offline fixture).\n`)
278
314
 
279
315
  const summary = {
280
316
  turns: parsed.turns,
@@ -285,6 +321,9 @@ const summary = {
285
321
  titleCardBodyLineMax,
286
322
  uniqueInjectedIds: uniqueInjected,
287
323
  sendFailures,
324
+ toolSteps: parsed.toolSteps,
325
+ midTurnInjections,
326
+ tokenBudget: { maximumTurnEstimated, limit: settings.injectionTotalTokens, violations: budgetViolations, actual: 'unverified', path: budgetPath },
288
327
  warnCount: warns.length,
289
328
  firstWarns: warns.slice(0, 3),
290
329
  entries: seeded,
@@ -296,4 +335,4 @@ const summary = {
296
335
  }
297
336
  console.log(parsed.json ? JSON.stringify(summary) : JSON.stringify(summary, null, 2))
298
337
 
299
- if (warns.length > 0) process.exitCode = 3
338
+ if (warns.length > 0 || budgetViolations > 0) process.exitCode = 3
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ // Uses only the isolated snapshot and the installed host peers; no test stubs.
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 { pathToFileURL } from 'node:url'
8
+
9
+ const runArgument = process.argv.find(arg => arg.startsWith('--run='))
10
+ if (!runArgument) throw new Error('--run=<isolated recovery-host directory> required')
11
+ const run = fs.realpathSync(runArgument.slice('--run='.length))
12
+ if (!path.basename(run).startsWith('recovery-host-')) throw new Error('isolated recovery-host directory required')
13
+ const data = path.join(run, 'home/dsh-memu-memory')
14
+ assert.equal(path.resolve(process.env.DSH_MEMU_HOME || ''), data)
15
+ assert.equal(path.resolve(process.env.DSH_MEMU_MEMORY_HOME || ''), data)
16
+ const snapshot = path.join(run, 'home/profiles/recovery-host/node_modules/dsh-memu-memory')
17
+ const fixtures = JSON.parse(fs.readFileSync(path.join(run, 'fixtures/private.json'), 'utf8'))
18
+ const statePath = path.join(data, 'state.json')
19
+ const hash = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')
20
+ const importSnapshot = file => import(pathToFileURL(path.join(snapshot, 'lib', file)).href)
21
+ const { privateRecall, readMemoryByRef } = await importSnapshot('memory.js')
22
+ const { flushState, setSessionBinding } = await importSnapshot('state.js')
23
+ const results = []
24
+ const execFor = fixture => ({ agent: { id: fixture.sessionId, session: { header: { id: fixture.sessionId } } } })
25
+
26
+ for (const fixture of fixtures) {
27
+ const file = path.join(data, 'index', fixture.libraryId + '.json')
28
+ assert.equal(hash(file), fixture.originalIndexSha256)
29
+ const originalIndex = JSON.parse(fs.readFileSync(file, 'utf8'))
30
+ const byId = await privateRecall({ exec: execFor(fixture), query: fixture.id, topK: 5 })
31
+ const actualIds = byId.files.map(item => item.name)
32
+ assert.ok(actualIds.includes(fixture.id), 'exact recall must contain the actual copied ID')
33
+ const natural = await privateRecall({ exec: execFor(fixture), query: fixture.query, topK: 5, relevanceThreshold: 0 })
34
+ const naturalIds = natural.files.map(item => item.name)
35
+ assert.ok(naturalIds.includes(fixture.id), 'title query must contain the actual copied ID')
36
+ const page = readMemoryByRef({ exec: execFor(fixture), id: fixture.id })
37
+ assert.equal(page.ref.id, fixture.id)
38
+ assert.ok(page.body.length > 0)
39
+ const currentIndex = JSON.parse(fs.readFileSync(file, 'utf8'))
40
+ assert.deepEqual(Object.keys(currentIndex.entries).sort(), Object.keys(originalIndex.entries).sort())
41
+ const changedObservationFields = new Set()
42
+ for (const [id, entry] of Object.entries(currentIndex.entries)) {
43
+ const previous = originalIndex.entries[id]
44
+ for (const key of new Set([...Object.keys(previous), ...Object.keys(entry)])) {
45
+ if (JSON.stringify(previous[key]) === JSON.stringify(entry[key])) continue
46
+ assert.ok(['lastAccessAt', 'accessCount'].includes(key), 'explicit recall may only update access observations')
47
+ changedObservationFields.add(key)
48
+ }
49
+ }
50
+ results.push({ kind: 'real', domain: fixture.domain, expectedId: fixture.id, actualIds, naturalIds, bodyRead: true,
51
+ factualFieldsUnchanged: true, changedObservationFields: [...changedObservationFields].sort() })
52
+ }
53
+
54
+ const [coding, rp] = fixtures
55
+ for (const [target, foreign] of [[coding, rp], [rp, coding]]) {
56
+ let actualIds = []
57
+ let deniedAsUnknown = false
58
+ try {
59
+ const recall = await privateRecall({ exec: execFor(target), query: foreign.id, topK: 5, relevanceThreshold: 0 })
60
+ actualIds = recall.files.map(item => item.name)
61
+ } catch (error) {
62
+ assert.equal(error.message, 'unknown memory: ' + foreign.id)
63
+ deniedAsUnknown = true
64
+ }
65
+ assert.ok(!actualIds.includes(foreign.id), 'foreign-domain actual ID must be absent')
66
+ assert.throws(() => readMemoryByRef({ exec: execFor(target), id: foreign.id, libraryId: foreign.libraryId }),
67
+ error => error.code === 'MEMORY_LIBRARY_FORBIDDEN')
68
+ results.push({ kind: 'real-cross-domain', domain: target.domain, foreignDomain: foreign.domain,
69
+ forbiddenId: foreign.id, actualIds, deniedAsUnknown, exactBodyDenied: true })
70
+ }
71
+
72
+ // The production sample contains no secrets. Synthetic copies test those gates explicitly.
73
+ const restrictedId = 'mem_recovery_secret'
74
+ const contextId = 'mem_recovery_context'
75
+ const indexFile = path.join(data, 'index', coding.libraryId + '.json')
76
+ const original = fs.readFileSync(indexFile)
77
+ const rawState = fs.readFileSync(statePath)
78
+ try {
79
+ const index = JSON.parse(original)
80
+ const sample = structuredClone(index.entries[coding.id])
81
+ index.entries[restrictedId] = { ...sample, title: 'recovery secrecy sentinel', content: 'recovery secrecy sentinel', visibility: 'secret' }
82
+ index.entries[contextId] = { ...sample, title: 'recovery context sentinel', content: 'recovery context sentinel',
83
+ context: { characterId: 'recovery-other-character', worldId: 'recovery-other-world' } }
84
+ fs.writeFileSync(indexFile, JSON.stringify(index), { mode: 0o600 })
85
+ // Module cache invalidation follows disk revision and a fresh session binding.
86
+ setSessionBinding(coding.sessionId, { memoryContext: { characterId: 'recovery-current-character', worldId: 'recovery-current-world' } })
87
+ for (const id of [restrictedId, contextId]) {
88
+ const recall = await privateRecall({ exec: execFor(coding), query: id, topK: 5, purpose: 'automatic' })
89
+ const actualIds = recall.files.map(item => item.name)
90
+ assert.ok(!actualIds.includes(id))
91
+ if (id === contextId) {
92
+ assert.throws(() => readMemoryByRef({ exec: execFor(coding), id }), error => error.code === 'MEMORY_NOT_READABLE')
93
+ } else {
94
+ const explicit = readMemoryByRef({ exec: execFor(coding), id })
95
+ assert.equal(explicit.ref.id, id, 'secret remains available on explicit bound recall')
96
+ const unbound = await privateRecall({ libraryId: coding.libraryId, query: id, topK: 5 })
97
+ assert.ok(!unbound.files.some(item => item.name === id), 'unbound caller may not read secret')
98
+ }
99
+ results.push({ kind: 'synthetic-restriction', forbiddenAutomaticId: id, actualIds,
100
+ exactBodyDenied: id === contextId, explicitBoundSecretAllowed: id === restrictedId })
101
+ }
102
+ flushState()
103
+ } finally {
104
+ fs.writeFileSync(indexFile, original, { mode: 0o600 })
105
+ fs.writeFileSync(statePath, rawState, { mode: 0o600 })
106
+ }
107
+ fs.writeFileSync(path.join(run, 'fixtures-report.json'), JSON.stringify({ ok: true, results }, null, 2) + '\r\n', { mode: 0o600 })
108
+ console.log(JSON.stringify({ ok: true, cases: results.length, realFixtures: fixtures.length, productionAccess: false }))