dsh-memu-memory 1.2.2 → 1.2.4

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 (58) hide show
  1. package/AGENTS.md +4 -1
  2. package/README.md +12 -16
  3. package/README.zh.md +13 -17
  4. package/docs/client-conventions.md +2 -0
  5. package/docs/contributing.md +7 -6
  6. package/docs/emotion-model-spec.md +2 -2
  7. package/docs/env-and-commands.md +63 -1
  8. package/docs/host-api.md +19 -0
  9. package/docs/memory-semantics.md +10 -1
  10. package/docs/troubleshooting.md +77 -3
  11. package/lib/activity-log.js +1 -1
  12. package/lib/binding-diagnostics.js +1 -1
  13. package/lib/client.js +223 -19
  14. package/lib/cycle.js +9 -1
  15. package/lib/embedding-catalog.js +416 -138
  16. package/lib/embedding-download.js +36 -11
  17. package/lib/freshness.js +97 -0
  18. package/lib/graph.js +244 -2
  19. package/lib/inject.js +218 -11
  20. package/lib/local-embedding-manager.js +3 -2
  21. package/lib/local-embedding-protocol.js +40 -3
  22. package/lib/local-embedding-worker.js +36 -6
  23. package/lib/local-vector-service.js +18 -4
  24. package/lib/memory.js +83 -17
  25. package/lib/memu.js +15 -7
  26. package/lib/private.js +25 -5
  27. package/lib/rpc.js +17 -3
  28. package/lib/salient-wake.js +402 -0
  29. package/lib/state.js +173 -1
  30. package/package.json +3 -2
  31. package/scripts/drive-session.mjs +864 -0
  32. package/scripts/mock-llm.mjs +903 -0
  33. package/scripts/simulate-injection.mjs +298 -0
  34. package/tests/client-render.test.mjs +69 -2
  35. package/tests/consolidation-fork.test.mjs +14 -1
  36. package/tests/drive-session.test.mjs +152 -0
  37. package/tests/embedding-catalog.test.mjs +116 -8
  38. package/tests/embedding-download.test.mjs +97 -2
  39. package/tests/embedding-runtime.test.mjs +21 -13
  40. package/tests/entity-merge.test.mjs +261 -0
  41. package/tests/fixtures/mock-llm/reply.txt +1 -0
  42. package/tests/freshness.test.mjs +140 -0
  43. package/tests/help-page.test.mjs +4 -4
  44. package/tests/injection-chain.test.mjs +176 -0
  45. package/tests/injection-rollback.test.mjs +230 -0
  46. package/tests/local-embedding-env.test.mjs +51 -0
  47. package/tests/local-embedding-manager.test.mjs +18 -0
  48. package/tests/local-embedding-protocol.test.mjs +28 -2
  49. package/tests/local-embedding-worker.test.mjs +94 -0
  50. package/tests/mock-llm.test.mjs +225 -0
  51. package/tests/open-loop-date.test.mjs +406 -0
  52. package/tests/salient-wake.test.mjs +362 -0
  53. package/tests/settings-plumbing.test.mjs +76 -0
  54. package/tests/sidebar.test.mjs +5 -1
  55. package/tests/simulate-injection.test.mjs +76 -0
  56. package/tests/stubs/dsh-schedule.js +105 -0
  57. package/tests/vector-profile.test.mjs +28 -4
  58. package/tests/webui-auth.test.mjs +4 -0
@@ -0,0 +1,140 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { freshnessSignals } from '../lib/freshness.js'
5
+
6
+ const DAY_MS = 86_400_000
7
+ // Local noon on 2026-11-15, so "today" is unambiguous in every timezone.
8
+ const NOW = new Date(2026, 10, 15, 12, 0, 0)
9
+ const daysAgo = (days) => new Date(NOW.getTime() - days * DAY_MS).toISOString()
10
+
11
+ function entry(patch = {}) {
12
+ return { title: '普通记忆', content: '窗外的雨停了。', updatedAt: daysAgo(0), ...patch }
13
+ }
14
+
15
+ test('a one-off date is stale only after its local day has passed', () => {
16
+ const cases = [
17
+ ['2026-11-14', true, 'dated-past:2026-11-14'],
18
+ ['2025-12-31', true, 'dated-past:2025-12-31'],
19
+ ['2026-11-15', false],
20
+ ['2026-11-16', false],
21
+ // Annual MM-DD is a birthday, not an expiry — even when that day already passed.
22
+ ['10-29', false],
23
+ ['02-29', false],
24
+ // Impossible or non-date-only values are ignored, never "expired".
25
+ ['2026-02-30', false],
26
+ ['2026-13-01', false],
27
+ ['2026-11-14T00:00:00', false],
28
+ ['', false],
29
+ [null, false],
30
+ [undefined, false],
31
+ ]
32
+ for (const [salientDate, stale, reason] of cases) {
33
+ const result = freshnessSignals(entry({ salientDate }), { now: NOW })
34
+ assert.equal(result.stale, stale, `salientDate=${String(salientDate)}`)
35
+ if (stale) assert.deepEqual(result.reasons, [reason])
36
+ else assert.deepEqual(result.reasons, [])
37
+ }
38
+ })
39
+
40
+ test('the fixed freshness vocabulary matches title and content', () => {
41
+ const terms = ['最新', '最近', '现在', '目前', '今年', '版本', '价格', '天气', '新闻', '比分', '汇率']
42
+ for (const term of terms) {
43
+ const inTitle = freshnessSignals(entry({ title: `关于${term}的记录` }), { now: NOW })
44
+ assert.equal(inTitle.stale, true, `${term} in title`)
45
+ assert.deepEqual(inTitle.reasons, [`freshness-term:${term}`])
46
+
47
+ const inContent = freshnessSignals(entry({ title: '记录', content: `这条提到${term}。` }), { now: NOW })
48
+ assert.equal(inContent.stale, true, `${term} in content`)
49
+ assert.deepEqual(inContent.reasons, [`freshness-term:${term}`])
50
+ }
51
+
52
+ const both = freshnessSignals(entry({ title: '最新价格' }), { now: NOW })
53
+ assert.deepEqual(both.reasons, ['freshness-term:最新', 'freshness-term:价格'])
54
+
55
+ assert.deepEqual(freshnessSignals(entry({ title: 'latest price' }), { now: NOW }), { stale: false, reasons: [] })
56
+ })
57
+
58
+ test('age comes from updatedAt first and ignores project facts', () => {
59
+ assert.deepEqual(
60
+ freshnessSignals(entry({ updatedAt: daysAgo(45) }), { now: NOW }).reasons,
61
+ ['age-days:45'],
62
+ )
63
+ // updatedAt wins over an older createdAt: an edited entry is current again.
64
+ assert.deepEqual(
65
+ freshnessSignals(entry({ updatedAt: daysAgo(1), createdAt: daysAgo(400) }), { now: NOW }).reasons,
66
+ [],
67
+ )
68
+ assert.deepEqual(
69
+ freshnessSignals(entry({ updatedAt: undefined, createdAt: daysAgo(45) }), { now: NOW }).reasons,
70
+ ['age-days:45'],
71
+ )
72
+ // Project conclusions may age too, but a coding library where every card says
73
+ // "old" is noise; the age leg stays off for them.
74
+ assert.deepEqual(
75
+ freshnessSignals(entry({ owner: 'about_project', updatedAt: daysAgo(400) }), { now: NOW }).reasons,
76
+ [],
77
+ )
78
+ // Only the age leg is excluded: time-sensitive wording still counts.
79
+ assert.deepEqual(
80
+ freshnessSignals(entry({ owner: 'about_project', title: '版本', updatedAt: daysAgo(400) }), { now: NOW }).reasons,
81
+ ['freshness-term:版本'],
82
+ )
83
+ })
84
+
85
+ test('missing, invalid and future timestamps are not age signals', () => {
86
+ const cases = [
87
+ { updatedAt: undefined, createdAt: undefined },
88
+ { updatedAt: null, createdAt: null },
89
+ { updatedAt: '', createdAt: '' },
90
+ { updatedAt: 'not-a-date', createdAt: 'also-not-a-date' },
91
+ { updatedAt: NaN, createdAt: NaN },
92
+ { updatedAt: daysAgo(-10), createdAt: daysAgo(-10) },
93
+ ]
94
+ for (const patch of cases) {
95
+ assert.deepEqual(freshnessSignals(entry(patch), { now: NOW }), { stale: false, reasons: [] })
96
+ }
97
+ })
98
+
99
+ test('the age boundary is inclusive at freshnessDays', () => {
100
+ const exact = freshnessSignals({ updatedAt: new Date(NOW.getTime() - 30 * DAY_MS).toISOString() }, { now: NOW })
101
+ assert.equal(exact.stale, true)
102
+ assert.deepEqual(exact.reasons, ['age-days:30'])
103
+
104
+ const justUnder = freshnessSignals({ updatedAt: new Date(NOW.getTime() - (30 * DAY_MS - 1)).toISOString() }, { now: NOW })
105
+ assert.deepEqual(justUnder, { stale: false, reasons: [] })
106
+
107
+ assert.equal(freshnessSignals({ updatedAt: daysAgo(89) }, { now: NOW, freshnessDays: 90 }).stale, false)
108
+ assert.equal(freshnessSignals({ updatedAt: daysAgo(90) }, { now: NOW, freshnessDays: 90 }).stale, true)
109
+
110
+ // An unusable threshold falls back to 30, not to "everything is stale".
111
+ assert.equal(freshnessSignals({ updatedAt: daysAgo(31) }, { now: NOW, freshnessDays: NaN }).stale, true)
112
+ assert.equal(freshnessSignals({ updatedAt: daysAgo(29) }, { now: NOW, freshnessDays: 'nope' }).stale, false)
113
+ })
114
+
115
+ test('signals compose and the reasons list names every one of them', () => {
116
+ const all = freshnessSignals({
117
+ title: '最新价格',
118
+ content: '汇率也变了。',
119
+ salientDate: '2026-11-01',
120
+ updatedAt: daysAgo(60),
121
+ }, { now: NOW })
122
+ assert.equal(all.stale, true)
123
+ assert.deepEqual(all.reasons, [
124
+ 'dated-past:2026-11-01',
125
+ 'freshness-term:最新',
126
+ 'freshness-term:价格',
127
+ 'freshness-term:汇率',
128
+ 'age-days:60',
129
+ ])
130
+ })
131
+
132
+ test('bad entries and bad clocks never throw', () => {
133
+ for (const value of [null, undefined, 42, 'memory']) {
134
+ assert.deepEqual(freshnessSignals(value), { stale: false, reasons: [] })
135
+ }
136
+ for (const now of [NaN, 'not-a-date', new Date(NaN)]) {
137
+ const result = freshnessSignals({ updatedAt: '2000-01-01T00:00:00Z' }, { now })
138
+ assert.equal(result.stale, true, `now=${String(now)} must fall back to the wall clock`)
139
+ }
140
+ })
@@ -231,7 +231,7 @@ test('the deep link #/settings/help lands on the help page when standalone', asy
231
231
  window.location.hash = ''
232
232
  })
233
233
 
234
- test('the help page shows five steps, ten FAQ details and the feedback actions', async () => {
234
+ test('the help page shows five steps, eleven FAQ details and the feedback actions', async () => {
235
235
  const component = settingsComponent()
236
236
  const props = { ctx: fakeCtx(), t: (key) => key }
237
237
  await mountAndSettle(component, props)
@@ -240,7 +240,7 @@ test('the help page shows five steps, ten FAQ details and the feedback actions',
240
240
  const { tree } = renderAt(component, props, 12)
241
241
  const text = treeText(tree)
242
242
  for (const step of [1, 2, 3, 4, 5]) assert.ok(text.includes(`helpStep${step}`), `quick start step ${step} is missing`)
243
- for (const n of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) {
243
+ for (const n of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) {
244
244
  assert.ok(text.includes(`helpFaq${n}`), `FAQ item ${n} is missing`)
245
245
  assert.ok(text.includes(`helpFaq${n}A`), `FAQ answer ${n} is missing`)
246
246
  }
@@ -248,13 +248,13 @@ test('the help page shows five steps, ten FAQ details and the feedback actions',
248
248
  assert.ok(text.includes('helpOpenIssue'), 'the issue button is missing')
249
249
  assert.ok(text.includes('helpCopyDiagnostics'), 'the copy-diagnostics button is missing')
250
250
  assert.ok(text.includes('helpDocs'), 'the docs link is missing')
251
- // FAQ 用 10 个 <details> 折叠;quick start 的每一步都带「前往 →」跳转按钮
251
+ // FAQ 用 11 个 <details> 折叠;quick start 的每一步都带「前往 →」跳转按钮
252
252
  //(第 2 步是会话侧动作,只给文案,不带跳转 → 4 个按钮)。
253
253
  const details = []
254
254
  walkNodes(tree, (node) => {
255
255
  if (node.type === 'details') details.push(node)
256
256
  })
257
- assert.equal(details.length, 10, `expected ten FAQ details, found ${details.length}`)
257
+ assert.equal(details.length, 11, `expected eleven FAQ details, found ${details.length}`)
258
258
  assert.equal((text.match(/helpGoTo/g) || []).length, 4, 'four of the five steps jump, the bind step cannot')
259
259
  // 不新增 RPC:复制诊断只序列化 getSettingsState 的既有快照(state 优先,缺了才补拉)。
260
260
  const src = clientSource
@@ -11,6 +11,7 @@ process.env.DSH_MEMU_HOME = home
11
11
  const state = await import('../lib/state.js')
12
12
  const memory = await import('../lib/memory.js')
13
13
  const inject = await import('../lib/inject.js')
14
+ const budget = await import('../lib/budget.js')
14
15
 
15
16
  test.after(() => {
16
17
  try { state.flushState() } catch {}
@@ -189,3 +190,178 @@ test('the remember tool tells the model to resolve a relative day', () => {
189
190
  assert.ok(source.includes('A relative day'), 'the tool description must mention relative days')
190
191
  assert.ok(source.includes('turns one appointment into a yearly reminder'), 'and why it matters')
191
192
  })
193
+
194
+ // ------------------------------------- D: freshness hint is conditional and bounded
195
+ // The hint is a footnote to a recall that already succeeded: it must appear once,
196
+ // after every closed <memory-context> block, and must never turn a normal turn into
197
+ // a hint-only or failed turn.
198
+
199
+ const DAY_MS = 86_400_000
200
+
201
+ function seedRecallEntry(binding, id, patch = {}) {
202
+ const now = new Date().toISOString()
203
+ const index = state.loadPrivateIndex(binding.libraryId)
204
+ index.entries[id] = {
205
+ track: 'memory',
206
+ layer: 'long_term',
207
+ title: '部署脚本的位置',
208
+ content: '部署脚本放在 tools/deploy.ps1,先跑 staging smoke。',
209
+ status: 'active',
210
+ confidence: 0.9,
211
+ createdAt: now,
212
+ updatedAt: now,
213
+ ...patch,
214
+ }
215
+ state.savePrivateIndex(binding.libraryId, index)
216
+ }
217
+
218
+ async function recallFor(sessionId, binding, query, patch = {}) {
219
+ const exec = { agent: { session: { header: { id: sessionId, agentPreset: 'coding' } } } }
220
+ return inject.buildRecall(binding, query, 1, {
221
+ ...state.getSettings(),
222
+ relevanceThreshold: 0,
223
+ ...patch,
224
+ }, exec, sessionId)
225
+ }
226
+
227
+ test('a stale recalled memory appends exactly one freshness hint after the closed blocks', async () => {
228
+ const cwd = path.join(home, 'project-freshness-stale')
229
+ const binding = state.ensureSession('chain-freshness-stale', { cwd, agentPreset: 'coding' })
230
+ const old = new Date(Date.now() - 45 * DAY_MS).toISOString()
231
+ seedRecallEntry(binding, 'mem-fresh-deploy', { updatedAt: old })
232
+ seedRecallEntry(binding, 'mem-fresh-release', {
233
+ title: '发布流程的审批',
234
+ content: '发布流程需要提前一天审批。',
235
+ updatedAt: old,
236
+ })
237
+
238
+ const recall = await recallFor('chain-freshness-stale', binding, '部署脚本和发布流程')
239
+ assert.deepEqual(recall.errors, [])
240
+ assert.ok(recall.ids.includes('mem-fresh-deploy'))
241
+ assert.ok(recall.ids.includes('mem-fresh-release'))
242
+ assert.equal((recall.text.match(/<memory-freshness>/g) || []).length, 1, 'the hint appears exactly once')
243
+ assert.ok(recall.text.includes('上面有 2 条记忆带时间敏感信号'), 'N counts the unique stale entries')
244
+ assert.ok(recall.text.indexOf('<memory-freshness>') > recall.text.lastIndexOf('</memory-context>'),
245
+ 'the hint follows the last closed context block')
246
+ assert.equal((recall.text.match(/<memory-context\b/g) || []).length, 1, 'recall still has one context block')
247
+ assert.equal((recall.text.match(/<\/memory-context>/g) || []).length, 1)
248
+ assert.ok(recall.text.endsWith('</memory-freshness>'))
249
+
250
+ // The age leg obeys freshnessDays: 45-day-old entries are fresh at 100 days.
251
+ const lenient = await recallFor('chain-freshness-stale', binding, '部署脚本和发布流程', { freshnessDays: 100 })
252
+ assert.ok(lenient.text.includes('</memory-context>'))
253
+ assert.equal(lenient.text.includes('<memory-freshness>'), false)
254
+ })
255
+
256
+ test('a fresh recalled memory adds no freshness hint', async () => {
257
+ const cwd = path.join(home, 'project-freshness-fresh')
258
+ const binding = state.ensureSession('chain-freshness-fresh', { cwd, agentPreset: 'coding' })
259
+ seedRecallEntry(binding, 'mem-fresh-now')
260
+
261
+ const recall = await recallFor('chain-freshness-fresh', binding, '部署脚本放在哪里')
262
+ assert.ok(recall.ids.includes('mem-fresh-now'))
263
+ assert.ok(recall.text.includes('</memory-context>'))
264
+ assert.equal(recall.text.includes('<memory-freshness>'), false)
265
+ })
266
+
267
+ test('the hint ships in the same plugin message as the recall block', async () => {
268
+ state.updateSettings({ randomCueChance: 0 })
269
+ const cwd = path.join(home, 'project-freshness-message')
270
+ const binding = state.ensureSession('chain-freshness-message', { cwd, agentPreset: 'coding' })
271
+ seedRecallEntry(binding, 'mem-fresh-message', { updatedAt: new Date(Date.now() - 45 * DAY_MS).toISOString() })
272
+
273
+ const user = {
274
+ id: 'u-freshness', role: 'user', source: { kind: 'user' },
275
+ content: [{ type: 'text', text: '部署脚本放在哪里' }],
276
+ }
277
+ const agent = { session: { header: { id: 'chain-freshness-message', cwd, agentPreset: 'coding', origin: 'user' } } }
278
+ const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [user] }, turn: 1, step: 1, signal: { aborted: false } })
279
+
280
+ assert.equal(out.messages.length, 2)
281
+ assert.equal(out.messages[0].source.kind, 'plugin:dsh-memu-memory')
282
+ const text = out.messages[0].content[0].text
283
+ assert.ok(text.includes('[mem-fresh-message]'))
284
+ assert.equal((text.match(/<memory-freshness>/g) || []).length, 1)
285
+ assert.ok(text.indexOf('<memory-freshness>') > text.lastIndexOf('</memory-context>'))
286
+ assert.equal(state.getSessionBinding('chain-freshness-message').lastRecallError, undefined)
287
+ })
288
+
289
+ test('anchor-only and autoInject off never append the freshness hint', async () => {
290
+ const cwd = path.join(home, 'project-freshness-modes')
291
+ const binding = state.ensureSession('chain-freshness-modes', { cwd, agentPreset: 'coding' })
292
+ seedRecallEntry(binding, 'mem-fresh-modes', { updatedAt: new Date(Date.now() - 90 * DAY_MS).toISOString() })
293
+
294
+ const anchorOnly = await recallFor('chain-freshness-modes', binding, '部署脚本放在哪里', { autoInject: 'anchor-only' })
295
+ assert.ok(anchorOnly.text.includes('</memory-context>'))
296
+ assert.equal(anchorOnly.text.includes('<memory-freshness>'), false)
297
+
298
+ // buildRecall itself is not the off switch; the caller is. The hint still must
299
+ // not appear if a future caller forgets that.
300
+ const off = await recallFor('chain-freshness-modes', binding, '部署脚本放在哪里', { autoInject: 'off' })
301
+ assert.ok(off.text.includes('</memory-context>'))
302
+ assert.equal(off.text.includes('<memory-freshness>'), false)
303
+ })
304
+
305
+ test('a query shorter than minUserChars gets the recall but no freshness hint', async () => {
306
+ const cwd = path.join(home, 'project-freshness-short')
307
+ const binding = state.ensureSession('chain-freshness-short', { cwd, agentPreset: 'coding' })
308
+ seedRecallEntry(binding, 'mem-fresh-short', {
309
+ title: '最新的部署方式',
310
+ content: '最新的部署方式放在 tools/deploy.ps1。',
311
+ })
312
+
313
+ const recall = await recallFor('chain-freshness-short', binding, '最新')
314
+ assert.ok(recall.ids.includes('mem-fresh-short'))
315
+ assert.ok(recall.text.includes('</memory-context>'))
316
+ assert.equal(recall.text.includes('<memory-freshness>'), false)
317
+ })
318
+
319
+ test('freshnessHint false suppresses the freshness hint', async () => {
320
+ const cwd = path.join(home, 'project-freshness-switch')
321
+ const binding = state.ensureSession('chain-freshness-switch', { cwd, agentPreset: 'coding' })
322
+ seedRecallEntry(binding, 'mem-fresh-switch', { updatedAt: new Date(Date.now() - 45 * DAY_MS).toISOString() })
323
+
324
+ const recall = await recallFor('chain-freshness-switch', binding, '部署脚本放在哪里', { freshnessHint: false })
325
+ assert.ok(recall.ids.includes('mem-fresh-switch'))
326
+ assert.ok(recall.text.includes('</memory-context>'))
327
+ assert.equal(recall.text.includes('<memory-freshness>'), false)
328
+ })
329
+
330
+ test('the hint is dropped when turnTokens cannot fit it, and the recall still succeeds', async () => {
331
+ const cwd = path.join(home, 'project-freshness-budget')
332
+ const binding = state.ensureSession('chain-freshness-budget', { cwd, agentPreset: 'coding' })
333
+ seedRecallEntry(binding, 'mem-fresh-budget', { updatedAt: new Date(Date.now() - 45 * DAY_MS).toISOString() })
334
+
335
+ const full = await recallFor('chain-freshness-budget', binding, '部署脚本放在哪里', { turnTokens: 800 })
336
+ const marker = '\n\n<memory-freshness>'
337
+ const at = full.text.indexOf(marker)
338
+ assert.ok(at > 0, 'with room the hint appears')
339
+ const hint = full.text.slice(at)
340
+ const base = full.text.slice(0, at)
341
+ const needed = budget.estTokens(base)
342
+ assert.ok(budget.estTokens(base + hint) > needed, 'the hint itself costs something')
343
+
344
+ // The smallest budget that still fits the card cannot also fit the footnote.
345
+ let squeezed = null
346
+ for (let extra = 0; extra <= 12 && !squeezed; extra += 1) {
347
+ const turnTokens = needed + extra
348
+ const attempt = await recallFor('chain-freshness-budget', binding, '部署脚本放在哪里', { turnTokens })
349
+ if (attempt.text) squeezed = { attempt, turnTokens }
350
+ }
351
+ assert.ok(squeezed, 'a budget near the base size still fits one card')
352
+ assert.ok(squeezed.attempt.text.includes('[mem-fresh-budget]'))
353
+ assert.ok(squeezed.attempt.text.includes('</memory-context>'))
354
+ assert.equal(squeezed.attempt.text.includes('<memory-freshness>'), false)
355
+ assert.ok(budget.estTokens(squeezed.attempt.text) <= squeezed.turnTokens)
356
+ })
357
+
358
+ test('no recall means no freshness hint', async () => {
359
+ const cwd = path.join(home, 'project-freshness-none')
360
+ const binding = state.ensureSession('chain-freshness-none', { cwd, agentPreset: 'coding' })
361
+ seedRecallEntry(binding, 'mem-fresh-none', { updatedAt: new Date(Date.now() - 45 * DAY_MS).toISOString() })
362
+
363
+ const recall = await recallFor('chain-freshness-none', binding, 'zzz-unrelated-token-zzz')
364
+ assert.equal(recall.text, '')
365
+ assert.deepEqual(recall.ids, [])
366
+ assert.equal(recall.text.includes('<memory-freshness>'), false)
367
+ })
@@ -0,0 +1,230 @@
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
+ // §3.24 —— 宿主会把失败的整轮回滚(真机实测:连用户消息都不留在转录里),而插件在"消息交回
8
+ // 决策"之后就记了账。不撤销的话,guide / 锚点 / 当日纪念日 / 复提时钟这类一次性内容就永远
9
+ // 不再投,整段对话只是"记忆像没接上",一句错都不报。判据是本轮那几条注入消息到底进过转录没有:
10
+ // 进过(请求已经发出去)就保住记账,没进过才撤回。这里把撤与不撤两面都钉住。
11
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-rollback-'))
12
+ process.env.DSH_MEMU_HOME = home
13
+
14
+ const state = await import('../lib/state.js')
15
+ const inject = await import('../lib/inject.js')
16
+ const activity = await import('../lib/activity-log.js')
17
+
18
+ const handlers = new Map()
19
+ const warns = []
20
+ const ctx = {
21
+ on: (topic, handler) => { handlers.set(topic, handler); return () => {} },
22
+ get: () => undefined,
23
+ logger: { warn: (message) => warns.push(String(message)), info: () => {}, error: () => {} },
24
+ effect: (fn) => { try { fn() } catch {} },
25
+ slots: { inject: () => {} },
26
+ webServer: { register: () => {} },
27
+ }
28
+ inject.registerInjection(ctx)
29
+ const preStep = handlers.get('agent/pre-step')
30
+ const sessionEvent = handlers.get('session/event')
31
+ assert.equal(typeof preStep, 'function', 'registerInjection must expose agent/pre-step')
32
+ assert.equal(typeof sessionEvent, 'function', 'registerInjection must listen to session/event')
33
+
34
+ const GUIDE_RE = /<memory-guide/
35
+ const ANCHOR_RE = /=====\s*memory\s*anchor\s*=====/
36
+ const textOf = (message) => (typeof message?.content === 'string'
37
+ ? message.content
38
+ : (message?.content || []).map((part) => part?.text || '').join(''))
39
+ const countWith = (messages, re) => messages.filter((message) => re.test(textOf(message))).length
40
+ const user = (n, text) => ({ id: `u-${n}`, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text }] })
41
+ const assistant = (n, text) => ({ id: `a-${n}`, role: 'assistant', content: [{ type: 'text', text }] })
42
+
43
+ function makeSession(id) {
44
+ const cwd = path.join(home, id)
45
+ const binding = state.ensureSession(id, { cwd, agentPreset: 'coding' })
46
+ state.setSessionBinding(id, { useLibrary: true, useGlobal: false })
47
+ const now = new Date().toISOString()
48
+ state.updatePrivateIndex(binding.libraryId, (index) => {
49
+ for (let i = 1; i <= 3; i += 1) {
50
+ index.entries[`mem-${id}-${i}`] = {
51
+ id: `mem-${id}-${i}`, track: 'memory', layer: 'long_term', status: 'active',
52
+ title: `林眠的相机镜头跑焦维修进度 ${i}`,
53
+ content: `林眠的相机镜头送修,报价与工期记录在第 ${i} 条。`,
54
+ visibility: 'shared', disclosure: 'can_tell', owner: 'me',
55
+ createdAt: now, updatedAt: now,
56
+ }
57
+ }
58
+ })
59
+ return { id, cwd }
60
+ }
61
+
62
+ async function step(session, turn, messages) {
63
+ const out = await preStep({
64
+ agent: { session: { header: { id: session.id, cwd: session.cwd, agentPreset: 'coding', origin: 'user' } } },
65
+ turn, step: 1, signal: { aborted: false },
66
+ }, async () => ({ kind: 'enter', messages }))
67
+ return out?.messages || messages
68
+ }
69
+
70
+ function failTurn(session, turn) {
71
+ return sessionEvent(
72
+ { header: { id: session.id } },
73
+ { type: 'turn/end', data: { turn, reason: { kind: 'error', error: { message: 'llm unreachable' } } } },
74
+ )
75
+ }
76
+
77
+ function completeTurn(session, turn) {
78
+ return sessionEvent({ header: { id: session.id } }, { type: 'turn/end', data: { turn, reason: { kind: 'completed' } } })
79
+ }
80
+
81
+ const facts = (id) => {
82
+ const binding = state.getSessionBinding(id) || {}
83
+ return {
84
+ guide: binding.guideRulesKey || null,
85
+ anchor: (binding.injectedIds || []).includes(inject.ANCHOR_SENTINEL),
86
+ rollback: binding.injectionRollback || null,
87
+ injected: (binding.injectedIds || []).filter((entry) => entry !== inject.ANCHOR_SENTINEL).length,
88
+ }
89
+ }
90
+
91
+ test('a failed turn gives back the one-shot accounting, and the next turn re-places it', async () => {
92
+ const session = makeSession('rb-err')
93
+ const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
94
+ assert.equal(countWith(first, GUIDE_RE), 1, 'turn 1 places the guide')
95
+ assert.equal(countWith(first, ANCHOR_RE), 1, 'turn 1 places the anchor')
96
+ const placed = facts(session.id)
97
+ assert.ok(placed.guide && placed.anchor && placed.injected > 0, 'the accounting says everything was delivered')
98
+
99
+ await failTurn(session, 1)
100
+ const rolled = facts(session.id)
101
+ assert.equal(rolled.guide, null, 'guide key rolled back')
102
+ assert.equal(rolled.anchor, false, 'anchor sentinel rolled back')
103
+ assert.equal(rolled.injected, 0, 'the recall ids of that turn are forgotten too')
104
+ assert.equal(rolled.rollback, null, 'the rollback record is consumed, not left to age')
105
+ assert.ok(warns.some((line) => /rolled back injection accounting/.test(line)), 'the rollback leaves a log signal')
106
+ const events = activity.listEvents({ limit: 50, kind: 'system' })
107
+ assert.ok(events.some((event) => event.sessionId === session.id && /已撤回本轮的注入记账/.test(event.message || '')),
108
+ 'and an activity-log row explains what happened')
109
+
110
+ // 下一轮:宿主给的转录里没有任何一次性的东西,必须重新投出来。
111
+ const second = await step(session, 2, [user(1, '林眠的相机镜头修好了吗'), user(2, '那维修报价给了吗')])
112
+ assert.equal(countWith(second, GUIDE_RE), 1, 'the guide comes back')
113
+ assert.equal(countWith(second, ANCHOR_RE), 1, 'the anchor comes back')
114
+ })
115
+
116
+ test('a completed turn keeps its accounting, so nothing is re-placed', async () => {
117
+ const session = makeSession('rb-ok')
118
+ const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
119
+ assert.equal(countWith(first, GUIDE_RE), 1)
120
+ await completeTurn(session, 1)
121
+
122
+ const kept = facts(session.id)
123
+ assert.ok(kept.guide, 'a completed turn must not forget the guide key')
124
+ assert.equal(kept.anchor, true, 'nor the anchor sentinel')
125
+
126
+ const view = [...first, assistant(1, '还在修。'), user(2, '林眠镜头跑焦的工期多久')]
127
+ const second = await step(session, 2, view)
128
+ assert.equal(countWith(second, GUIDE_RE), 1, 'the guide stays single-copy')
129
+ assert.equal(countWith(second, ANCHOR_RE), 1, 'the anchor is not repeated')
130
+ })
131
+
132
+ test('a completed turn consumes its record, so a late error cannot un-place what is already in the transcript', async () => {
133
+ const session = makeSession('rb-stale')
134
+ const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
135
+ assert.equal(countWith(first, GUIDE_RE), 1)
136
+ assert.ok(facts(session.id).rollback, 'the turn that just delivered leaves a rollback record')
137
+
138
+ await completeTurn(session, 1)
139
+ const kept = facts(session.id)
140
+ assert.equal(kept.rollback, null, 'a completed turn consumes the record')
141
+ assert.ok(kept.guide, 'its guide key stays')
142
+ assert.equal(kept.anchor, true, 'and so does the anchor sentinel')
143
+
144
+ // 迟到的 error 事件不能再撤回已经落在转录里的那一份,否则下一轮就凭空多出第二条规则消息/锚点。
145
+ await failTurn(session, 1)
146
+ const after = facts(session.id)
147
+ assert.ok(after.guide, 'the late error does not forget the guide key')
148
+ assert.equal(after.anchor, true, 'nor re-arm the anchor')
149
+ assert.equal(after.injected, kept.injected, 'the recall ids of that turn stay accounted')
150
+
151
+ const warnBefore = warns.length
152
+ const second = await step(session, 2, [...first, assistant(1, '还在修。'), user(2, '维修报价给了吗')])
153
+ assert.equal(countWith(second, GUIDE_RE), 1, 'no second rules message')
154
+ assert.equal(countWith(second, ANCHOR_RE), 1, 'no second anchor')
155
+ assert.equal(warns.slice(warnBefore).filter((line) => /rolled back injection accounting/.test(line)).length, 0,
156
+ 'and nothing was rolled back along the way')
157
+ })
158
+
159
+ test('a failure after the injection reached the transcript keeps the accounting', async () => {
160
+ const session = makeSession('rb-admitted')
161
+ const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
162
+ const injected = first.find((message) => message?.source?.kind === 'plugin:dsh-memu-memory')
163
+ assert.ok(injected?.id, 'the turn produced an identified injection message')
164
+
165
+ // 宿主在第一次尝试里就把 decision.messages 逐条追加进转录,之后才连模型。上游 500 / 超时
166
+ // 属于这一类:内容已经在转录里,撤回记账只会让下一轮多出第二份规则消息与锚点。
167
+ await sessionEvent({ header: { id: session.id } }, { type: 'user/message', data: injected })
168
+ await failTurn(session, 1)
169
+ const kept = facts(session.id)
170
+ assert.ok(kept.guide, 'the rules message stays accounted')
171
+ assert.equal(kept.anchor, true, 'and so does the anchor')
172
+ assert.equal(kept.rollback, null, 'the record is consumed instead of rolled back')
173
+
174
+ const warnBefore = warns.length
175
+ const second = await step(session, 2, [...first, user(2, '维修报价给了吗')])
176
+ assert.equal(countWith(second, GUIDE_RE), 1, 'no second rules message')
177
+ assert.equal(countWith(second, ANCHOR_RE), 1, 'no second anchor')
178
+ assert.equal(warns.slice(warnBefore).filter((line) => /rolled back injection accounting/.test(line)).length, 0,
179
+ 'nothing was rolled back along the way')
180
+ })
181
+
182
+ test('a cancel before the messages were appended also gives the accounting back', async () => {
183
+ const session = makeSession('rb-abort')
184
+ const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
185
+ assert.equal(countWith(first, ANCHOR_RE), 1)
186
+
187
+ // 用户在模型调用之前就按了停止:转录里什么都没有,aborted 同样该把记账还回来。
188
+ await sessionEvent({ header: { id: session.id } }, {
189
+ type: 'turn/end', data: { turn: 1, reason: { kind: 'aborted', reason: 'user stop' } },
190
+ })
191
+ const after = facts(session.id)
192
+ assert.equal(after.guide, null, '取消发生在投放之前:一次性内容还没有落进转录')
193
+ assert.equal(after.anchor, false)
194
+
195
+ const again = await step(session, 2, [user(1, '林眠的相机镜头修好了吗')])
196
+ assert.equal(countWith(again, ANCHOR_RE), 1, 'the anchor is placed again next turn')
197
+ })
198
+
199
+ test('rollback also clears the day marks so dated blocks can return', async () => {
200
+ const session = makeSession('rb-dated')
201
+ const now = Date.now()
202
+ const iso = (offsetDays) => new Date(now + offsetDays * 86400000).toISOString()
203
+ const day = (offset) => {
204
+ const value = new Date(now + offset * 86400000)
205
+ return `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`
206
+ }
207
+ state.updatePrivateIndex(state.getSessionBinding(session.id).libraryId, (index) => {
208
+ index.entries['mem-rb-dated-lost'] = {
209
+ id: 'mem-rb-dated-lost', track: 'memory', layer: 'long_term', status: 'active',
210
+ title: '明天要把镜头还给林眠', content: '说明天在城南咖啡店把镜头还给林眠。',
211
+ salientDate: day(1), openLoop: true, visibility: 'shared', disclosure: 'can_tell', owner: 'me',
212
+ createdAt: iso(-2), updatedAt: iso(-2),
213
+ }
214
+ index.entries['mem-rb-dated-loop'] = {
215
+ id: 'mem-rb-dated-loop', track: 'memory', layer: 'long_term', status: 'active',
216
+ title: '答应给林眠带咖啡豆', content: '一直没做,也没有约定日期。',
217
+ openLoop: true, visibility: 'shared', disclosure: 'can_tell', owner: 'me',
218
+ createdAt: iso(-5), updatedAt: iso(-5),
219
+ }
220
+ })
221
+
222
+ await step(session, 1, [user(1, '明天有什么我要办的事')])
223
+ const binding = state.getSessionBinding(session.id)
224
+ assert.ok(Object.keys(binding.anniversariesShown || {}).length > 0 || (binding.injectedIds || []).length > 1,
225
+ 'the dated blocks recorded their own clocks on that turn')
226
+ await failTurn(session, 1)
227
+ const after = state.getSessionBinding(session.id)
228
+ assert.equal(Object.keys(after.anniversariesShown || {}).length, 0, 'the day mark is withdrawn with the turn')
229
+ assert.equal(Object.keys(after.openLoopRemindedAt || {}).length, 0, 'and so is the re-reminder clock')
230
+ })
@@ -0,0 +1,51 @@
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-env-'))
8
+ process.env.DSH_MEMU_MEMORY_HOME = home
9
+
10
+ const { localEmbeddingEnv } = await import('../lib/memu.js')
11
+
12
+ test.after(() => fs.rmSync(home, { recursive: true, force: true }))
13
+
14
+ const E5 = 'multilingual-e5-small@252d0dcb679dda2c7b6fd5bbfed15df3c7feaebf+dsh-local-embedding-v1'
15
+ const BGE = 'bge-small-zh-v1.5-int8@313386ad7ffad360a4870fd1910f8ecaf1a05151+dsh-local-embedding-v1'
16
+ const BASE = 'http://127.0.0.1:45123/v1'
17
+ const TOKEN = 'worker-token-0123456789abcdef'
18
+
19
+ // §14.4:MemU 的请求信封里没有角色字段,所以「这条文本是查询还是条目」只能由启动子进程的
20
+ // 插件来说——它写在 model 字符串上,由 worker 解析回来。
21
+ test('the role the plugin knows rides on the model string MemU echoes back', () => {
22
+ const query = localEmbeddingEnv({ baseUrl: BASE, token: TOKEN, model: E5, rolesRequired: true, role: 'query', db: 'C:/x/global.sqlite3' })
23
+ assert.equal(query.MEMU_EMBED_MODEL, E5 + ':query')
24
+ const document = localEmbeddingEnv({ baseUrl: BASE, token: TOKEN, model: E5, rolesRequired: true, role: 'document' })
25
+ assert.equal(document.MEMU_EMBED_MODEL, E5 + ':passage')
26
+ // 未知角色也只能落在文档读法上,不能悄悄变成查询读法
27
+ assert.equal(localEmbeddingEnv({ baseUrl: BASE, token: TOKEN, model: E5, rolesRequired: true }).MEMU_EMBED_MODEL, E5 + ':passage')
28
+ })
29
+
30
+ test('a model with one prefix for both sides keeps the byte-identical model string', () => {
31
+ for (const role of [undefined, 'query', 'document']) {
32
+ assert.equal(
33
+ localEmbeddingEnv({ baseUrl: BASE, token: TOKEN, model: BGE, rolesRequired: false, role }).MEMU_EMBED_MODEL,
34
+ BGE,
35
+ 'BGE/MiniLM must not pick up a role suffix',
36
+ )
37
+ }
38
+ })
39
+
40
+ test('the strict-local envelope is unchanged: loopback base, token as key, telemetry off', () => {
41
+ const env = localEmbeddingEnv({ baseUrl: BASE, token: TOKEN, model: BGE, db: 'C:/x/global.sqlite3' })
42
+ assert.equal(env.MEMU_MEMORY_MODE, 'local')
43
+ assert.equal(env.MEMU_EMBED_PROVIDER, 'openai')
44
+ assert.equal(env.MEMU_TELEMETRY, '0')
45
+ assert.equal(env.DO_NOT_TRACK, '1')
46
+ assert.equal(env.MEMU_EVENTS_BASE_URL, '')
47
+ assert.equal(env.MEMU_BASE_URL, BASE)
48
+ assert.equal(env.MEMU_API_KEY, TOKEN, 'the loopback token is the only credential this env can carry')
49
+ assert.equal(env.MEMU_DB, 'C:/x/global.sqlite3')
50
+ assert.equal(Object.keys(env).filter(name => /PROXY/i.test(name)).length, 0)
51
+ })