dsh-memu-memory 1.2.8 → 1.3.0

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 (90) hide show
  1. package/CHANGELOG.md +494 -0
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/docs/memory-semantics.md +3 -2
  5. package/lib/backup.js +154 -25
  6. package/lib/binding-diagnostics.js +2 -3
  7. package/lib/budget.js +0 -9
  8. package/lib/client.js +221 -128
  9. package/lib/commitment.js +3 -3
  10. package/lib/consolidation-ledger.js +46 -3
  11. package/lib/consolidation-receipt.js +41 -16
  12. package/lib/consolidation-worker.js +34 -10
  13. package/lib/curator-policy.js +23 -0
  14. package/lib/cycle.js +8 -4
  15. package/lib/embedding-download.js +168 -28
  16. package/lib/embedding-runtime.js +76 -17
  17. package/lib/engine.js +0 -6
  18. package/lib/freshness.js +2 -2
  19. package/lib/graph.js +139 -11
  20. package/lib/index.js +71 -20
  21. package/lib/inject.js +50 -7
  22. package/lib/lexicon.js +61 -16
  23. package/lib/local-vector-service.js +21 -1
  24. package/lib/media.js +49 -12
  25. package/lib/memory.js +662 -116
  26. package/lib/paths.js +0 -7
  27. package/lib/preset-scope.js +6 -1
  28. package/lib/private.js +281 -18
  29. package/lib/prompts/private-consolidation.md +2 -2
  30. package/lib/prompts/private-consolidation.rp.md +3 -2
  31. package/lib/prompts.js +0 -7
  32. package/lib/rpc.js +95 -17
  33. package/lib/snippet.js +18 -2
  34. package/lib/state.js +109 -30
  35. package/lib/stats.js +2 -2
  36. package/lib/temporal.js +19 -0
  37. package/lib/text-retrieval.js +120 -44
  38. package/lib/text-similarity.js +205 -24
  39. package/lib/tokenizer-v2.js +0 -24
  40. package/lib/tools.js +62 -62
  41. package/lib/vector-migration.js +15 -0
  42. package/lib/vector-profile.js +81 -8
  43. package/lib/visibility.js +0 -4
  44. package/lib/webui/standalone.css +17 -22
  45. package/lib/webui/standalone.js +27 -9
  46. package/lib/webui.js +4 -4
  47. package/package.json +3 -2
  48. package/scripts/acceptance-local.mjs +2 -2
  49. package/scripts/check-all.mjs +3 -1
  50. package/scripts/check-i18n.mjs +35 -1
  51. package/scripts/migrate-visibility.mjs +3 -3
  52. package/scripts/prune-sessions.mjs +34 -0
  53. package/scripts/prune-vectors.mjs +24 -0
  54. package/tests/appendix-b.test.mjs +5 -4
  55. package/tests/audit-batch3.test.mjs +247 -0
  56. package/tests/audit-regression.test.mjs +2 -2
  57. package/tests/backup.test.mjs +83 -83
  58. package/tests/browser.test.mjs +6 -1
  59. package/tests/client-render.test.mjs +2 -2
  60. package/tests/consolidation-fork.test.mjs +61 -15
  61. package/tests/consolidation-ledger.test.mjs +64 -3
  62. package/tests/consolidation-snapshot.test.mjs +25 -9
  63. package/tests/curator-clusters.test.mjs +18 -0
  64. package/tests/curator-pairing.test.mjs +59 -16
  65. package/tests/dynamic-rrf.test.mjs +22 -19
  66. package/tests/dynamic-threshold.test.mjs +52 -0
  67. package/tests/fact-version.test.mjs +18 -0
  68. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  69. package/tests/graph-cascade.test.mjs +29 -0
  70. package/tests/graph.test.mjs +45 -0
  71. package/tests/inject-conflict.test.mjs +18 -0
  72. package/tests/injection-chain.test.mjs +2 -2
  73. package/tests/lexical-bm25.test.mjs +171 -0
  74. package/tests/lexicon-frequency.test.mjs +16 -0
  75. package/tests/lexicon-inject.test.mjs +21 -0
  76. package/tests/lexicon-perf.test.mjs +37 -9
  77. package/tests/lexicon-scope.test.mjs +2 -2
  78. package/tests/lexicon-ui.test.mjs +1 -1
  79. package/tests/managed-memory.test.mjs +19 -0
  80. package/tests/ops-hardening.test.mjs +209 -0
  81. package/tests/package-shipping.test.mjs +4 -0
  82. package/tests/prompt-semantics.test.mjs +1 -1
  83. package/tests/prompts.test.mjs +1 -1
  84. package/tests/recall-intent.test.mjs +23 -0
  85. package/tests/slot-similarity.test.mjs +153 -0
  86. package/tests/state-gc.test.mjs +34 -0
  87. package/tests/state.test.mjs +2 -2
  88. package/tests/tokenizer-v2.test.mjs +1 -1
  89. package/tests/vector-gc.test.mjs +37 -0
  90. package/tests/webui.test.mjs +27 -0
package/lib/lexicon.js CHANGED
@@ -689,9 +689,20 @@ function clamp01(value) {
689
689
  }
690
690
 
691
691
  /**
692
- * Wilson 下界(§6.3 包 C 的有界频率先验):hitCounts 三计数(candidate/injection/
693
- * query)→ 95% Wilson 置信下界。n=candidate 是分母(候选池大小),成功 =
694
- * injection+query(真的注入了 / 被显式查过),恒 ≤ n。设计约束:
692
+ * Wilson 下界(§6.3 包 C 的有界频率先验,A-13:同源分子/分母)。
693
+ *
694
+ * 分母 n 优先取 priorAttempts——「该词条被召回的总尝试次数」这一同源计数;
695
+ * 成功数 success = injection + query,即「被召回后确实被注入/查询命中」的
696
+ * 同源事件。旧实现把 candidate(候选池大小,另一条计数通道)当分母,再把
697
+ * injection+query clamp 到它,两个不相干的计数被硬凑成一个比例,口径不严谨
698
+ * (虽然有界、不会 runaway)。
699
+ *
700
+ * 兼容近似:当前写入路径还没有记录 priorAttempts,缺失(或非正数)时退回
701
+ * candidate 作为分母,并在此文档化这一假设——candidate 是「进过匹配结果」的
702
+ * 次数,是现有数据里与「被召回」最接近的代理;success 仍被 min(n, ...) 钳住,
703
+ * 公式保持有界。写入侧按同源事件补上 priorAttempts 后,先验自动切换到严格口径。
704
+ *
705
+ * 设计约束不变:
695
706
  * * n=0 → 0(从未候选过的词条没有任何频率证据,因子取下限 0.85)。
696
707
  * * 1/1 的下界 ≈ 0.207,因子最多 ~3% 差距——一条偶发命中压不过长期稳定使用的词。
697
708
  * * 100/120 的下界明显更高——长期被真正使用的词条温和提升。
@@ -699,7 +710,8 @@ function clamp01(value) {
699
710
  * (0.85 + 0.15 * lb) 后 effective 因子恒在 [0.85,1.00],不 runaway。
700
711
  */
701
712
  export function usageLowerBound(counts) {
702
- const n = Math.max(0, Math.floor(Number(counts?.candidate) || 0))
713
+ const attempts = Math.max(0, Math.floor(Number(counts?.priorAttempts) || 0))
714
+ const n = attempts > 0 ? attempts : Math.max(0, Math.floor(Number(counts?.candidate) || 0))
703
715
  if (n === 0) return 0
704
716
  const success = Math.min(n, Math.max(0, (Number(counts?.injection) || 0) + (Number(counts?.query) || 0)))
705
717
  const p = success / n
@@ -761,8 +773,17 @@ function scopeSpecificity(context) {
761
773
  return ['channelId', 'speakerId', 'characterId', 'worldId', 'branchId'].filter(key => context[key]).length
762
774
  }
763
775
 
764
- /** 文本侧:穷举 BUCKET_WIDTH 字符窗口,按出现顺序去重,上限 MAX_BUCKETS。 */
765
- function textBuckets(normalizedText, maxBuckets = LEXICON_MAX_BUCKETS) {
776
+ /**
777
+ * 文本侧窗口(A-8):穷举 BUCKET_WIDTH 字符窗口并去重,按「该窗口在前缀桶里
778
+ * 命中的词条数」降序取 top-N。旧实现按出现顺序取前 16 个窗口:长文本里真正
779
+ * 含错字变体的窗口(例如 40 字闲聊末尾的「糖刀文雪」)常常落在第 17 个之后,
780
+ * 模糊层连候选都收不到——召不回不是因为 Dice 不够,而是窗口根本没被展开。
781
+ * 命中数相同的窗口保持出现顺序(sort 稳定),输出可复现。
782
+ *
783
+ * 命中数取索引里该桶的全量大小(含 archived/pending):窗口排序只是「哪些窗口
784
+ * 值得展开」的成本决策,可见性仍由逐候选的 isVisible 复核,不会被这里放宽。
785
+ */
786
+ function textBuckets(normalizedText, index, maxBuckets = LEXICON_MAX_BUCKETS) {
766
787
  const keys = []
767
788
  const seen = new Set()
768
789
  for (let i = 0; i + BUCKET_WIDTH <= normalizedText.length; i++) {
@@ -770,9 +791,12 @@ function textBuckets(normalizedText, maxBuckets = LEXICON_MAX_BUCKETS) {
770
791
  if (seen.has(key)) continue
771
792
  seen.add(key)
772
793
  keys.push(key)
773
- if (keys.length >= maxBuckets) break
774
794
  }
775
795
  return keys
796
+ .map((key, order) => ({ key, order, hits: index?.prefixBuckets?.get(key)?.size || 0 }))
797
+ .sort((a, b) => b.hits - a.hits || a.order - b.order)
798
+ .slice(0, maxBuckets)
799
+ .map((item) => item.key)
776
800
  }
777
801
 
778
802
  /**
@@ -836,7 +860,9 @@ function hitOf(entry, termId, kindOfHit, score) {
836
860
  * 全部走 revision-keyed 索引(§10 P1):等值 O(1) 查 Map;包含层用「词面 ⊆ 文本
837
861
  * ⇒ 词面前缀 = 文本某个 2 字窗口」的性质从前缀桶收候选(窗口穷举不设 16 上限——
838
862
  * 16 上限只属于 dice 候选,精确层语义从来没有窗口上限);dice 兜底仍按桶扫且
839
- * C ≤ 64 不变(§6)。可见性(status + contextVisible)在收候选时逐个复核。
863
+ * C ≤ 64 不变(§6),但窗口按命中词条数排序、候选按与 query 的共享 gram 数
864
+ * 排序(A-8:候选准入看相关性,不看 strength)。可见性(status +
865
+ * contextVisible)在收候选时逐个复核。
840
866
  */
841
867
  export function matchLexiconHits(libraryId, userText, memoryContext) {
842
868
  const normalizedText = normalizeLexeme(userText)
@@ -878,17 +904,36 @@ export function matchLexiconHits(libraryId, userText, memoryContext) {
878
904
  hits.push(hitOf(entry, termId, matched.via === 'term' ? 'exact-term' : 'exact-alias', 1))
879
905
  }
880
906
  }
881
- // dice 候选:仍按 textBuckets 的 16 窗口上限收(§4.2 的 C≤64 语义不变)。
882
- const candidateIds = []
883
- for (const key of textBuckets(normalizedText)) {
907
+ // dice 候选:窗口数仍以 LEXICON_MAX_BUCKETS 封顶(§4.2 的 C≤64 语义不变),
908
+ // 但窗口与候选都按「与 query 的相关性」排:窗口按命中词条数降序(见
909
+ // textBuckets),候选按与 query 共享的 gram 数降序。旧实现把候选按
910
+ // strength×confidence 取前 64——候选池被一批不一定相关的强词条占满,真正
911
+ // 只差一个字的弱词条反而进不了 diceFallback。strength 与 termId 只做确定性
912
+ // tiebreak(与 diceFallback 的末位排序同口径)。
913
+ const candidateIds = new Set()
914
+ for (const key of textBuckets(normalizedText, index)) {
884
915
  for (const termId of index.prefixBuckets.get(key) || []) {
885
- if (exactIds.has(termId) || candidateIds.includes(termId) || !isVisible(termId)) continue
886
- candidateIds.push(termId)
916
+ if (exactIds.has(termId) || !isVisible(termId)) continue
917
+ candidateIds.add(termId)
887
918
  }
888
919
  }
889
- const candidates = candidateIds
890
- .map(termId => hitOf(data.terms[termId], termId, 'dice', 0))
891
- .sort((a, b) => (Number(b.strength) || 0) * (Number(b.confidence) || 0) - (Number(a.strength) || 0) * (Number(a.confidence) || 0))
920
+ const textGrams = bigrams(normalizedText)
921
+ const sharedGramCount = termId => {
922
+ let best = 0
923
+ for (const { surface } of index.surfacesByTerm.get(termId) || []) {
924
+ let shared = 0
925
+ for (const gram of bigrams(surface)) if (textGrams.has(gram)) shared += 1
926
+ if (shared > best) best = shared
927
+ }
928
+ return best
929
+ }
930
+ const weightOf = termId => (Number(data.terms[termId].strength) || 0) * (Number(data.terms[termId].confidence) || 0)
931
+ const candidates = [...candidateIds]
932
+ .map(termId => ({ termId, shared: sharedGramCount(termId) }))
933
+ .sort((a, b) => b.shared - a.shared
934
+ || weightOf(b.termId) - weightOf(a.termId)
935
+ || String(a.termId).localeCompare(String(b.termId)))
936
+ .map(({ termId }) => hitOf(data.terms[termId], termId, 'dice', 0))
892
937
  const fuzzy = diceFallback(normalizedText, candidates)
893
938
  // stableRank 的末位 tie-break 是唯一 termId,命中顺序不影响最终排序。
894
939
  return stableRank([...hits, ...fuzzy])
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import { downloadsDir, warn } from './paths.js'
4
- import { listLibraries, loadPrivateIndex, loadGlobalIndex } from './state.js'
4
+ import { listLibraries, loadPrivateIndex, loadGlobalIndex, saveGlobalIndex, updatePrivateIndex } from './state.js'
5
5
  import { commit as memuCommit, listFiles as memuListFiles, forget as memuForget } from './memu.js'
6
6
  import { getEmbeddingCatalog, prefixesRequireRole, resolveEmbeddingSources } from './embedding-catalog.js'
7
7
  import { createEmbeddingDownloadManager } from './embedding-download.js'
@@ -217,6 +217,26 @@ function migratorFor() {
217
217
  assertProfileVerified(profile)
218
218
  return memuListFiles({ db, vectorProfile: profile, route: 'managed-local' })
219
219
  },
220
+ clearVectorPending: ({ libraryId, ids }) => {
221
+ const wanted = new Set((Array.isArray(ids) ? ids : []).map(String).filter(Boolean))
222
+ if (!wanted.size) return
223
+ const clear = (index) => {
224
+ let touched = 0
225
+ for (const id of wanted) {
226
+ const entry = index.entries?.[id]
227
+ if (entry && entry.vectorPending) { delete entry.vectorPending; touched += 1 }
228
+ }
229
+ return touched
230
+ }
231
+ // The global layer is its own index file; a private library has one each. Nothing
232
+ // crosses between them, so the scope decides which write path to take.
233
+ if (libraryId == null) {
234
+ const index = loadGlobalIndex()
235
+ if (clear(index)) saveGlobalIndex(index)
236
+ return
237
+ }
238
+ updatePrivateIndex(libraryId, (index) => { clear(index) })
239
+ },
220
240
  })
221
241
  }
222
242
 
package/lib/media.js CHANGED
@@ -18,6 +18,25 @@ const MIME_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp'
18
18
  const SHA = /^[a-f0-9]{64}$/
19
19
  const captures = new Map()
20
20
  let activeCaptions = 0
21
+ // A v2 bundle is always written with a SHA-256 of memories.json. Legacy v1
22
+ // archives predate that field, so they stay importable without it; a v2
23
+ // manifest with the field removed (or malformed) must be rejected instead of
24
+ // silently trusting an edited body. This is an integrity check against
25
+ // truncation/accidental edits, NOT a signature: a caller able to rewrite the
26
+ // whole manifest can also downgrade `format` to a legacy name, which is an
27
+ // explicit compatibility opt-in rather than a checksum bypass.
28
+ const MEDIA_FORMAT = 'dsh-memu-memory-media@2'
29
+ const LEGACY_MEDIA_FORMATS = ['dsh-memu-memory-media@1', 'dsh-memu-media@1']
30
+ function verifyBundleChecksum(manifest, memories) {
31
+ const digest = manifest.memoriesSha256
32
+ if (!digest) {
33
+ if (!LEGACY_MEDIA_FORMATS.includes(manifest.format)) throw new Error('memories.json checksum missing')
34
+ return
35
+ }
36
+ if (typeof digest !== 'string' || !SHA.test(digest)) throw new Error('memories.json checksum is malformed')
37
+ const actual = crypto.createHash('sha256').update(memories).digest('hex')
38
+ if (actual !== digest) throw new Error('memories.json checksum mismatch')
39
+ }
21
40
  function poolFile(libraryId) {
22
41
  if (!isSafeId(libraryId)) throw new Error('invalid library id')
23
42
  return path.join(indexDir(), `${libraryId}.media.json`)
@@ -291,7 +310,7 @@ export async function captionImage(libraryId, sha256) {
291
310
  export function exportMediaBundle(libraryId, payload) {
292
311
  const pool = loadPool(libraryId)
293
312
  const files = {}
294
- const manifest = { format: 'dsh-memu-memory-media@1', blobs: {} }
313
+ const manifest = { format: MEDIA_FORMAT, blobs: {} }
295
314
  const wanted = new Set(payload.memories.flatMap(entry => (entry.attachments || []).map(item => item.sha256)))
296
315
  for (const sha of wanted) {
297
316
  const blob = pool.blobs[sha]
@@ -304,7 +323,10 @@ export function exportMediaBundle(libraryId, payload) {
304
323
  files[name] = data
305
324
  manifest.blobs[sha] = { ...blob, file: name }
306
325
  }
307
- files['memories.json'] = Buffer.from(JSON.stringify(payload))
326
+ const memoriesBuffer = Buffer.from(JSON.stringify(payload))
327
+ manifest.bundleId = payload?.bundleId || null
328
+ manifest.memoriesSha256 = crypto.createHash('sha256').update(memoriesBuffer).digest('hex')
329
+ files['memories.json'] = memoriesBuffer
308
330
  files['manifest.json'] = Buffer.from(JSON.stringify(manifest))
309
331
  return Buffer.from(zipSync(files, { level: 0 }))
310
332
  }
@@ -318,9 +340,15 @@ export function importMediaBundle(libraryId, archive) {
318
340
  if (file.name !== 'memories.json' && file.name !== 'manifest.json' && !/^attachments\/[a-f0-9]{64}\.(png|jpg|gif|webp)$/.test(file.name)) throw new Error('archive contains an unsupported path')
319
341
  return true
320
342
  } })
321
- const manifest = JSON.parse(Buffer.from(files['manifest.json'] || []).toString('utf8'))
322
- const payload = JSON.parse(Buffer.from(files['memories.json'] || []).toString('utf8'))
323
- if (!['dsh-memu-memory-media@1', 'dsh-memu-media@1'].includes(manifest.format) || !Array.isArray(payload.memories)) throw new Error('invalid memory archive')
343
+ let manifest, payload
344
+ try {
345
+ manifest = JSON.parse(Buffer.from(files['manifest.json'] || []).toString('utf8'))
346
+ payload = JSON.parse(Buffer.from(files['memories.json'] || []).toString('utf8'))
347
+ } catch {
348
+ throw new Error('invalid memory archive')
349
+ }
350
+ if (![MEDIA_FORMAT, ...LEGACY_MEDIA_FORMATS].includes(manifest.format) || !Array.isArray(payload.memories)) throw new Error('invalid memory archive')
351
+ verifyBundleChecksum(manifest, files['memories.json'])
324
352
  let missing = 0
325
353
  withFileLock(poolFile(libraryId), () => {
326
354
  const pool = loadPool(libraryId)
@@ -341,7 +369,7 @@ export function importMediaBundle(libraryId, archive) {
341
369
  }
342
370
  savePool(libraryId, pool)
343
371
  })
344
- return { memories: payload.memories, graph: payload.graph || null, missing }
372
+ return { memories: payload.memories, graph: payload.graph || null, missing, bundleId: payload.bundleId || manifest.bundleId || null }
345
373
  }
346
374
 
347
375
  /** Stream the original images; never materialize a 500 MB library as base64. */
@@ -353,7 +381,10 @@ export async function streamMediaExport(libraryId, payload, response) {
353
381
  if (chunk.length) response.write(chunk)
354
382
  if (final) response.end()
355
383
  })
356
- const manifest = { format: 'dsh-memu-memory-media@1', blobs: {} }
384
+ const manifest = { format: MEDIA_FORMAT, blobs: {} }
385
+ const memoriesBuffer = Buffer.from(JSON.stringify(payload))
386
+ manifest.bundleId = payload.bundleId || null
387
+ manifest.memoriesSha256 = crypto.createHash('sha256').update(memoriesBuffer).digest('hex')
357
388
  const push = async (name, source) => {
358
389
  const entry = new ZipPassThrough(name)
359
390
  zip.add(entry)
@@ -381,7 +412,7 @@ export async function streamMediaExport(libraryId, payload, response) {
381
412
  await push(name, fs.createReadStream(file, { highWaterMark: 64 * 1024 }))
382
413
  manifest.blobs[sha] = { ...blob, file: name }
383
414
  }
384
- await push('memories.json', [Buffer.from(JSON.stringify(payload))])
415
+ await push('memories.json', [memoriesBuffer])
385
416
  await push('manifest.json', [Buffer.from(JSON.stringify(manifest))])
386
417
  zip.end()
387
418
  } catch (error) {
@@ -430,9 +461,15 @@ export async function importMediaStream(libraryId, request) {
430
461
  unzip.push(new Uint8Array(), true)
431
462
  if (failure) throw failure
432
463
  if ([...files.values()].some(item => !item.complete) || !files.has('manifest.json') || !files.has('memories.json')) throw new Error('incomplete memory archive')
433
- const payload = JSON.parse(fs.readFileSync(files.get('memories.json').file, 'utf8'))
434
- const manifest = JSON.parse(fs.readFileSync(files.get('manifest.json').file, 'utf8'))
435
- if (!['dsh-memu-memory-media@1', 'dsh-memu-media@1'].includes(manifest.format) || !Array.isArray(payload.memories)) throw new Error('invalid memory archive')
464
+ let payload, manifest
465
+ try {
466
+ payload = JSON.parse(fs.readFileSync(files.get('memories.json').file, 'utf8'))
467
+ manifest = JSON.parse(fs.readFileSync(files.get('manifest.json').file, 'utf8'))
468
+ } catch {
469
+ throw new Error('invalid memory archive')
470
+ }
471
+ if (![MEDIA_FORMAT, ...LEGACY_MEDIA_FORMATS].includes(manifest.format) || !Array.isArray(payload.memories)) throw new Error('invalid memory archive')
472
+ verifyBundleChecksum(manifest, fs.readFileSync(files.get('memories.json').file))
436
473
  let missing = 0
437
474
  withFileLock(poolFile(libraryId), () => {
438
475
  const pool = loadPool(libraryId)
@@ -460,7 +497,7 @@ export async function importMediaStream(libraryId, request) {
460
497
  throw error
461
498
  }
462
499
  })
463
- return { memories: payload.memories, graph: payload.graph, missing }
500
+ return { memories: payload.memories, graph: payload.graph, missing, bundleId: payload.bundleId || manifest.bundleId || null }
464
501
  } finally {
465
502
  for (const fd of descriptors) { try { fs.closeSync(fd) } catch {} }
466
503
  if (!path.resolve(staging).startsWith(path.resolve(dataDir(), 'tmp') + path.sep)) throw new Error('invalid archive staging directory')