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
@@ -255,10 +255,10 @@ test('missing-db recall reuses loaded indexes on repeated warm-cache calls', asy
255
255
  const result = await memory.privateRecall({ exec: f.exec, query: 'needle', purpose: 'automatic' })
256
256
  await settleRebuildProbes()
257
257
  assert.deepEqual(result.files.map(file => file.name), ['mem-budget'])
258
- // Two source snapshots clone twice each; the one hit also checks the existing
259
- // relation-inverted-index signature (stat only, no snapshot).
260
- assert.equal(access.stats.get(indexFile), 3 * round, 'two index reads plus one relation signature stat')
261
- assert.equal(access.clones, 4 * round, 'no extra full-index clones, regardless of corpus size')
258
+ // Source refreshes validate the frozen view; relation lookup reuses its
259
+ // content revision instead of adding the former weak-signature stat.
260
+ assert.equal(access.stats.get(indexFile), 2 * round, 'two validated source reads; relation lookup reuses their revision')
261
+ assert.equal(access.clones, 0, 'pure recall never clones a full index, regardless of corpus size')
262
262
  assert.equal(rebuildProbes.length, round, 'the fallback remains uncached and diagnostic')
263
263
  }
264
264
  })
@@ -287,21 +287,25 @@ test('cross-library missing-db diagnostics use the full source before domain fil
287
287
  assert.equal(vectorDegradeRows(empty.libraryId).length, 0)
288
288
  assert.equal(rebuildProbes.length, 2, 'a domain-filtered empty view still needs a rebuild probe')
289
289
  assert.equal(calls.length, 0)
290
- assert.deepEqual(indexFiles.map(file => access.stats.get(file)), [3, 1, 1], 'only the primary hit adds a relation signature stat')
291
- assert.equal(access.clones, 8, 'three source loads plus the existing primary refresh only')
290
+ assert.deepEqual(indexFiles.map(file => access.stats.get(file)), [2, 1, 1], 'only the primary hit refreshes its validated source view')
291
+ assert.equal(access.clones, 0, 'source reads and the primary refresh all use frozen views')
292
292
  })
293
293
 
294
294
  test('by-id private recall still short-circuits vector IO and missing-db diagnostics', async t => {
295
- const f = fixture({ 'mem-byid': entry('needle direct lookup') })
295
+ const f = fixture({
296
+ 'mem-byid': entry('needle direct lookup', { links: [{ to: 'mem-related', kind: 'relation', confidence: .9, note: 'explicit linked evidence' }] }),
297
+ 'mem-related': entry('linked target fact'),
298
+ })
296
299
  const databases = activate([])
297
300
  const globalDb = vp.resolveVectorPath(databases.global.path)
298
301
  fs.rmSync(globalDb)
299
302
  const indexFile = path.join(paths.indexDir(), f.libraryId + '.json')
300
303
  const access = trackIndexAccess(t, [indexFile, globalDb])
301
304
  const read = t.mock.method(fs, 'readFileSync')
302
- const result = await memory.privateRecall({ exec: f.exec, query: 'mem-byid', purpose: 'automatic' })
305
+ const result = await memory.privateRecall({ exec: f.exec, query: 'mem-byid', purpose: 'automatic', topK: 1 })
303
306
  await settleRebuildProbes()
304
307
  assert.deepEqual(result.files.map(file => file.name), ['mem-byid'])
308
+ assert.deepEqual(result.files[0].related.map(row => row.id), ['mem-related'], 'the relation lookup must return the actual target, not silently fail open')
305
309
  assert.equal(result.recallRoute, 'local')
306
310
  assert.deepEqual(warnings, [])
307
311
  assert.equal(vectorDegradeRows(f.libraryId).length, 0)
@@ -309,8 +313,8 @@ test('by-id private recall still short-circuits vector IO and missing-db diagnos
309
313
  assert.equal(calls.length, 0)
310
314
  assert.equal(read.mock.calls.some(call => call.arguments[0] === activeFile), false, 'by-id does not read vector state')
311
315
  assert.equal(access.stats.get(globalDb), 0, 'by-id does not validate vector databases')
312
- assert.equal(access.stats.get(indexFile), 3, 'two index reads plus the existing relation signature stat')
313
- assert.equal(access.clones, 4)
316
+ assert.equal(access.stats.get(indexFile), 2, 'two validated source reads; relation lookup adds no redundant stat')
317
+ assert.equal(access.clones, 0, 'read-only views add no full-index clones')
314
318
  })
315
319
 
316
320
  test('global recall uses the null library route even for an empty index and adds no index snapshots', async t => {
@@ -340,7 +344,7 @@ test('global recall uses the null library route even for an empty index and adds
340
344
  assert.equal(vectorDegradeRows(null).length, 0)
341
345
  assert.equal(rebuildProbes.length, 0)
342
346
  assert.equal(access.stats.get(indexFile), 2)
343
- assert.equal(access.clones, 4)
347
+ assert.equal(access.clones, 0, 'read-only views add no full-index clones')
344
348
  })
345
349
 
346
350
  for (const content of ['empty', 'other-domain', 'matching']) {
@@ -1232,3 +1236,27 @@ test('automatic recent exclusion cannot promote an unqualified lexical-only nois
1232
1236
  assert.equal(next.trace.counts.recentRows, 5)
1233
1237
  await assertRankingBoundary(2)
1234
1238
  })
1239
+
1240
+ test('global hybrid corpus keys separate equal-sized role bindings before BM25 statistics', async () => {
1241
+ const f = fixture()
1242
+ activate([f.libraryId])
1243
+ const base = { domain: 'coding', createdAt: '2026-11-01T00:00:00Z', updatedAt: '2026-11-01T00:00:00Z' }
1244
+ const rows = { 'gmem-a-needle': entry('zqhybrid', base) }
1245
+ for (let i = 0; i < 7; i++) {
1246
+ rows[`gmem-alpha-${i}`] = entry('unrelated' + i, { ...base, context: { characterId: 'alpha' } })
1247
+ rows[`gmem-beta-${i}`] = entry('zqhybrid', { ...base, context: { characterId: 'beta' } })
1248
+ }
1249
+ state.saveGlobalIndex({ entries: rows })
1250
+ state.setSessionBinding(f.sessionId, { memoryContext: { characterId: 'alpha' } })
1251
+ const recall = () => memory.globalRecall({ exec: f.exec, query: 'zqhybrid', purpose: 'automatic', topK: 5, relevanceThreshold: 0 })
1252
+ const first = await recall()
1253
+ assert.equal(first.recallRoute, 'managed-vector-rrf')
1254
+ const lexical = result => result.files.find(file => file.name === 'gmem-a-needle')?.lexical
1255
+ assert.ok(lexical(first) > 0)
1256
+ state.setSessionBinding(f.sessionId, { memoryContext: { characterId: 'beta' }, sceneTime: '2027-01-01T00:00:00Z' })
1257
+ const other = await recall()
1258
+ assert.ok(lexical(other) < lexical(first), 'the beta corpus must use its own document frequency')
1259
+ state.setSessionBinding(f.sessionId, { memoryContext: { characterId: 'alpha' }, sceneTime: '2027-01-02T00:00:00Z' })
1260
+ const restored = await recall()
1261
+ assert.equal(lexical(restored), lexical(first))
1262
+ })
@@ -4,6 +4,8 @@ import fs from 'node:fs'
4
4
  import os from 'node:os'
5
5
  import path from 'node:path'
6
6
  import crypto from 'node:crypto'
7
+ import { c as tarCreate } from 'tar'
8
+ import { USTC_UV_BASE, USTC_PYTHON_BASE, PYTHON_OFFICIAL_BASE } from '../lib/engine-sources.js'
7
9
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-runtime-'))
8
10
  process.env.DSH_MEMU_HOME = home
9
11
  const { ensureManagedPython, verifyRuntimeArchive, UV_VERSION, MANAGED_PYTHON } = await import('../lib/managed-runtime.js')
@@ -70,3 +72,110 @@ test('a discovered interpreter outside the plugin directory is refused', async (
70
72
  run: async (_cmd, args) => ({ code: 0, stdout: args[0] === '--version' ? `uv ${UV_VERSION}` : 'C:/outside/python.exe' }),
71
73
  }), /escaped/)
72
74
  })
75
+
76
+ test('Python fallback survives thrown mirror failures and explicitly replaces inherited mirror configuration', async () => {
77
+ const attempts = []
78
+ const python = path.join(home, 'engine', 'runtime', 'python', 'python.exe')
79
+ const previous = process.env.UV_PYTHON_INSTALL_MIRROR
80
+ process.env.UV_PYTHON_INSTALL_MIRROR = 'https://broken.inherited.example'
81
+ try {
82
+ const result = await ensureManagedPython({ settings: {}, env: {},
83
+ run: async (_cmd, args, options) => {
84
+ if (args[0] === '--version') return { code: 0, stdout: `uv ${UV_VERSION}` }
85
+ const mirror = options.env.UV_PYTHON_INSTALL_MIRROR
86
+ if (args[1] === 'install') { attempts.push(mirror); if (mirror === USTC_PYTHON_BASE) throw new Error('mirror timed out') }
87
+ return { code: 0, stdout: args[1] === 'find' ? python : '' }
88
+ }, fetcher: async () => { throw new Error('reuse verified uv') } })
89
+ assert.equal(result.cmd, python)
90
+ assert.deepEqual(attempts, [USTC_PYTHON_BASE, PYTHON_OFFICIAL_BASE])
91
+ } finally {
92
+ if (previous === undefined) delete process.env.UV_PYTHON_INSTALL_MIRROR
93
+ else process.env.UV_PYTHON_INSTALL_MIRROR = previous
94
+ }
95
+ })
96
+
97
+ test('a dead network names every source and keeps the transport cause', async () => {
98
+ const previousHome = process.env.DSH_MEMU_HOME
99
+ const isolated = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-runtime-offline-'))
100
+ process.env.DSH_MEMU_HOME = isolated
101
+ try {
102
+ const failure = new TypeError('fetch failed')
103
+ failure.cause = Object.assign(new Error('connect ECONNRESET 20.27.177.113:443'), { code: 'ECONNRESET' })
104
+ await assert.rejects(ensureManagedPython({
105
+ run: async () => ({ code: 0, stdout: '' }),
106
+ fetcher: async () => { throw failure },
107
+ settings: {},
108
+ env: {},
109
+ }), (error) => {
110
+ assert.match(error.message, /USTC mirror 0\.13\.6/)
111
+ assert.match(error.message, /GitHub releases 0\.13\.6/)
112
+ assert.match(error.message, /ECONNRESET/)
113
+ assert.match(error.message, /DSH_MEMU_PYTHON/)
114
+ return true
115
+ })
116
+ } finally {
117
+ process.env.DSH_MEMU_HOME = previousHome
118
+ fs.rmSync(isolated, { recursive: true, force: true })
119
+ }
120
+ })
121
+
122
+ // The Linux/macOS branch extracts a tar.gz; the Windows branch unzips a zip. On a
123
+ // Windows host the former was never exercised, so this test switches the platform
124
+ // to linux and serves a constructed tarball from a fake rolling mirror.
125
+ test('linux gnu tarballs install through the rolling mirror path', async () => {
126
+ const previousHome = process.env.DSH_MEMU_HOME
127
+ const previousPlatform = process.platform
128
+ const isolated = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-runtime-linux-'))
129
+ const tarWork = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-runtime-tar-'))
130
+ process.env.DSH_MEMU_HOME = isolated
131
+ try {
132
+ fs.mkdirSync(path.join(tarWork, 'uv-x86_64-unknown-linux-gnu'), { recursive: true })
133
+ fs.writeFileSync(path.join(tarWork, 'uv-x86_64-unknown-linux-gnu', 'uv'), '#!/bin/sh\necho uv\n', { mode: 0o755 })
134
+ const archivePath = path.join(tarWork, 'uv.tar.gz')
135
+ await tarCreate({ gzip: true, file: archivePath, cwd: tarWork }, ['uv-x86_64-unknown-linux-gnu'])
136
+ const bytes = fs.readFileSync(archivePath)
137
+ const digest = crypto.createHash('sha256').update(bytes).digest('hex')
138
+
139
+ const pythonPath = path.join(isolated, 'engine', 'runtime', 'python', 'cpython-3.12.16-x86_64-unknown-linux-gnu', 'bin', 'python3')
140
+ fs.mkdirSync(path.dirname(pythonPath), { recursive: true })
141
+ fs.writeFileSync(pythonPath, '')
142
+
143
+ const textResponse = (text) => ({ ok: true, headers: { get: () => null }, text: async () => text })
144
+ const bytesResponse = (data) => ({
145
+ ok: true,
146
+ headers: { get: () => String(data.length) },
147
+ body: (async function* () { yield data })(),
148
+ text: async () => data.toString(),
149
+ })
150
+ const fetcher = async (url) => {
151
+ if (url === `${USTC_UV_BASE}/`) return textResponse('<a href="/github-release/astral-sh/uv/0.13.10/">0.13.10</a>')
152
+ if (url === `${USTC_UV_BASE}/0.13.10/sha256.sum`) return textResponse(`${digest} *uv-x86_64-unknown-linux-gnu.tar.gz`)
153
+ if (url === `${USTC_UV_BASE}/0.13.10/uv-x86_64-unknown-linux-gnu.tar.gz`) return bytesResponse(bytes)
154
+ if (url === `${USTC_PYTHON_BASE}/LatestRelease/`) {
155
+ return textResponse('/x/20261124/cpython-3.12.16%2B20261124-x86_64-unknown-linux-gnu-install_only.tar.gz')
156
+ }
157
+ throw new Error(`unexpected URL: ${url}`)
158
+ }
159
+ const run = async (_cmd, args) => {
160
+ if (args[0] === '--version') return { code: 0, stdout: 'uv 0.13.10 (e3e7c1eac 2026-11-24 x86_64-unknown-linux-gnu)\n' }
161
+ if (args[0] === 'python' && args[1] === 'install') return { code: 0, stdout: '' }
162
+ if (args[0] === 'python' && args[1] === 'find') return { code: 0, stdout: `${pythonPath}\n` }
163
+ return { code: 0, stdout: '' }
164
+ }
165
+
166
+ Object.defineProperty(process, 'platform', { value: 'linux', configurable: true })
167
+ const result = await ensureManagedPython({ run, fetcher, settings: { engineAllowUnpinned: true }, env: {} })
168
+ assert.equal(result.source, 'managed-uv:ustc')
169
+ assert.equal(result.version.raw, '3.12.16', 'the rolling uv pairs with the mirror newest CPython')
170
+ const executable = path.join(isolated, 'engine', 'runtime', 'uv', 'uv')
171
+ assert.ok(fs.existsSync(executable), 'unpinned installs land in the rolling directory')
172
+ const metadata = JSON.parse(fs.readFileSync(path.join(isolated, 'engine', 'runtime', 'uv', 'verified.json'), 'utf8'))
173
+ assert.equal(metadata.version, '0.13.10')
174
+ assert.equal(metadata.archiveSha256, digest)
175
+ } finally {
176
+ Object.defineProperty(process, 'platform', { value: previousPlatform, configurable: true })
177
+ process.env.DSH_MEMU_HOME = previousHome
178
+ fs.rmSync(isolated, { recursive: true, force: true })
179
+ fs.rmSync(tarWork, { recursive: true, force: true })
180
+ }
181
+ })
@@ -61,7 +61,7 @@ test('context.occurredAt overrides sceneTime for the same write', async () => {
61
61
  test('month-end and unresolved relative wording are marked, not guessed', async () => {
62
62
  const { exec } = session('fields-precision')
63
63
  const monthEnd = await memory.privateRemember({ exec, title: '月底对账', content: '月底前把账对完。' })
64
- assert.equal(monthEnd.entry.absolute_date, '2026-11-30')
64
+ assert.equal(monthEnd.entry.absolute_date, undefined)
65
65
  assert.equal(monthEnd.entry.date_precision, 'month')
66
66
 
67
67
  const fuzzy = await memory.privateRemember({ exec, title: '下周再说', content: '下周再讨论排期。' })
@@ -89,24 +89,36 @@ test('an explicit absolute_date overrides prose and an impossible date is refuse
89
89
 
90
90
  test('valid_from / valid_to hide an entry outside its window and never hide old entries without them', async () => {
91
91
  const { exec, sessionId } = session('fields-validity')
92
+ // Windows are relative to the day the suite runs: absolute 2026-xx literals made
93
+ // this test expire as soon as the wall clock left that month.
94
+ const day = (offset) => {
95
+ const date = new Date()
96
+ date.setHours(12, 0, 0, 0)
97
+ date.setDate(date.getDate() + offset)
98
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
99
+ }
100
+ const expiredDay = day(-40)
101
+ const currentStart = day(-5)
102
+ const currentEnd = day(1)
103
+ const upcomingDay = day(2)
104
+ const now = Date.now()
92
105
  const expired = await memory.privateRemember({
93
- exec, title: '旧地址', content: '她住在旧公寓。', absoluteDate: '2026-10-01', validTo: '2026-10-31',
106
+ exec, title: '旧地址', content: '她住在旧公寓。', absoluteDate: day(-60), validTo: expiredDay,
94
107
  })
95
108
  const upcoming = await memory.privateRemember({
96
- exec, title: '新地址', content: '她下个月搬去新公寓。', absoluteDate: '2026-12-01', validFrom: '2026-12-01',
109
+ exec, title: '新地址', content: '她下个月搬去新公寓。', absoluteDate: upcomingDay, validFrom: upcomingDay,
97
110
  })
98
111
  const current = await memory.privateRemember({
99
- exec, title: '当前住处', content: '她现在住在河边的房子。', absoluteDate: '2026-11-01', validFrom: '2026-11-01', validTo: '2026-11-30',
112
+ exec, title: '当前住处', content: '她现在住在河边的房子。', absoluteDate: currentStart, validFrom: currentStart, validTo: currentEnd,
100
113
  })
101
114
  const legacy = await memory.privateRemember({ exec, title: '没有日期的旧条目', content: '窗户是朝东的。' })
102
- assert.equal(expired.entry.valid_to, '2026-10-31')
103
- assert.equal(upcoming.entry.valid_from, '2026-12-01')
115
+ assert.equal(expired.entry.valid_to, expiredDay)
116
+ assert.equal(upcoming.entry.valid_from, upcomingDay)
104
117
 
105
- const currentEligible = memory.isMemoryEligible(current.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') })
106
- assert.equal(currentEligible, true)
107
- assert.equal(memory.isMemoryEligible(expired.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') }), false)
108
- assert.equal(memory.isMemoryEligible(upcoming.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') }), false)
109
- assert.equal(memory.isMemoryEligible(legacy.entry, { now: Date.parse('2026-11-06T12:00:00+08:00') }), true)
118
+ assert.equal(memory.isMemoryEligible(current.entry, { now }), true)
119
+ assert.equal(memory.isMemoryEligible(expired.entry, { now }), false)
120
+ assert.equal(memory.isMemoryEligible(upcoming.entry, { now }), false)
121
+ assert.equal(memory.isMemoryEligible(legacy.entry, { now }), true)
110
122
 
111
123
  const recalled = await memory.privateRecall({ exec, query: '公寓 住处 窗户', topK: 10, relevanceThreshold: 0 })
112
124
  const ids = recalled.files.map((file) => file.name)
@@ -114,7 +126,7 @@ test('valid_from / valid_to hide an entry outside its window and never hide old
114
126
  assert.ok(ids.includes(legacy.id), 'an entry without a window is not filtered')
115
127
  assert.ok(!ids.includes(expired.id), 'a past valid_to is filtered')
116
128
  assert.ok(!ids.includes(upcoming.id), 'a future valid_from is filtered')
117
- assert.equal(index(sessionId).entries[expired.id].valid_to, '2026-10-31', 'filtering is read-only')
129
+ assert.equal(index(sessionId).entries[expired.id].valid_to, expiredDay, 'filtering is read-only')
118
130
  })
119
131
 
120
132
  test('rewriting the text re-derives the date; the query resolves relative words too', async () => {
@@ -0,0 +1,52 @@
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 crypto from 'node:crypto'
7
+ import sharp from 'sharp'
8
+
9
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-observed-'))
10
+ process.env.DSH_MEMU_HOME = home
11
+ const state = await import('../lib/state.js')
12
+ const memory = await import('../lib/memory.js')
13
+ const media = await import('../lib/media.js')
14
+
15
+ test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
16
+
17
+ test('missing attachment evidence discounts derived strength and accuracy, and restoration reverses it', async () => {
18
+ state.updateSettings({ memoryBackend: 'agent', autoLinkMode: 'off' })
19
+ const binding = state.ensureSession('observed', { cwd: path.join(home, 'project') })
20
+ const bytes = await sharp({ create: { width: 10, height: 10, channels: 3, background: '#339966' } }).png().toBuffer()
21
+ const sha = crypto.createHash('sha256').update(bytes).digest('hex')
22
+ const ref = { attachmentId: sha, mediaType: 'image/png', bytes: bytes.length, width: 10, height: 10 }
23
+ const session = { header: { id: 'observed' } }
24
+ await media.captureMediaEvent({ get: key => key === 'attachments' ? { readImage: async () => ({ ref, data: bytes }) } : null }, session,
25
+ { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'image', attachment: ref }] } })
26
+ const at = new Date().toISOString()
27
+ state.savePrivateIndex(binding.libraryId, { version: 1, entries: { 'mem-observed': {
28
+ title: 'evidence sample', content: 'evidence sample photograph', status: 'active', layer: 'long_term',
29
+ confidence: 0.8, accuracy: 0.8, strength: 1, createdAt: at, updatedAt: at,
30
+ attachments: [{ sha256: sha }],
31
+ } } })
32
+ const exec = { agent: { session } }
33
+ const recall = async () => (await memory.privateRecall({ exec, query: 'mem-observed', purpose: 'automatic', topK: 1 })).files[0]
34
+ const present = await recall()
35
+ assert.equal(present.name, 'mem-observed')
36
+ assert.equal(present.entry.observed, true)
37
+ const blobPath = path.join(home, 'attachments', binding.libraryId, fs.readdirSync(path.join(home, 'attachments', binding.libraryId))[0])
38
+ fs.unlinkSync(blobPath)
39
+ const missing = await recall()
40
+ assert.equal(missing.entry.observed, false)
41
+ assert.ok(Math.abs(missing.strength / present.strength - 0.85) < 1e-8)
42
+ assert.ok(Math.abs(missing.entry.accuracy - 0.68) < 1e-8)
43
+ const persisted = state.readPrivateIndex(binding.libraryId).entries['mem-observed']
44
+ assert.equal(persisted.strength, 1)
45
+ assert.equal(persisted.accuracy, 0.8)
46
+ assert.equal(persisted.observed, undefined, 'derived disk evidence must not rewrite the memory fact')
47
+ fs.writeFileSync(blobPath, bytes)
48
+ const restored = await recall()
49
+ assert.equal(restored.entry.observed, true)
50
+ assert.equal(restored.entry.accuracy, present.entry.accuracy)
51
+ assert.ok(Math.abs(restored.strength - present.strength) < 1e-8)
52
+ })
@@ -14,7 +14,8 @@ process.env.DSH_MEMU_HOME = home
14
14
 
15
15
  // 只从公开入口取能力:适配器就该这么用,测试顺带证明入口自洽。
16
16
  const port = await import('../lib/port-surface.js')
17
- const { createLibrary, ensureSession, loadPrivateIndex, savePrivateIndex, setWorkspacePolicy } = await import('../lib/state.js')
17
+ const { createLibrary, ensureSession, loadPrivateIndex, savePrivateIndex, setWorkspacePolicy, loadGlobalIndex, saveGlobalIndex, setSessionBinding } = await import('../lib/state.js')
18
+ const { dispatch } = await import('../lib/rpc.js')
18
19
 
19
20
  test.after(() => {
20
21
  try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
@@ -118,6 +119,97 @@ test('privateRemember writes with only a libraryId', async () => {
118
119
  )
119
120
  })
120
121
 
122
+ test('port omits raw storage and destructive management functions', () => {
123
+ for (const name of ['loadPrivateIndex', 'loadGlobalIndex', 'privateDelete', 'globalDelete', 'globalSetStatus', 'previewDelete', 'restoreDeleted']) {
124
+ assert.equal(port[name], undefined, `${name} belongs to the internal management surface`)
125
+ }
126
+ })
127
+
128
+ test('session-less private/global reads enforce identity boundaries without weakening browser management', async () => {
129
+ const lib = createLibrary({ name: 'port-restricted', cwd: path.join(home, 'port-restricted') })
130
+ const cases = {
131
+ secret: { visibility: 'secret' },
132
+ channel: { context: { channelId: 'restricted-channel' } },
133
+ character: { context: { characterId: 'restricted-character' } },
134
+ world: { context: { worldId: 'restricted-world' } },
135
+ branch: { context: { branchId: 'restricted-branch' } },
136
+ known: { context: { knownBy: ['restricted-knower'] } },
137
+ archived: { status: 'archived' },
138
+ pending: { status: 'pending_review' },
139
+ }
140
+ const global = loadGlobalIndex()
141
+ const hiddenIds = []
142
+ for (const [name, patch] of Object.entries(cases)) {
143
+ const id = `mem-restricted-${name}`
144
+ hiddenIds.push(id)
145
+ seed(lib.id, id, { title: `private hidden ${name}`, content: `restricted needle body ${name}`, ...patch })
146
+ global.entries[`g${id}`] = { layer: 'long_term', domain: 'general', status: 'active', title: `global hidden ${name}`, content: `restricted needle global ${name}`, ...patch }
147
+ }
148
+ saveGlobalIndex(global)
149
+ seed(lib.id, 'mem-port-visible', {
150
+ content: 'restricted needle visible content',
151
+ conflicts_with: hiddenIds[0],
152
+ links: hiddenIds.map(to => ({ to, kind: 'conflict', note: `hidden edge ${to}` })),
153
+ })
154
+ const g = loadGlobalIndex()
155
+ g.entries['gmem-port-visible'] = {
156
+ layer: 'long_term', domain: 'general', status: 'active', title: 'global visible', content: 'restricted needle global visible content',
157
+ absorbedFrom: hiddenIds.map(id => `g${id}`), representativeId: `g${hiddenIds[0]}`,
158
+ absorbSnapshot: { target: { id: `g${hiddenIds[0]}` }, sources: [{ id: `g${hiddenIds[1]}`, links: [{ to: `g${hiddenIds[2]}` }] }], rewired: [{ entryId: `g${hiddenIds[3]}` }] },
159
+ pendingAbsorb: { targetId: `g${hiddenIds[0]}`, sourceIds: hiddenIds },
160
+ maintenanceSnapshot: { hiddenBody: 'internal-maintenance-body', id: hiddenIds[0] },
161
+ audit: { id: hiddenIds[0] }, vector: { generation: 'internal-vector-generation' },
162
+ }
163
+ saveGlobalIndex(g)
164
+ for (const options of [{}, { restricted: false, admin: true, preferIndex: false }]) {
165
+ const listed = await port.privateList({ libraryId: lib.id, ...options })
166
+ assert.deepEqual(listed.files.map(file => file.name), ['mem-port-visible'])
167
+ const recalled = await port.privateRecall({ libraryId: lib.id, query: 'restricted needle', topK: 20, relevanceThreshold: 0, ...options })
168
+ assert.ok(recalled.files.some(file => file.name === 'mem-port-visible'))
169
+ const globalListed = await port.globalList({ domain: 'general', ...options })
170
+ assert.ok(globalListed.files.some(file => file.name === 'gmem-port-visible'))
171
+ const globalRecalled = await port.globalRecall({ query: 'restricted needle', topK: 20, relevanceThreshold: 0, ...options })
172
+ assert.ok(globalRecalled.files.some(file => file.name === 'gmem-port-visible'))
173
+ for (const result of [listed, recalled, globalListed, globalRecalled]) {
174
+ const serialized = JSON.stringify(result)
175
+ for (const id of hiddenIds) assert.ok(!serialized.includes(id), `hidden id must not leak via files, conflict groups, raw or relation placeholders: ${id}`)
176
+ assert.equal(result.raw, null)
177
+ assert.ok(!serialized.includes('internal-maintenance-body'))
178
+ assert.ok(!serialized.includes('internal-vector-generation'))
179
+ }
180
+ }
181
+ const browser = await dispatch({}, 'browseLibrary', { libraryId: lib.id })
182
+ assert.deepEqual(new Set(browser.files.map(file => file.id)), new Set(['mem-port-visible', ...hiddenIds]), 'management retains archived, review, secret and context-scoped rows')
183
+ await dispatch({}, 'updateMemory', { libraryId: lib.id, id: hiddenIds[0], patch: { title: 'managed secret' } })
184
+ assert.equal(loadPrivateIndex(lib.id).entries[hiddenIds[0]].title, 'managed secret')
185
+ for (const id of hiddenIds) {
186
+ await assert.rejects(() => port.privateUpdate({ libraryId: lib.id, id, title: 'forbidden' }), /unknown memory/)
187
+ assert.throws(() => port.privateArchive({ libraryId: lib.id, id }), /unknown memory/)
188
+ }
189
+ await port.privateUpdate({ libraryId: lib.id, id: 'mem-port-visible', title: 'updated visible' })
190
+ assert.equal(loadPrivateIndex(lib.id).entries['mem-port-visible'].title, 'updated visible')
191
+ const written = await port.privateRemember({ libraryId: lib.id, title: 'new boundary record', content: 'A newly supplied fact owned by another character.', context: { characterId: 'other' } })
192
+ assert.ok(written.id)
193
+ assert.equal(written.entry, null, 'permission to supply a scoped record does not grant read identity')
194
+ const hidden = await port.privateUpdate({ libraryId: lib.id, id: 'mem-port-visible', visibility: 'secret' })
195
+ assert.equal(hidden.entry, null, 'an edit that hides its result must not return the body')
196
+ })
197
+
198
+ test('bound port reads honor character identity and keep explicit secret reads', async () => {
199
+ const cwd = path.join(home, 'port-identity')
200
+ const binding = ensureSession('port-identity', { cwd })
201
+ setSessionBinding('port-identity', { memoryContext: { characterId: 'hero' } })
202
+ seed(binding.libraryId, 'mem-port-hero', { context: { knownBy: ['hero'] }, content: 'identity needle hero fact' })
203
+ seed(binding.libraryId, 'mem-port-villain', { context: { knownBy: ['villain'] }, content: 'identity needle villain fact' })
204
+ seed(binding.libraryId, 'mem-port-secret', { visibility: 'secret', content: 'identity needle explicitly readable secret' })
205
+ const exec = { agent: { session: { header: { id: 'port-identity', cwd } } } }
206
+ const listed = await port.privateList({ exec })
207
+ assert.deepEqual(new Set(listed.files.map(file => file.name)), new Set(['mem-port-hero', 'mem-port-secret']))
208
+ const recalled = await port.privateRecall({ exec, query: 'identity needle', topK: 20, relevanceThreshold: 0 })
209
+ assert.ok(recalled.files.some(file => file.name === 'mem-port-hero'))
210
+ assert.ok(!JSON.stringify(recalled).includes('mem-port-villain'))
211
+ })
212
+
121
213
  test('a folder that turned private memory off stays off for session-less callers', async () => {
122
214
  const lib = createLibrary({ name: 'port-disabled', cwd: path.join(home, 'port-disabled') })
123
215
  setWorkspacePolicy(lib.scopeKey, { useLibrary: false })
@@ -100,7 +100,7 @@ test('wrap 的 promise 去重:并发两次同 key,producer 只执行一次',
100
100
  const producer = async () => { runs += 1; await gate; return { n: runs } }
101
101
  const first = cache.wrap('k', producer)
102
102
  const joined = cache.wrap('k', producer)
103
- assert.equal(first, joined, '同 key 在途合并复用同一个 promise')
103
+ assert.notEqual(first, joined, '同 key 合并计算,每个等待者使用独立的 promise')
104
104
  assert.equal(cache.stats().inflight, 1)
105
105
  release()
106
106
  const [x, y] = await Promise.all([first, joined])
@@ -112,6 +112,57 @@ test('wrap 的 promise 去重:并发两次同 key,producer 只执行一次',
112
112
  assert.equal(stats.hits, 1, '在途合并计为一次命中')
113
113
  })
114
114
 
115
+ test('在途合并为各等待者深拷贝,嵌套变异不污染彼此或缓存', async () => {
116
+ const cache = createRecallCache()
117
+ let release
118
+ let runs = 0
119
+ const gate = new Promise(resolve => { release = resolve })
120
+ const producer = async () => { runs += 1; await gate; return { files: [{ id: 'original', tags: ['kept'] }] } }
121
+ const first = cache.wrap('isolated', producer)
122
+ const second = cache.wrap('isolated', producer)
123
+ const third = cache.wrap('isolated', producer)
124
+ release()
125
+ const [a, b, c] = await Promise.all([first, second, third])
126
+ assert.equal(runs, 1)
127
+ assert.notEqual(a.files[0], b.files[0])
128
+ assert.notEqual(b.files[0], c.files[0])
129
+ a.files[0].id = 'changed-first'
130
+ b.files[0].tags.push('changed-second')
131
+ assert.equal(c.files[0].id, 'original')
132
+ assert.deepEqual(c.files[0].tags, ['kept'])
133
+ assert.deepEqual(cache.get('isolated'), { files: [{ id: 'original', tags: ['kept'] }] })
134
+ })
135
+
136
+ test('首个消费者同步修改结果也不能抢先污染在途等待者', async () => {
137
+ const cache = createRecallCache()
138
+ let release
139
+ const gate = new Promise(resolve => { release = resolve })
140
+ const first = cache.wrap('immediate-mutation', async () => { await gate; return { nested: { value: 'original' } } })
141
+ const mutated = first.then(value => { value.nested.value = 'changed'; return value })
142
+ const joined = cache.wrap('immediate-mutation', () => assert.fail('must share producer'))
143
+ release()
144
+ assert.equal((await mutated).nested.value, 'changed')
145
+ assert.equal((await joined).nested.value, 'original')
146
+ assert.equal(cache.get('immediate-mutation').nested.value, 'original')
147
+ })
148
+
149
+ test('在途 producer 拒绝时所有等待者收到原错误,并允许重试', async () => {
150
+ const cache = createRecallCache()
151
+ let reject
152
+ const failure = new Error('shared producer failure')
153
+ const first = cache.wrap('failed', () => new Promise((resolve, no) => { reject = no }))
154
+ const joined = cache.wrap('failed', () => assert.fail('producer must be merged'))
155
+ const outcomes = Promise.allSettled([first, joined])
156
+ reject(failure)
157
+ for (const outcome of await outcomes) {
158
+ assert.equal(outcome.status, 'rejected')
159
+ assert.equal(outcome.reason, failure)
160
+ }
161
+ assert.equal(cache.stats().inflight, 0)
162
+ assert.equal(cache.stats().errors, 0)
163
+ assert.deepEqual(await cache.wrap('failed', () => ({ retried: true })), { retried: true })
164
+ })
165
+
115
166
  test('producer 抛错:不缓存、原样透传,下次重新执行', async () => {
116
167
  const cache = createRecallCache()
117
168
  let runs = 0
@@ -178,8 +229,10 @@ test('模块级单例存在且具备全部公开方法', () => {
178
229
  assert.equal(typeof recallCache[method], 'function', method)
179
230
  }
180
231
  assert.deepEqual(Object.keys(recallCache.stats()).sort(),
181
- ['errors', 'evictions', 'generations', 'hits', 'inflight', 'lastError', 'misses', 'size', 'staleSkipped'])
182
- assert.deepEqual(recallCacheStats(), recallCache.stats(), 'the stats reader is a snapshot of the singleton')
232
+ ['byteAccounting', 'bytes', 'errors', 'evictions', 'expirations', 'generations', 'hits', 'inflight', 'lastError', 'maxBytes', 'maxEntries', 'misses', 'oversized', 'size', 'staleSkipped', 'ttlMs'])
233
+ const { caches, ...own } = recallCacheStats()
234
+ assert.deepEqual(own, recallCache.stats(), 'the stats reader is a snapshot of the singleton')
235
+ assert.ok(caches.recall.maxBytes > 0, 'existing diagnostics expose shared bounded cache limits')
183
236
  })
184
237
 
185
238
  // ---------------------------------------------------------------- 接线部分
@@ -330,16 +330,27 @@ test('updating a memory into a near-duplicate of another entry is refused, not m
330
330
  'mem-host': entry('部署窗口约定', BODY_DEPLOY),
331
331
  'mem-t': entry('占位记录', '这条只是个占位,与部署无关。'),
332
332
  })
333
+ const original = structuredClone(state.loadPrivateIndex(f.libraryId).entries['mem-t'])
334
+ let pendingId
333
335
  await assert.rejects(
334
336
  memory.privateUpdate({ exec: f.exec, libraryId: f.libraryId, id: 'mem-t', content: BODY_DEPLOY }),
335
337
  (error) => {
336
338
  assert.match(error.message, /update refused/)
337
339
  assert.match(error.message, /mem-host/, 'the refusal must name the existing entry')
340
+ assert.equal(error.code, 'MEMORY_DRAFT_HELD')
341
+ pendingId = error.pendingId
338
342
  return true
339
343
  },
340
344
  )
341
345
  const index = state.loadPrivateIndex(f.libraryId)
342
- assert.equal(index.entries['mem-t'].content, '这条只是个占位,与部署无关。', 'the refused update changes nothing')
346
+ assert.deepEqual(index.entries['mem-t'], original, 'the refused update preserves the complete original')
347
+ assert.ok(pendingId)
348
+ assert.equal(index.entries[pendingId].content, BODY_DEPLOY)
349
+ assert.equal(index.entries[pendingId].status, 'pending_review')
350
+ assert.equal(index.entries[pendingId].draftOf, 'mem-t')
351
+ assert.equal(index.entries[pendingId].draftOperation, 'update')
352
+ assert.equal(index.entries[pendingId].vector, undefined)
353
+ assert.equal(memory.isMemoryEligible(index.entries[pendingId]), false)
343
354
  assert.equal(index.entries['mem-host'].content, BODY_DEPLOY, 'the existing entry is untouched')
344
355
  assert.equal(commitCalls.length, 0, 'the refusal happens before any backend commit')
345
356
  const event = activity.listEvents({ kind: 'write' }).find((item) => item.detail?.deduped === true && item.detail?.id === 'mem-t')
@@ -359,6 +370,45 @@ test('rewriting an entry close to its own previous text is not a duplicate (self
359
370
  assert.equal(result.entry.duplicateOf, undefined)
360
371
  })
361
372
 
373
+ test('rejected draft retries reuse one pending proposal and stale content CAS still refuses before saving', async () => {
374
+ const f = fixture({ 'mem-host': entry('部署窗口约定', BODY_DEPLOY), 'mem-t': entry('占位记录', '完全不同的旧稿。') })
375
+ const ids = []
376
+ for (let i = 0; i < 2; i++) {
377
+ await assert.rejects(memory.privateUpdate({ exec: f.exec, id: 'mem-t', content: BODY_DEPLOY }), error => {
378
+ assert.equal(error.code, 'MEMORY_DRAFT_HELD'); ids.push(error.pendingId); return true
379
+ })
380
+ }
381
+ assert.equal(ids[0], ids[1])
382
+ assert.equal(Object.keys(state.loadPrivateIndex(f.libraryId).entries).length, 3)
383
+ const stale = memory.memoryEntryRevision(state.loadPrivateIndex(f.libraryId).entries['mem-t'])
384
+ state.updatePrivateIndex(f.libraryId, index => { index.entries['mem-t'].title = '并发修订的原条' })
385
+ await assert.rejects(memory.privateUpdate({ exec: f.exec, id: 'mem-t', content: BODY_DEPLOY, expectedRevision: stale }), { code: 'MEMORY_CHANGED' })
386
+ assert.equal(Object.keys(state.loadPrivateIndex(f.libraryId).entries).length, 3)
387
+ assert.equal(commitCalls.length, 0)
388
+ })
389
+
390
+ test('a hidden duplicate update preserves the draft without exposing its target id', async () => {
391
+ const f = fixture({
392
+ 'mem-hidden-target': entry('占位记录', BODY_DEPLOY, { context: { characterId: 'hero', knownBy: ['someone-else'] } }),
393
+ 'mem-t': entry('占位记录', '完全不同的旧稿。', { context: { characterId: 'hero', knownBy: ['hero'] } }),
394
+ })
395
+ state.setSessionBinding(f.sessionId, { memoryContext: { characterId: 'hero' } })
396
+ const before = state.loadPrivateIndex(f.libraryId)
397
+ assert.equal(memory.visibleToSession(before.entries['mem-hidden-target'], f.sessionId), false)
398
+ assert.equal(memory.visibleToSession(before.entries['mem-t'], f.sessionId), true)
399
+ let pendingId
400
+ await assert.rejects(memory.privateUpdate({ exec: f.exec, id: 'mem-t', content: BODY_DEPLOY }), error => {
401
+ assert.equal(error.code, 'MEMORY_DRAFT_HELD')
402
+ assert.equal(error.message.includes('mem-hidden-target'), false)
403
+ pendingId = error.pendingId; return true
404
+ })
405
+ const after = state.loadPrivateIndex(f.libraryId)
406
+ assert.deepEqual(after.entries['mem-t'], before.entries['mem-t'])
407
+ assert.equal(after.entries[pendingId].status, 'pending_review')
408
+ assert.equal(JSON.stringify(after.entries[pendingId]).includes('mem-hidden-target'), false)
409
+ assert.equal(commitCalls.length, 0)
410
+ })
411
+
362
412
  test('an update landing in the topic band tags duplicateOf instead of refusing', async () => {
363
413
  const f = fixture({
364
414
  'mem-host': entry('部署窗口约定', BODY_DEPLOY),
@@ -401,16 +451,27 @@ test('review accept that would duplicate a third entry is refused and the review
401
451
  'mem-c': entry('部署窗口约定', BODY_DEPLOY),
402
452
  'mem-p': entry('茶水间的约定', '茶水间自动售货机经常卡币的说法待定。', { status: 'pending_review', conflictingWith: 'mem-c', reviewReason: 'conflict' }),
403
453
  })
454
+ const original = structuredClone(state.loadPrivateIndex(f.libraryId).entries['mem-p'])
455
+ let pendingId
404
456
  await assert.rejects(
405
457
  memory.resolveMemoryReview({ libraryId: f.libraryId, id: 'mem-p', action: 'accept', content: BODY_COFFEE }),
406
458
  (error) => {
407
459
  assert.match(error.message, /review accept refused/)
408
460
  assert.match(error.message, /mem-third/)
461
+ assert.equal(error.code, 'MEMORY_DRAFT_HELD')
462
+ pendingId = error.pendingId
409
463
  return true
410
464
  },
411
465
  )
412
466
  const index = state.loadPrivateIndex(f.libraryId)
413
- assert.equal(index.entries['mem-p'].status, 'pending_review', 'the review stays resolvable')
467
+ assert.deepEqual(index.entries['mem-p'], original, 'the original review remains completely unchanged')
468
+ assert.ok(pendingId && pendingId !== 'mem-p')
469
+ assert.equal(index.entries[pendingId].content, BODY_COFFEE)
470
+ assert.equal(index.entries[pendingId].status, 'pending_review')
471
+ assert.equal(index.entries[pendingId].draftOf, 'mem-p')
472
+ assert.equal(index.entries[pendingId].draftOperation, 'review-accept')
473
+ assert.equal(index.entries[pendingId].vector, undefined)
474
+ assert.equal(commitCalls.length, 0)
414
475
  assert.equal(index.entries['mem-c'].status, 'active', 'a refused accept supersedes nothing')
415
476
  })
416
477