dsh-memu-memory 1.2.8 → 1.2.9

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 (78) hide show
  1. package/CHANGELOG.md +472 -0
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/lib/backup.js +154 -25
  5. package/lib/binding-diagnostics.js +1 -2
  6. package/lib/budget.js +0 -9
  7. package/lib/client.js +221 -128
  8. package/lib/commitment.js +3 -3
  9. package/lib/consolidation-ledger.js +5 -2
  10. package/lib/curator-policy.js +23 -0
  11. package/lib/cycle.js +8 -4
  12. package/lib/embedding-download.js +168 -28
  13. package/lib/embedding-runtime.js +76 -17
  14. package/lib/engine.js +0 -6
  15. package/lib/freshness.js +2 -2
  16. package/lib/graph.js +139 -11
  17. package/lib/index.js +71 -20
  18. package/lib/inject.js +50 -7
  19. package/lib/lexicon.js +61 -16
  20. package/lib/local-vector-service.js +21 -1
  21. package/lib/media.js +49 -12
  22. package/lib/memory.js +662 -116
  23. package/lib/paths.js +0 -7
  24. package/lib/preset-scope.js +6 -1
  25. package/lib/private.js +45 -7
  26. package/lib/prompts.js +0 -7
  27. package/lib/rpc.js +95 -17
  28. package/lib/snippet.js +18 -2
  29. package/lib/state.js +109 -30
  30. package/lib/stats.js +2 -2
  31. package/lib/temporal.js +19 -0
  32. package/lib/text-retrieval.js +120 -44
  33. package/lib/text-similarity.js +205 -24
  34. package/lib/tokenizer-v2.js +0 -24
  35. package/lib/vector-migration.js +15 -0
  36. package/lib/vector-profile.js +81 -8
  37. package/lib/visibility.js +0 -4
  38. package/lib/webui/standalone.css +17 -22
  39. package/lib/webui/standalone.js +27 -9
  40. package/lib/webui.js +4 -4
  41. package/package.json +3 -2
  42. package/scripts/acceptance-local.mjs +2 -2
  43. package/scripts/check-all.mjs +3 -1
  44. package/scripts/check-i18n.mjs +35 -1
  45. package/scripts/migrate-visibility.mjs +3 -3
  46. package/scripts/prune-sessions.mjs +34 -0
  47. package/scripts/prune-vectors.mjs +24 -0
  48. package/tests/appendix-b.test.mjs +5 -4
  49. package/tests/audit-batch3.test.mjs +247 -0
  50. package/tests/audit-regression.test.mjs +2 -2
  51. package/tests/backup.test.mjs +83 -83
  52. package/tests/browser.test.mjs +6 -1
  53. package/tests/client-render.test.mjs +2 -2
  54. package/tests/curator-clusters.test.mjs +18 -0
  55. package/tests/curator-pairing.test.mjs +59 -16
  56. package/tests/dynamic-rrf.test.mjs +22 -19
  57. package/tests/dynamic-threshold.test.mjs +52 -0
  58. package/tests/fact-version.test.mjs +18 -0
  59. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  60. package/tests/graph-cascade.test.mjs +29 -0
  61. package/tests/graph.test.mjs +45 -0
  62. package/tests/inject-conflict.test.mjs +18 -0
  63. package/tests/lexical-bm25.test.mjs +171 -0
  64. package/tests/lexicon-frequency.test.mjs +16 -0
  65. package/tests/lexicon-inject.test.mjs +21 -0
  66. package/tests/lexicon-perf.test.mjs +37 -9
  67. package/tests/lexicon-scope.test.mjs +2 -2
  68. package/tests/lexicon-ui.test.mjs +1 -1
  69. package/tests/managed-memory.test.mjs +19 -0
  70. package/tests/ops-hardening.test.mjs +209 -0
  71. package/tests/package-shipping.test.mjs +4 -0
  72. package/tests/recall-intent.test.mjs +23 -0
  73. package/tests/slot-similarity.test.mjs +153 -0
  74. package/tests/state-gc.test.mjs +34 -0
  75. package/tests/state.test.mjs +2 -2
  76. package/tests/tokenizer-v2.test.mjs +1 -1
  77. package/tests/vector-gc.test.mjs +37 -0
  78. package/tests/webui.test.mjs +27 -0
@@ -280,7 +280,10 @@ function naiveBucketKeysOf(entry) {
280
280
  return [...keys]
281
281
  }
282
282
 
283
- function naiveTextBuckets(normalizedText, maxBuckets = LEXICON_MAX_BUCKETS) {
283
+ // 窗口顺序与 lib 的 textBuckets 同口径:按桶命中词条数降序(A-8),而不是
284
+ // 按出现顺序取前 16 个。bucketSizeOf 用全量词条桶(含不可见词条)计算,与
285
+ // 索引里的 prefixBuckets.size 一致。
286
+ function naiveTextBuckets(normalizedText, bucketSizeOf, maxBuckets = LEXICON_MAX_BUCKETS) {
284
287
  const keys = []
285
288
  const seen = new Set()
286
289
  for (let i = 0; i + BUCKET_WIDTH <= normalizedText.length; i++) {
@@ -288,9 +291,12 @@ function naiveTextBuckets(normalizedText, maxBuckets = LEXICON_MAX_BUCKETS) {
288
291
  if (seen.has(key)) continue
289
292
  seen.add(key)
290
293
  keys.push(key)
291
- if (keys.length >= maxBuckets) break
292
294
  }
293
295
  return keys
296
+ .map((key, order) => ({ key, order, hits: bucketSizeOf(key) }))
297
+ .sort((a, b) => b.hits - a.hits || a.order - b.order)
298
+ .slice(0, maxBuckets)
299
+ .map(item => item.key)
294
300
  }
295
301
 
296
302
  function naiveDiceFallback(normalizedText, candidates, { threshold = LEXICON_DICE_THRESHOLD, maxCandidates = LEXICON_MAX_CANDIDATES, maxTerms = LEXICON_MAX_TERMS } = {}) {
@@ -383,7 +389,11 @@ function naiveMatch(terms, userText, memoryContext) {
383
389
  if (!normalizedText) return []
384
390
  const visibleIds = []
385
391
  const byBucket = new Map()
392
+ const allBucketSizes = new Map()
386
393
  for (const [termId, entry] of Object.entries(terms)) {
394
+ for (const key of naiveBucketKeysOf(entry)) {
395
+ allBucketSizes.set(key, (allBucketSizes.get(key) || 0) + 1)
396
+ }
387
397
  if ((entry.status || 'active') !== 'active') continue
388
398
  if (!contextVisible(entry.context, memoryContext)) continue
389
399
  visibleIds.push(termId)
@@ -394,15 +404,33 @@ function naiveMatch(terms, userText, memoryContext) {
394
404
  }
395
405
  const exact = naiveExactHits(terms, normalizedText, visibleIds)
396
406
  const exactIds = new Set(exact.map(hit => hit.termId))
397
- const candidateIds = []
398
- for (const key of naiveTextBuckets(normalizedText)) {
399
- for (const termId of byBucket.get(key) || []) {
400
- if (!exactIds.has(termId) && !candidateIds.includes(termId)) candidateIds.push(termId)
407
+ // 候选按「与 query 共享的 gram 数」降序(A-8);strength 与 termId 只做
408
+ // 确定性 tiebreak。共享 gram 按整段 query 与每个词面计算(与 lib 同口径)。
409
+ const candidateIds = new Set()
410
+ for (const key of naiveTextBuckets(normalizedText, k => allBucketSizes.get(k) || 0)) {
411
+ for (const termId of new Set(byBucket.get(key) || [])) {
412
+ if (exactIds.has(termId)) continue
413
+ candidateIds.add(termId)
414
+ }
415
+ }
416
+ const textGrams = bigrams(normalizedText)
417
+ const sharedGramCount = termId => {
418
+ let best = 0
419
+ for (const surface of [terms[termId].normalizedTerm, ...(terms[termId].normalizedAliases || [])]) {
420
+ if (!surface) continue
421
+ let shared = 0
422
+ for (const gram of bigrams(surface)) if (textGrams.has(gram)) shared += 1
423
+ if (shared > best) best = shared
401
424
  }
425
+ return best
402
426
  }
403
- const candidates = candidateIds
404
- .map(termId => naiveHitOf(terms[termId], termId, 'dice', 0))
405
- .sort((a, b) => (Number(b.strength) || 0) * (Number(b.confidence) || 0) - (Number(a.strength) || 0) * (Number(a.strength) || 0))
427
+ const weightOf = termId => (Number(terms[termId].strength) || 0) * (Number(terms[termId].confidence) || 0)
428
+ const candidates = [...candidateIds]
429
+ .map(termId => ({ termId, shared: sharedGramCount(termId) }))
430
+ .sort((a, b) => b.shared - a.shared
431
+ || weightOf(b.termId) - weightOf(a.termId)
432
+ || String(a.termId).localeCompare(String(b.termId)))
433
+ .map(({ termId }) => naiveHitOf(terms[termId], termId, 'dice', 0))
406
434
  const fuzzy = naiveDiceFallback(normalizedText, candidates)
407
435
  return naiveStableRank([...exact, ...fuzzy])
408
436
  }
@@ -230,9 +230,9 @@ test('lexiconAdd 带会话时给私有词条打领域戳', async () => {
230
230
  assert.equal(entryOf(libs.current.id, '面板词').domain, 'coding')
231
231
  })
232
232
 
233
- test('全局词典与私有词典同权进自动备份清单', () => {
233
+ test('全局词典与私有词典同权进自动备份清单', async () => {
234
234
  world()
235
- const created = backup.createBackup({ label: 'lexicon-scope-global' })
235
+ const created = await backup.createBackup({ label: 'lexicon-scope-global' })
236
236
  const manifest = JSON.parse(fs.readFileSync(path.join(created.dir, 'manifest.json'), 'utf8'))
237
237
  assert.ok(manifest.files[`lexicon/${GLOBAL_ID}.json`], 'global.json 是词典数据,必须在备份里')
238
238
  })
@@ -359,7 +359,7 @@ test('backup manifest carries the lexicon store and skips unsafe names', async (
359
359
  const junk = path.join(dataDir(), 'lexicon', 'bad id.json')
360
360
  fs.mkdirSync(path.dirname(junk), { recursive: true })
361
361
  fs.writeFileSync(junk, '{}')
362
- const created = backup.createBackup({ label: 'lexicon-ui' })
362
+ const created = await backup.createBackup({ label: 'lexicon-ui' })
363
363
  const manifest = JSON.parse(fs.readFileSync(path.join(created.dir, 'manifest.json'), 'utf8'))
364
364
  const rel = `lexicon/${lib.id}.json`
365
365
  assert.ok(manifest.files[rel], `manifest lists ${rel}`)
@@ -400,6 +400,25 @@ test('library queue spans compensation across routes and releases after failure'
400
400
  assert.equal(backendRows.size, 1)
401
401
  })
402
402
 
403
+ test('managed vector commit failure defers to index-only instead of losing the write', async () => {
404
+ const f = fixture()
405
+ activate([f.libraryId])
406
+ failCommit = true
407
+ const written = await memory.privateRemember({ exec: f.exec, content: 'deferred write survives', title: 'deferred' })
408
+ let entry = state.loadPrivateIndex(f.libraryId).entries[written.id]
409
+ assert.equal(entry.content, 'deferred write survives')
410
+ assert.equal(entry.vectorPending, true)
411
+ assert.equal(entry.vector, undefined)
412
+ assert.equal(backendRows.size, 0, 'nothing was falsely recorded as committed')
413
+ assert.ok(warnings.some(message => /deferred/.test(message)), 'the degradation must be observable')
414
+
415
+ failCommit = false
416
+ await memory.privateUpdate({ exec: f.exec, id: written.id, content: 'deferred write now committed' })
417
+ entry = state.loadPrivateIndex(f.libraryId).entries[written.id]
418
+ assert.equal(entry.vectorPending, undefined, 'a later successful commit clears the pending flag')
419
+ assert.equal(entry.vector.route, 'managed-local')
420
+ })
421
+
403
422
  test('managed import failure rejects without index-first false success', async () => {
404
423
  const f = fixture()
405
424
  activate([f.libraryId])
@@ -0,0 +1,209 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-ops-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+ const activity = await import('../lib/activity-log.js')
13
+ const media = await import('../lib/media.js')
14
+ const { zipSync, unzipSync } = await import('fflate')
15
+ const { dispatch } = await import('../lib/rpc.js')
16
+
17
+ test.after(() => {
18
+ state.flushState()
19
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
20
+ })
21
+
22
+ function session(name) {
23
+ const cwd = path.join(home, 'ws', name)
24
+ state.ensureSession(name, { cwd, agentPreset: 'coding' })
25
+ return {
26
+ libraryId: state.getSessionBinding(name).libraryId,
27
+ exec: { agent: { session: { header: { id: name, cwd, agentPreset: 'coding' } } } },
28
+ }
29
+ }
30
+
31
+ test('permanently deleting a host clears duplicateOf on its copies', async () => {
32
+ const { libraryId, exec } = session('ops-delete')
33
+ const now = new Date().toISOString()
34
+ state.savePrivateIndex(libraryId, {
35
+ entries: {
36
+ 'mem-host': { title: 'host', content: 'host body', status: 'archived', layer: 'long_term', createdAt: now, updatedAt: now },
37
+ 'mem-copy': { title: 'copy', content: 'copy body', status: 'active', layer: 'long_term', createdAt: now, updatedAt: now, duplicateOf: 'mem-host' },
38
+ },
39
+ })
40
+ await memory.privateDelete({ exec, id: 'mem-host' })
41
+ const entries = state.loadPrivateIndex(libraryId).entries
42
+ assert.equal(entries['mem-host'], undefined)
43
+ assert.equal(entries['mem-copy'].duplicateOf, undefined, 'a dangling duplicateOf must not keep the soft penalty')
44
+ assert.equal(entries['mem-copy'].content, 'copy body')
45
+ })
46
+
47
+ test('clearing the activity log requires explicit confirmation', async () => {
48
+ activity.clearEvents()
49
+ activity.record({ kind: 'write', message: 'must survive an unconfirmed clear' })
50
+ await assert.rejects(
51
+ () => dispatch({}, 'clearActivityLog', {}),
52
+ /explicit confirmation/,
53
+ )
54
+ assert.equal(activity.listEvents().length, 1, 'the unconfirmed call must not clear anything')
55
+ await dispatch({}, 'clearActivityLog', { confirmed: true })
56
+ assert.equal(activity.listEvents().length, 0)
57
+ })
58
+
59
+ test('delete preview is read-only and a permanent delete can be restored locally', async () => {
60
+ const { libraryId } = session('ops-delete-restore')
61
+ const now = new Date().toISOString()
62
+ state.savePrivateIndex(libraryId, {
63
+ entries: {
64
+ 'mem-restorable': {
65
+ title: 'restorable', content: 'this body should come back', status: 'archived',
66
+ layer: 'long_term', createdAt: now, updatedAt: now,
67
+ },
68
+ },
69
+ })
70
+ const preview = await dispatch({}, 'deleteMemory', { libraryId, id: 'mem-restorable', preview: true })
71
+ assert.equal(preview.deletable, true)
72
+ assert.equal(preview.plan.deleteFromIndex, true)
73
+ assert.ok(state.loadPrivateIndex(libraryId).entries['mem-restorable'], 'preview must not write')
74
+
75
+ await assert.rejects(
76
+ () => dispatch({}, 'deleteMemory', { libraryId, id: 'mem-restorable' }),
77
+ /explicit confirmation/,
78
+ 'an archived memory still needs consent before it is erased',
79
+ )
80
+ await dispatch({}, 'deleteMemory', { libraryId, id: 'mem-restorable', confirmed: true })
81
+ assert.equal(state.loadPrivateIndex(libraryId).entries['mem-restorable'], undefined)
82
+ const restored = await dispatch({}, 'deleteMemory', { libraryId, id: 'mem-restorable', restore: true })
83
+ assert.equal(restored.entry.content, 'this body should come back')
84
+ assert.equal(restored.entry.status, 'active')
85
+ assert.equal(state.loadPrivateIndex(libraryId).entries['mem-restorable'].content, 'this body should come back')
86
+ await assert.rejects(() => dispatch({}, 'deleteMemory', { libraryId, id: 'mem-nope', restore: true }), /no deleted memory/)
87
+ })
88
+
89
+ test('a memory bundle carries a memories checksum and rejects tampering', () => {
90
+ const { libraryId } = session('ops-bundle')
91
+ const bundle = media.exportMediaBundle(libraryId, {
92
+ bundleId: 'bnd-test',
93
+ memories: [{ title: 'bundle member', content: 'bundle member body' }],
94
+ graph: null,
95
+ lexicon: null,
96
+ })
97
+ const files = unzipSync(bundle)
98
+ const manifest = JSON.parse(Buffer.from(files['manifest.json']).toString('utf8'))
99
+ assert.equal(manifest.bundleId, 'bnd-test')
100
+ assert.match(manifest.memoriesSha256, /^[0-9a-f]{64}$/)
101
+ const imported = media.importMediaBundle(libraryId, bundle)
102
+ assert.equal(imported.bundleId, 'bnd-test')
103
+
104
+ files['memories.json'] = Buffer.from(JSON.stringify({ bundleId: 'bnd-test', memories: [{ title: 'tampered', content: 'tampered' }] }))
105
+ const tampered = Buffer.from(zipSync(files, { level: 0 }))
106
+ assert.throws(() => media.importMediaBundle(libraryId, tampered), /memories\.json checksum mismatch/)
107
+ })
108
+
109
+ test('an import batch can be reverted without touching earlier memories', async () => {
110
+ const { libraryId } = session('ops-revert')
111
+ const now = new Date().toISOString()
112
+ state.savePrivateIndex(libraryId, {
113
+ entries: { 'mem-before': { title: 'before', content: 'before body', status: 'active', layer: 'long_term', createdAt: now, updatedAt: now } },
114
+ })
115
+ const imported = await dispatch({}, 'importMemories', {
116
+ libraryId,
117
+ bundleId: 'bnd-revert',
118
+ memories: [{ title: 'bundle fact', content: 'this fact came from a bundle' }],
119
+ })
120
+ assert.equal(imported.importBatchId, 'bnd-revert')
121
+ let entries = state.loadPrivateIndex(libraryId).entries
122
+ assert.ok(Object.values(entries).some((entry) => entry.importedBundle === 'bnd-revert'))
123
+ const reverted = await dispatch({}, 'importMemories', { libraryId, revertBatchId: 'bnd-revert' })
124
+ assert.equal(reverted.removed, 1)
125
+ entries = state.loadPrivateIndex(libraryId).entries
126
+ assert.equal(entries['mem-before'].content, 'before body')
127
+ assert.ok(!Object.values(entries).some((entry) => entry.importedBundle === 'bnd-revert'))
128
+ })
129
+
130
+
131
+ function bundleWithManifest(files, manifest) {
132
+ return Buffer.from(zipSync({ ...files, 'manifest.json': Buffer.from(JSON.stringify(manifest)) }, { level: 0 }))
133
+ }
134
+
135
+ test('a v2 bundle rejects a removed, malformed or forged checksum', () => {
136
+ const { libraryId } = session('ops-bundle-integrity')
137
+ const files = unzipSync(media.exportMediaBundle(libraryId, {
138
+ bundleId: 'bnd-integrity', memories: [{ title: 'kept', content: 'kept body' }], graph: null, lexicon: null,
139
+ }))
140
+ const manifest = JSON.parse(Buffer.from(files['manifest.json']).toString('utf8'))
141
+ assert.equal(manifest.format, 'dsh-memu-memory-media@2')
142
+ assert.equal(media.importMediaBundle(libraryId, bundleWithManifest(files, manifest)).memories.length, 1)
143
+
144
+ const removed = { ...manifest }
145
+ delete removed.memoriesSha256
146
+ assert.throws(() => media.importMediaBundle(libraryId, bundleWithManifest(files, removed)), /checksum missing/)
147
+ assert.throws(() => media.importMediaBundle(libraryId, bundleWithManifest(files, { ...manifest, memoriesSha256: 'nope' })), /checksum is malformed/)
148
+ assert.throws(() => media.importMediaBundle(libraryId, bundleWithManifest(files, { ...manifest, memoriesSha256: '0'.repeat(64) })), /checksum mismatch/)
149
+ })
150
+
151
+ test('legacy v1 archives without a checksum stay importable', () => {
152
+ const { libraryId } = session('ops-bundle-legacy')
153
+ const archive = Buffer.from(zipSync({
154
+ 'memories.json': Buffer.from(JSON.stringify({ memories: [{ title: 'legacy', content: 'legacy body' }] })),
155
+ 'manifest.json': Buffer.from(JSON.stringify({ format: 'dsh-memu-media@1', blobs: {} })),
156
+ }, { level: 0 }))
157
+ assert.equal(media.importMediaBundle(libraryId, archive).memories.length, 1)
158
+ })
159
+
160
+ test('streaming imports enforce the same checksum rule', async () => {
161
+ const { Readable } = await import('node:stream')
162
+ const { libraryId } = session('ops-bundle-stream')
163
+ const files = unzipSync(media.exportMediaBundle(libraryId, {
164
+ bundleId: 'bnd-stream', memories: [{ title: 'streamed', content: 'streamed body' }], graph: null, lexicon: null,
165
+ }))
166
+ const manifest = JSON.parse(Buffer.from(files['manifest.json']).toString('utf8'))
167
+ delete manifest.memoriesSha256
168
+ await assert.rejects(
169
+ media.importMediaStream(libraryId, Readable.from([bundleWithManifest(files, manifest)])),
170
+ /checksum missing/,
171
+ )
172
+ })
173
+
174
+ test('a corrupt manifest is reported as an invalid archive, not a raw SyntaxError', () => {
175
+ const { libraryId } = session('ops-bundle-corrupt')
176
+ const archive = Buffer.from(zipSync({
177
+ 'memories.json': Buffer.from('{ not json'),
178
+ 'manifest.json': Buffer.from('{ not json'),
179
+ }, { level: 0 }))
180
+ assert.throws(() => media.importMediaBundle(libraryId, archive), /invalid memory archive/)
181
+ })
182
+
183
+ test('an expired delete stash cannot be restored, is swept and never enters a backup', async () => {
184
+ const { indexDir, writeJson } = await import('../lib/paths.js')
185
+ const { libraryId, exec } = session('ops-delete-ttl')
186
+ const now = new Date().toISOString()
187
+ state.savePrivateIndex(libraryId, {
188
+ entries: { 'mem-expired': { title: 'gone', content: 'PERMANENTLY-DELETED-BODY', status: 'archived', layer: 'long_term', createdAt: now, updatedAt: now } },
189
+ })
190
+ await memory.privateDelete({ exec, id: 'mem-expired' })
191
+ const stashPath = path.join(indexDir(), `${libraryId}.deleted.json`)
192
+ const stash = JSON.parse(fs.readFileSync(stashPath, 'utf8'))
193
+ assert.ok(stash.items['mem-expired'], 'a fresh delete is still restorable')
194
+ stash.items['mem-expired'].deletedAt = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString()
195
+ writeJson(stashPath, stash)
196
+ await assert.rejects(() => memory.restoreDeleted({ libraryId, id: 'mem-expired' }), /no deleted memory/)
197
+
198
+ const swept = memory.pruneDeletedStores()
199
+ assert.ok(swept.removed >= 1, 'the startup sweep must drop expired stash entries')
200
+ assert.ok(!JSON.parse(fs.readFileSync(stashPath, 'utf8')).items['mem-expired'])
201
+
202
+ const dest = await state.backupDatabases()
203
+ const manifest = JSON.parse(fs.readFileSync(path.join(dest, 'manifest.json'), 'utf8'))
204
+ assert.deepEqual(
205
+ Object.keys(manifest.files).filter(rel => rel.endsWith('.deleted.json')),
206
+ [],
207
+ 'permanently deleted bodies must not leak into a backup',
208
+ )
209
+ })
@@ -43,6 +43,10 @@ function runCheckAll(root) {
43
43
  test('package.json ships tests/ so the packaged suite is not silently empty', () => {
44
44
  assert.ok(Array.isArray(pkg.files), 'package.json needs a files whitelist')
45
45
  assert.ok(pkg.files.includes('tests'), 'files must include "tests" or npm test finds 0 test files')
46
+ // G-1 in the packaged acceptance suite reads CHANGELOG.md. If it does not ship,
47
+ // the installed package reports a 49/50 acceptance run while the repo is 50/50.
48
+ assert.ok(pkg.files.includes('CHANGELOG.md'), 'files must include "CHANGELOG.md" for packaged acceptance G-1')
49
+ assert.equal(new Set(pkg.files).size, pkg.files.length, 'files must not contain duplicate entries')
46
50
  // The suite is only runnable if its harness (loader + stubs) travels with it.
47
51
  for (const rel of ['loader-register.mjs', 'loader.mjs', 'stubs/dsh-llm.js']) {
48
52
  assert.ok(fs.existsSync(path.join(REPO, 'tests', rel)), 'tests/' + rel + ' must ship with the package')
@@ -67,6 +67,29 @@ test('one-hop expansion follows an explicit link to a memory the query never mat
67
67
  assert.ok(recalled.files.find((file) => file.name === b.id).relatedTo === a.id)
68
68
  })
69
69
 
70
+ test('graph expansion only fills empty topK seats, never adds injected entries', async () => {
71
+ const { exec, sessionId } = session('intent-multihop-budget')
72
+ const a = await memory.privateRemember({
73
+ exec, title: '码头灯塔记录', content: '林眠傍晚去了码头看灯塔。',
74
+ })
75
+ const b = await memory.privateRemember({
76
+ exec, title: '灯塔亮起时间', content: '码头边的灯塔亮了三次。',
77
+ })
78
+ const linked = await memory.privateRemember({
79
+ exec, title: '她带了一把旧伞', content: '那天她带着一把旧伞。',
80
+ })
81
+ const binding = state.getSessionBinding(sessionId)
82
+ state.updatePrivateIndex(binding.libraryId, (index) => {
83
+ index.entries[a.id].links = [{ to: linked.id, kind: 'event', note: 'same evening', confidence: 0.9 }]
84
+ })
85
+ const recalled = await memory.privateRecall({ exec, query: '码头 灯塔', topK: 2, relevanceThreshold: 0 })
86
+ const ids = recalled.files.map((file) => file.name)
87
+ assert.equal(recalled.files.length, 2, 'topK seats stay full; expansion cannot add a third')
88
+ assert.ok(ids.includes(a.id) && ids.includes(b.id))
89
+ assert.ok(!ids.includes(linked.id), 'the linked memory must wait until a seat is free')
90
+ assert.equal(recalled.expanded, undefined)
91
+ })
92
+
70
93
  test('automatic recall hides never_say and only_if_asked; boundary questions release only_if_asked', async () => {
71
94
  const { exec } = session('intent-disclosure')
72
95
  const open = await memory.privateRemember({
@@ -0,0 +1,153 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-slots-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+ const similarity = await import('../lib/text-similarity.js')
13
+
14
+ test.after(() => {
15
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
16
+ })
17
+
18
+ let seq = 0
19
+ function session(name) {
20
+ seq += 1
21
+ const cwd = path.join(home, 'ws', `${name}-${seq}`)
22
+ const sessionId = `${name}-${seq}`
23
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
24
+ return {
25
+ sessionId,
26
+ libraryId: state.getSessionBinding(sessionId).libraryId,
27
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } },
28
+ }
29
+ }
30
+
31
+ const LOAN_A = '图书馆借阅规则:每人每次最多借五本书,借期十四天,可以续借一次,逾期按天收取滞纳金,闭馆日不办理。'
32
+ const LOAN_B = '图书馆借阅规则:每人每次最多借七本书,借期十四天,可以续借一次,逾期按天收取滞纳金,闭馆日不办理。'
33
+
34
+ test('numbers, dates, times, weekdays and quoted names are slot conflicts', () => {
35
+ const cases = [
36
+ [LOAN_A, LOAN_B],
37
+ ['复诊安排在2026-11-08上午十点。', '复诊安排在2026-11-15上午十点。'],
38
+ ['每周一上午九点开会。', '每周二上午九点开会。'],
39
+ ['他说“林眠”明天会来,而且会带伞。', '他说“Yuike”明天会来,而且会带伞。'],
40
+ ]
41
+ for (const [a, b] of cases) {
42
+ const detail = similarity.similarityDetail(a, b)
43
+ assert.equal(detail.slotConflict, true, a.slice(0, 18))
44
+ assert.ok(detail.dice >= similarity.TOPIC_DICE, 'fixture must be similar enough to inspect slots')
45
+ assert.ok(similarity.similarTexts(a, b) < similarity.TOPIC_DICE, 'slot conflict must fall below the topic band')
46
+ }
47
+ assert.deepEqual(similarity.slotSignature('借五本书,等十五天').numbers.sort(), ['15', '5'])
48
+ })
49
+
50
+ test('same slots and added numbers are not capped', () => {
51
+ assert.equal(similarity.similarityDetail(LOAN_A, LOAN_A).slotConflict, false)
52
+ const same = '图书馆借阅规则:每人每次最多借五本书,借期十四天。'
53
+ const added = '图书馆借阅规则:每人每次最多借五本书,借期十四天,押金二十元,每人限办一张卡。'
54
+ const detail = similarity.similarityDetail(same, added)
55
+ assert.equal(detail.slotConflict, false, 'an added number is an enrichment, not a contradiction')
56
+ assert.equal(similarity.similarTexts(same, added), Math.max(detail.dice, detail.containment))
57
+ // Totally unrelated text never pays for slot extraction and is not a conflict.
58
+ assert.equal(similarity.similarityDetail('窗外的雨停了。', '图书馆周三闭馆。').slotConflict, false)
59
+ })
60
+
61
+ test('different-title facts that only change a number both stay active', async () => {
62
+ const { exec, libraryId } = session('slot-write')
63
+ const first = await memory.privateRemember({ exec, title: '借阅上限', content: LOAN_A })
64
+ const raw = similarity.similarityDetail(LOAN_A, LOAN_B)
65
+ assert.ok(raw.dice >= similarity.DUP_REJECT_DICE, 'fixture must sit in the old reject band, got ' + raw.dice)
66
+ assert.equal(raw.slotConflict, true)
67
+ const second = await memory.privateRemember({ exec, title: '借阅额度', content: LOAN_B })
68
+ assert.equal(second.deduped, undefined)
69
+ assert.equal(second.entry.status, 'active')
70
+ assert.equal(second.entry.duplicateOf, undefined)
71
+ const index = state.loadPrivateIndex(libraryId)
72
+ assert.equal(Object.keys(index.entries).length, 2)
73
+ assert.equal(index.entries[first.id].status, 'active')
74
+ assert.equal(index.entries[second.id].content, LOAN_B)
75
+ })
76
+
77
+ test('same title + changed number is held as a conflict, not swallowed as duplicate', async () => {
78
+ const { exec, libraryId } = session('slot-same-title')
79
+ const first = await memory.privateRemember({ exec, title: '借阅上限', content: LOAN_A })
80
+ const second = await memory.privateRemember({ exec, title: '借阅上限', content: LOAN_B })
81
+ assert.equal(second.conflict, first.id, 'same-title slot correction must be a conflict')
82
+ const index = state.loadPrivateIndex(libraryId)
83
+ assert.equal(index.entries[second.id].status, 'pending_review')
84
+ assert.match(index.entries[second.id].reviewReason, /slot|说法|同题/)
85
+ assert.equal(index.entries[second.id].content, LOAN_B, 'the corrected text is preserved')
86
+ })
87
+
88
+ test('an update that only changes a number is not refused as a duplicate', async () => {
89
+ const { exec, libraryId } = session('slot-update')
90
+ const index = state.loadPrivateIndex(libraryId)
91
+ const now = new Date().toISOString()
92
+ index.entries['mem-host'] = {
93
+ title: '借阅上限', content: LOAN_A,
94
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
95
+ }
96
+ index.entries['mem-target'] = {
97
+ title: '借阅额度备注', content: '这条先占位,稍后改成正式规则。',
98
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
99
+ }
100
+ state.savePrivateIndex(libraryId, index)
101
+ const updated = await memory.privateUpdate({ exec, id: 'mem-target', content: LOAN_B })
102
+ assert.equal(updated.entry.content, LOAN_B)
103
+ assert.equal(updated.entry.status, 'active')
104
+ assert.equal(updated.entry.duplicateOf, undefined, 'a slot change is a different fact, not a duplicate')
105
+ })
106
+
107
+ test('recall keeps same-template different-number facts in separate seats', async () => {
108
+ const { exec, libraryId } = session('slot-recall')
109
+ const index = state.loadPrivateIndex(libraryId)
110
+ const now = new Date().toISOString()
111
+ index.entries['mem-five'] = {
112
+ title: '借阅上限五本', content: LOAN_A,
113
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
114
+ }
115
+ index.entries['mem-seven'] = {
116
+ title: '借阅上限七本', content: LOAN_B,
117
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
118
+ }
119
+ state.savePrivateIndex(libraryId, index)
120
+ const raw = similarity.similarityDetail(LOAN_A, LOAN_B)
121
+ assert.ok(raw.dice >= similarity.DUP_DICE, 'fixture must be in the old folding band')
122
+ const recalled = await memory.privateRecall({ exec, query: '图书馆借阅规则', topK: 10, relevanceThreshold: 0 })
123
+ const ids = recalled.files.map((file) => file.name)
124
+ assert.ok(ids.includes('mem-five') && ids.includes('mem-seven'), 'distinct facts must keep two seats')
125
+ assert.deepEqual(recalled.dedup?.collapsed || [], [], 'the pair must not be folded')
126
+ })
127
+
128
+ test('A-10: similarity thresholds have a single source; compat exports keep their values', () => {
129
+ assert.deepEqual(similarity.SIMILARITY_THRESHOLDS, {
130
+ duplicateDice: 0.82,
131
+ rejectDice: 0.90,
132
+ topicDice: 0.55,
133
+ lengthPruneRatio: 0.5,
134
+ containmentFloor: 0.92,
135
+ probeMinChars: 6,
136
+ probeMaxChars: 240,
137
+ })
138
+ assert.equal(similarity.DUP_DICE, similarity.SIMILARITY_THRESHOLDS.duplicateDice)
139
+ assert.equal(similarity.DUP_REJECT_DICE, similarity.SIMILARITY_THRESHOLDS.rejectDice)
140
+ assert.equal(similarity.TOPIC_DICE, similarity.SIMILARITY_THRESHOLDS.topicDice)
141
+ assert.equal(similarity.LENGTH_PRUNE_RATIO, similarity.SIMILARITY_THRESHOLDS.lengthPruneRatio)
142
+ assert.equal(similarity.CONTAINMENT_FLOOR, similarity.SIMILARITY_THRESHOLDS.containmentFloor)
143
+ assert.equal(similarity.CORE_COVER_FLOOR, similarity.SIMILARITY_THRESHOLDS.rejectDice)
144
+ for (const value of [similarity.DUP_DICE, similarity.DUP_REJECT_DICE, similarity.TOPIC_DICE, similarity.CONTAINMENT_FLOOR]) {
145
+ assert.equal(typeof value, 'number', 'compat exports stay plain numbers')
146
+ }
147
+ })
148
+
149
+ test('D-21: jaccard is exported from the shared ruler with the old formula', () => {
150
+ assert.equal(similarity.jaccard(new Set(), new Set(['a'])), 0)
151
+ assert.equal(similarity.jaccard(new Set(['a', 'b']), new Set(['b', 'c'])), 1 / 3)
152
+ assert.equal(similarity.jaccard(new Set(['a', 'b']), new Set(['a', 'b'])), 1)
153
+ })
@@ -0,0 +1,34 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-gc-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+
12
+ test.after(() => {
13
+ state.flushState()
14
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
15
+ })
16
+
17
+ test('session-binding GC is dry-run first and skips bindings without a clock', async () => {
18
+ state.ensureSession('gc-old', { cwd: path.join(home, 'old') })
19
+ state.setSessionBinding('gc-old', { lastTurnAt: '2020-01-01T00:00:00.000Z' })
20
+ state.ensureSession('gc-new', { cwd: path.join(home, 'new') })
21
+ state.setSessionBinding('gc-new', { lastTurnAt: new Date().toISOString() })
22
+ state.ensureSession('gc-noclock', { cwd: path.join(home, 'noclock') })
23
+
24
+ const dry = state.pruneSessionBindings({ olderThanDays: 30 })
25
+ assert.equal(dry.dryRun, true)
26
+ assert.deepEqual(dry.candidates.map((item) => item.sessionId), ['gc-old'])
27
+ assert.ok(state.getSessionBinding('gc-old'), 'dry-run must not remove')
28
+
29
+ const applied = state.pruneSessionBindings({ olderThanDays: 30, dryRun: false })
30
+ assert.deepEqual(applied.removed, ['gc-old'])
31
+ assert.equal(state.getSessionBinding('gc-old'), null)
32
+ assert.ok(state.getSessionBinding('gc-new'), 'a recent binding survives')
33
+ assert.ok(state.getSessionBinding('gc-noclock'), 'a binding without lastTurnAt is never guessed away')
34
+ })
@@ -56,8 +56,8 @@ test('the unpin marker is gone from session bindings', () => {
56
56
  assert.equal(typeof state.consumeTrauma, 'undefined')
57
57
  })
58
58
 
59
- test('backup creates a timestamped directory', () => {
60
- const dest = state.backupDatabases()
59
+ test('backup creates a timestamped directory', async () => {
60
+ const dest = await state.backupDatabases()
61
61
  assert.ok(fs.existsSync(dest))
62
62
  assert.ok(fs.existsSync(path.join(dest, 'index')))
63
63
  })
@@ -5,9 +5,9 @@ import {
5
5
  tokenize,
6
6
  tokenizeStats,
7
7
  tokenizeV2,
8
- TEST_CASES,
9
8
  tokenStreamV2,
10
9
  } from '../lib/tokenizer-v2.js'
10
+ import { TEST_CASES } from './fixtures/tokenizer-cases.mjs'
11
11
 
12
12
  // —— 召回升级 P0-1:Tokenizer V2(CJK 三层 n-gram + 实体保护)——
13
13
  // 开关在 lib/curator-policy.js(TOKENIZER_V2);这里测 V2 本身的行为契约。
@@ -0,0 +1,37 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { vectorGcCandidates } from '../lib/vector-profile.js'
5
+
6
+ const DAY = 86_400_000
7
+ const NOW = 1_800_000_000_000
8
+
9
+ test('vector GC keeps active/pending paths and the last N generations', () => {
10
+ const old = NOW - 40 * DAY
11
+ const files = [
12
+ { file: 'global.aaaa.g1.sqlite3', generation: 1, bytes: 10, mtimeMs: old },
13
+ { file: 'global.aaaa.g2.sqlite3', generation: 2, bytes: 10, mtimeMs: old },
14
+ { file: 'global.aaaa.g3.sqlite3', generation: 3, bytes: 10, mtimeMs: old },
15
+ { file: 'vector-ledger.aaaa.g1.json', generation: 1, bytes: 10, mtimeMs: old },
16
+ { file: 'legacy.sqlite3', generation: null, bytes: 10, mtimeMs: old },
17
+ ]
18
+ const candidates = vectorGcCandidates({
19
+ files, activeGeneration: 3, keepGenerations: 2, olderThanDays: 7, now: NOW,
20
+ })
21
+ assert.deepEqual(candidates.map((item) => item.file).sort(), [
22
+ 'global.aaaa.g1.sqlite3',
23
+ 'vector-ledger.aaaa.g1.json',
24
+ ])
25
+
26
+ const kept = vectorGcCandidates({
27
+ files, activeGeneration: 3, keepGenerations: 2, olderThanDays: 7, now: NOW,
28
+ keepPaths: ['global.aaaa.g1.sqlite3'],
29
+ })
30
+ assert.deepEqual(kept.map((item) => item.file), ['vector-ledger.aaaa.g1.json'])
31
+
32
+ const recent = vectorGcCandidates({
33
+ files: [{ file: 'global.aaaa.g1.sqlite3', generation: 1, bytes: 10, mtimeMs: NOW - DAY }],
34
+ activeGeneration: 3, keepGenerations: 2, olderThanDays: 7, now: NOW,
35
+ })
36
+ assert.deepEqual(recent, [], 'a recent old generation is left for the retention window')
37
+ })