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
@@ -114,6 +114,51 @@ test('relationship snapshots preserve unknowns, evidence, boundaries and previou
114
114
  assert.throws(() => graph.updateRelationship({ libraryId, fromId: a.id, toId: b.id, state: {}, evidenceIds: [], reason: 'no evidence' }), /evidence/)
115
115
  })
116
116
 
117
+ test('relationship history is capped while the current snapshot and evidence stay', () => {
118
+ const a = graph.createEntity({ libraryId, name: 'History A' })
119
+ const b = graph.createEntity({ libraryId, name: 'History B' })
120
+ for (let i = 0; i < 55; i += 1) {
121
+ graph.updateRelationship({
122
+ libraryId, fromId: a.id, toId: b.id,
123
+ state: { trust: 0.5, callbacks: [`callback ${i}`] },
124
+ evidenceIds: ['mem-2'], reason: `Evidence-backed revision ${i} is explicit.`,
125
+ })
126
+ }
127
+ const relation = graph.getRelationship({ libraryId, fromId: a.id, toId: b.id }).relationship
128
+ assert.equal(relation.history.length, 50, 'old revisions are capped')
129
+ assert.equal(relation.revision, 55)
130
+ assert.deepEqual(relation.state.callbacks, ['callback 54'])
131
+ assert.deepEqual(relation.evidenceIds, ['mem-2'])
132
+ })
133
+
134
+ test('relationship retention is a pure wall-clock decay with access reinforcement', () => {
135
+ assert.equal(graph.relationshipRetentionAt(1, 24), 0.5)
136
+ assert.equal(graph.relationshipRetentionAt(1, 48), 0.25)
137
+ assert.equal(graph.relationshipRetentionAt(1, -5), 1, 'clock rollback never boosts retention')
138
+ const accessed = graph.accessRelationship(0.5, { now: 10_000_000, lastAccessAt: null })
139
+ assert.ok(accessed > 0.5 && accessed < 1)
140
+ assert.equal(graph.accessRelationship(0.5, { now: 10_000_000, lastAccessAt: new Date(10_000_000 - 1000).toISOString() }), 0.5, 'cooldown blocks a second bump')
141
+ })
142
+
143
+ test('relationship snapshots persist retention, last access and next review', () => {
144
+ const a = graph.createEntity({ libraryId, name: 'Lifecycle A' })
145
+ const b = graph.createEntity({ libraryId, name: 'Lifecycle B' })
146
+ const created = graph.updateRelationship({
147
+ libraryId, fromId: a.id, toId: b.id,
148
+ state: { trust: 0.6 }, evidenceIds: ['mem-2'], reason: 'First explicit evidence for this relation.',
149
+ }).relationship
150
+ assert.equal(created.retention_strength, 1)
151
+ assert.ok(created.last_access_at)
152
+ assert.ok(created.next_review_at)
153
+ const next = graph.updateRelationship({
154
+ libraryId, fromId: a.id, toId: b.id,
155
+ state: { trust: 0.7 }, evidenceIds: ['mem-2'], reason: 'Second explicit evidence for this relation.',
156
+ }).relationship
157
+ assert.ok(next.retention_strength > 0 && next.retention_strength <= 1)
158
+ assert.ok(next.last_access_at >= created.last_access_at)
159
+ assert.equal(next.history[0].retention_strength, 1)
160
+ })
161
+
117
162
  test('a dangling edge is reported as missing, matching the graph view placeholder', () => {
118
163
  // mem-1 was deleted from the index in an earlier test; its inbound edge from
119
164
  // mem-0 remains. getGraph renders a [deleted] placeholder for it, so recall
@@ -71,6 +71,24 @@ test('the card text stays under 200 characters even with long titles', () => {
71
71
  assert.equal(conflictCard({ left: null, right: null }), '')
72
72
  })
73
73
 
74
+ test('the card orders sides by local authority and observed time', () => {
75
+ const card = conflictCard({
76
+ factKey: 'home:living_floor_color',
77
+ left: { id: 'mem-inferred', entry: { title: '木色', source_kind: 'inferred' } },
78
+ right: { id: 'mem-user', entry: { title: '灰色', source_kind: 'user_said' } },
79
+ })
80
+ assert.match(card, /- A \[mem-user\]/, 'a direct quote is shown first')
81
+ assert.match(card, /- B \[mem-inferred\]/)
82
+ assert.ok(card.length <= 200)
83
+
84
+ const newer = conflictCard({
85
+ factKey: 'x',
86
+ left: { id: 'mem-old', entry: { title: '旧', fact_authority: 1, observed_at: '2026-11-01' } },
87
+ right: { id: 'mem-new', entry: { title: '新', fact_authority: 1, observed_at: '2026-11-05' } },
88
+ })
89
+ assert.match(newer, /- A \[mem-new\]/, 'equal authority falls back to the newer observation')
90
+ })
91
+
74
92
  test('a conflict card that cannot fit falls back to the ordinary title cards', async () => {
75
93
  const { exec, sessionId } = session('conflict-budget')
76
94
  const longTitle = '非常长的旅行目的地描述'.repeat(8)
@@ -187,8 +187,8 @@ test('every consolidation prompt tells the model how to write the field', () =>
187
187
 
188
188
  test('the remember tool tells the model to resolve a relative day', () => {
189
189
  const source = fs.readFileSync(fileURLToPath(new URL('../lib/tools.js', import.meta.url)), 'utf8')
190
- assert.ok(source.includes('A relative day'), 'the tool description must mention relative days')
191
- assert.ok(source.includes('turns one appointment into a yearly reminder'), 'and why it matters')
190
+ assert.ok(source.includes('Resolve 今天/明天/下周 to the absolute date'), 'the tool description must mention relative days')
191
+ assert.ok(source.includes('never send a bare MM-DD for a one-off'), 'and why it matters')
192
192
  })
193
193
 
194
194
  // ------------------------------------- D: freshness hint is conditional and bounded
@@ -0,0 +1,171 @@
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-bm25-'))
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
+
13
+ test.after(() => {
14
+ delete process.env.DSH_MEMU_RECALL_LEXICAL
15
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
16
+ })
17
+
18
+ function fixture() {
19
+ const sessionId = 'bm25-session'
20
+ const cwd = path.join(home, 'ws-bm25')
21
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
22
+ const binding = state.getSessionBinding(sessionId)
23
+ const index = state.loadPrivateIndex(binding.libraryId)
24
+ const now = new Date().toISOString()
25
+ // "版本" is common across the corpus; "灰度" exists only in the target. The
26
+ // legacy includes scorer weights the title of every decoy above the target's body.
27
+ for (let i = 1; i <= 20; i += 1) {
28
+ index.entries[`mem-decoy${i}`] = {
29
+ title: `版本记录 ${i}`,
30
+ content: `这是第 ${i} 次版本记录,只记录版本号和变更人,没有别的说明。`,
31
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
32
+ }
33
+ }
34
+ index.entries['mem-target'] = {
35
+ title: '发布说明',
36
+ content: '本次版本更新包含灰度发布,灰度只允许在变更窗口内执行。',
37
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
38
+ }
39
+ state.savePrivateIndex(binding.libraryId, index)
40
+ return {
41
+ sessionId,
42
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } },
43
+ }
44
+ }
45
+
46
+ async function recall(exec, mode) {
47
+ if (mode === 'includes') process.env.DSH_MEMU_RECALL_LEXICAL = 'includes'
48
+ else delete process.env.DSH_MEMU_RECALL_LEXICAL
49
+ return memory.privateRecall({ exec, query: '版本 灰度', topK: 5, relevanceThreshold: 0 })
50
+ }
51
+
52
+ function rankOf(result, id) {
53
+ const index = result.files.findIndex((file) => file.name === id)
54
+ return index < 0 ? Infinity : index + 1
55
+ }
56
+
57
+ test('BM25 ranks the rare-term target first where includes-count does not', async () => {
58
+ const { exec } = fixture()
59
+ const legacy = await recall(exec, 'includes')
60
+ const bm25 = await recall(exec, 'bm25')
61
+
62
+ const legacyRank = rankOf(legacy, 'mem-target')
63
+ const bm25Rank = rankOf(bm25, 'mem-target')
64
+ assert.equal(bm25Rank, 1, 'BM25 must put the only 灰度 memory first')
65
+ assert.ok(legacyRank > 5, `includes-count must miss Recall@5, got rank ${legacyRank}`)
66
+ assert.ok(1 / bm25Rank > 1 / legacyRank, 'MRR must improve')
67
+
68
+ const target = bm25.files[0]
69
+ // A-2:query 里的「版本」出现在全部 21 条记忆里(df=N),按 df 闸门整条不参与
70
+ // 打分,decoys 因此拿不到任何 lexical 分数、进不了候选池。旧实现会给每个
71
+ // decoy 一个极小的正分,把全库一起拉进来——这正是要修的行为。
72
+ const decoy = bm25.files.find((file) => file.name.startsWith('mem-decoy'))
73
+ assert.equal(decoy, undefined, 'the corpus-wide term must no longer pull every decoy into the pool')
74
+ assert.ok(target.lexical > 0, 'the rare term still scores the target')
75
+ })
76
+
77
+ test('the lexical corpus cache is invalidated by a write', async () => {
78
+ const { exec } = fixture()
79
+ await recall(exec, 'bm25')
80
+ const written = await memory.privateRemember({
81
+ exec, title: '新的灰度记录',
82
+ content: '灰度发布新增了一条回滚检查,必须在变更窗口内完成。',
83
+ })
84
+ const after = await memory.privateRecall({ exec, query: '灰度', topK: 10, relevanceThreshold: 0 })
85
+ assert.ok(after.files.some((file) => file.name === written.id), 'a write must invalidate the cached corpus')
86
+ })
87
+
88
+ test('BM25 improves MRR and Recall@5 across eight rare-term queries', async () => {
89
+ const sessionId = 'bm25-multi'
90
+ const cwd = path.join(home, 'ws-bm25-multi')
91
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
92
+ const binding = state.getSessionBinding(sessionId)
93
+ const index = state.loadPrivateIndex(binding.libraryId)
94
+ const now = new Date().toISOString()
95
+ const rares = ['灰度', '熔断', '幂等', '分片', '回填', '限流', '审计', '快照']
96
+ const common = ['版本', '发布', '接口', '缓存', '部署', '回滚', '日志', '监控']
97
+ for (let group = 0; group < 8; group += 1) {
98
+ index.entries[`mem-target-${group}`] = {
99
+ title: `发布说明 ${group}`,
100
+ content: `本次${common[group]}更新包含${rares[group]}策略,${rares[group]}只允许在变更窗口内执行。`,
101
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
102
+ }
103
+ for (let i = 0; i < 20; i += 1) {
104
+ index.entries[`mem-decoy-${group}-${i}`] = {
105
+ title: `${common[group]}记录 ${group}-${i}`,
106
+ content: `这是第 ${i} 次${common[group]}记录,只记录${common[group]}号和变更人,没有别的说明。`,
107
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
108
+ }
109
+ }
110
+ }
111
+ state.savePrivateIndex(binding.libraryId, index)
112
+ const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } }
113
+
114
+ async function measure(mode) {
115
+ if (mode === 'includes') process.env.DSH_MEMU_RECALL_LEXICAL = 'includes'
116
+ else delete process.env.DSH_MEMU_RECALL_LEXICAL
117
+ let mrr = 0
118
+ let recall = 0
119
+ for (let group = 0; group < 8; group += 1) {
120
+ const result = await memory.privateRecall({
121
+ exec, query: `${common[group]} ${rares[group]}`, topK: 5, relevanceThreshold: 0,
122
+ })
123
+ const rank = result.files.findIndex((file) => file.name === `mem-target-${group}`) + 1
124
+ if (rank > 0) {
125
+ mrr += 1 / rank
126
+ if (rank <= 5) recall += 1
127
+ }
128
+ }
129
+ return { mrr: mrr / 8, recall5: recall }
130
+ }
131
+
132
+ const legacy = await measure('includes')
133
+ const bm25 = await measure('bm25')
134
+ delete process.env.DSH_MEMU_RECALL_LEXICAL
135
+ assert.ok(bm25.mrr > legacy.mrr, `MRR must improve: ${legacy.mrr} -> ${bm25.mrr}`)
136
+ assert.ok(bm25.recall5 > legacy.recall5, `Recall@5 must improve: ${legacy.recall5}/8 -> ${bm25.recall5}/8`)
137
+ assert.equal(bm25.recall5, 8, 'every rare-term target must enter the top five')
138
+ })
139
+
140
+ test('the includes fallback remains byte-for-byte available', async () => {
141
+ const { exec } = fixture()
142
+ const result = await recall(exec, 'includes')
143
+ assert.ok(result.files.length > 0)
144
+ assert.ok(result.files.every((file) => Number.isFinite(file.lexical)))
145
+ delete process.env.DSH_MEMU_RECALL_LEXICAL
146
+ })
147
+
148
+ test('tags and attachment captions still participate in the BM25 corpus', async () => {
149
+ const sessionId = 'bm25-fields'
150
+ const cwd = path.join(home, 'ws-bm25-fields')
151
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
152
+ const binding = state.getSessionBinding(sessionId)
153
+ const index = state.loadPrivateIndex(binding.libraryId)
154
+ const now = new Date().toISOString()
155
+ index.entries['mem-tagged'] = {
156
+ title: '一条普通记录', content: '正文里没有检索词。', tags: ['灰度', '发布'],
157
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
158
+ }
159
+ index.entries['mem-captioned'] = {
160
+ title: '另一条记录', content: '正文也很干净。',
161
+ attachments: [{ sha256: 'a'.repeat(64), caption: '灰度截图' }],
162
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
163
+ }
164
+ state.savePrivateIndex(binding.libraryId, index)
165
+ const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } }
166
+ delete process.env.DSH_MEMU_RECALL_LEXICAL
167
+ const tagged = await memory.privateRecall({ exec, query: '灰度', topK: 5, relevanceThreshold: 0 })
168
+ const ids = tagged.files.map((file) => file.name)
169
+ assert.ok(ids.includes('mem-tagged'), 'a query term in tags must still match')
170
+ assert.ok(ids.includes('mem-captioned'), 'a query term in an attachment caption must still match')
171
+ })
@@ -67,6 +67,22 @@ test('usageLowerBound: n=0 is 0, success is clamped to n, output stays in [0,1]'
67
67
  assert.ok(Math.abs(single - 0.207) < 0.01, `1/1 lower bound should be ~0.207, got ${single}`)
68
68
  })
69
69
 
70
+ test('usageLowerBound: priorAttempts is the same-source denominator; overflow stays bounded and monotone', () => {
71
+ const probe = (priorAttempts, injection, query = 0) => lexicon.usageLowerBound({ candidate: 100, priorAttempts, injection, query })
72
+ // 同源分母:固定 priorAttempts,同源成功数越多,下界单调不减。
73
+ const steps = [0, 1, 2, 3, 5].map(success => probe(5, success))
74
+ for (let i = 1; i < steps.length; i += 1) {
75
+ assert.ok(steps[i] >= steps[i - 1], `success ${i} must not lower the bound: ${steps[i - 1]} -> ${steps[i]}`)
76
+ }
77
+ // 分子超过分母:仍被 clamp 到 n,结果有界且等于 p=1 的下界(不会 >1)。
78
+ const overflow = probe(5, 50)
79
+ const full = probe(5, 5)
80
+ assert.equal(overflow, full)
81
+ assert.ok(overflow > 0 && overflow <= 1)
82
+ // 缺失 priorAttempts 时退回 candidate 分母:与旧近似的数值一致(文档化假设)。
83
+ assert.equal(lexicon.usageLowerBound({ candidate: 5, injection: 5 }), full)
84
+ })
85
+
70
86
  test('usageLowerBound: 10/9 ranks above 10/1 — a high miss rate is punished', () => {
71
87
  const good = lexicon.usageLowerBound({ candidate: 10, injection: 9, query: 0 })
72
88
  const bad = lexicon.usageLowerBound({ candidate: 10, injection: 1, query: 0 })
@@ -90,6 +90,27 @@ test('dice fallback: a fuzzy variant inside the prefix bucket hits with score >=
90
90
  assert.deepEqual(lexicon.matchLexiconHits(binding.libraryId, '今天天气不错', binding.memoryContext), [])
91
91
  })
92
92
 
93
+ test('dice fallback: a typo at the end of a long message still recalls the term (windows by hit count, not order)', () => {
94
+ const binding = setupSession('dice-tail', { terms: [{ term: '糖刀文学', kind: 'term', meaning: '又甜又虐的写法' }] })
95
+ // 40 字闲聊 + 末尾错字变体:旧实现按出现顺序只取前 16 个不同窗口,糖刀这个
96
+ // 前缀窗口落在第 17 个之后,模糊层收不到候选;现在窗口按命中词条数排序。
97
+ const chatter = '今晚的雾夜灯桥边茶铺霜露未散他忽然提起那些旧梗台词接得毫无痕迹我们笑作一团后来月影移过柳岸'
98
+ const text = `${chatter}糖刀文雪`
99
+ const normalized = lexicon.normalizeLexeme(text)
100
+ const windows = []
101
+ for (let i = 0; i + 2 <= normalized.length; i++) {
102
+ const key = normalized.slice(i, i + 2)
103
+ if (!windows.includes(key)) windows.push(key)
104
+ }
105
+ assert.ok(!windows.slice(0, lexicon.LEXICON_MAX_BUCKETS).includes('糖刀'),
106
+ 'fixture guard: the matching window must sit beyond the old 16-window cut')
107
+ const hits = lexicon.matchLexiconHits(binding.libraryId, text, binding.memoryContext)
108
+ assert.equal(hits.length, 1)
109
+ assert.equal(hits[0].term, '糖刀文学')
110
+ assert.equal(hits[0].kindOfHit, 'dice')
111
+ assert.ok(hits[0].score >= lexicon.LEXICON_DICE_THRESHOLD)
112
+ })
113
+
93
114
  test('active and restored terms match; archived and rejected never match or search', () => {
94
115
  const binding = setupSession('status', {})
95
116
  const lib = binding.libraryId
@@ -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
+ })