dsh-memu-memory 1.3.7 → 1.3.8

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 (54) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +58 -0
  3. package/README.md +7 -7
  4. package/README.zh.md +7 -7
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/contributing.md +2 -2
  7. package/docs/memory-semantics.md +7 -6
  8. package/docs/troubleshooting.md +74 -7
  9. package/lib/binding-diagnostics.js +2 -2
  10. package/lib/client.js +150 -81
  11. package/lib/consolidation-ledger.js +6 -2
  12. package/lib/inbound.js +24 -9
  13. package/lib/inject.js +379 -215
  14. package/lib/memory.js +704 -181
  15. package/lib/paths.js +24 -0
  16. package/lib/private.js +242 -132
  17. package/lib/rpc.js +53 -6
  18. package/lib/snippet.js +49 -28
  19. package/lib/state.js +185 -26
  20. package/lib/tools.js +137 -28
  21. package/lib/webui.js +25 -1
  22. package/lib/worker-pool.js +260 -26
  23. package/package.json +1 -1
  24. package/scripts/check-i18n.mjs +19 -0
  25. package/scripts/recall-bench.mjs +4 -4
  26. package/scripts/simulate-injection.mjs +3 -0
  27. package/tests/activity-wiring.test.mjs +52 -0
  28. package/tests/client-render.test.mjs +207 -0
  29. package/tests/consolidation-feed.test.mjs +26 -0
  30. package/tests/consolidation-fork.test.mjs +587 -26
  31. package/tests/cross-library-recall.test.mjs +156 -0
  32. package/tests/cue.test.mjs +15 -2
  33. package/tests/hybrid-recall.test.mjs +488 -0
  34. package/tests/inbound.test.mjs +49 -4
  35. package/tests/inject-conflict.test.mjs +70 -9
  36. package/tests/inject-guide.test.mjs +13 -1
  37. package/tests/inject.test.mjs +10 -0
  38. package/tests/injection-budget.test.mjs +101 -0
  39. package/tests/injection-chain.test.mjs +37 -0
  40. package/tests/injection-rollback.test.mjs +172 -9
  41. package/tests/issue2-chain.test.mjs +169 -0
  42. package/tests/lexicon-inject.test.mjs +33 -5
  43. package/tests/managed-memory.test.mjs +625 -1
  44. package/tests/media.test.mjs +1 -1
  45. package/tests/new-session-gate.test.mjs +280 -25
  46. package/tests/open-loop-date.test.mjs +11 -1
  47. package/tests/recall-intent.test.mjs +52 -3
  48. package/tests/simulate-injection.test.mjs +4 -4
  49. package/tests/snippet.test.mjs +33 -1
  50. package/tests/state.test.mjs +8 -3
  51. package/tests/tool-schema.test.mjs +52 -0
  52. package/tests/tools.test.mjs +394 -0
  53. package/tests/webui.test.mjs +16 -2
  54. package/tests/worker-lifecycle.test.mjs +419 -36
@@ -0,0 +1,169 @@
1
+ // 服务端注入与 RPC 集成;弹窗生命周期由 new-session-gate.test.mjs 独立验证。
2
+ import test from 'node:test'
3
+ import assert from 'node:assert/strict'
4
+ import fs from 'node:fs'
5
+ import os from 'node:os'
6
+ import path from 'node:path'
7
+
8
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-issue2-chain-'))
9
+ process.env.DSH_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
11
+ process.env.DSH_MEMU_HOME = home
12
+
13
+ const state = await import('../lib/state.js')
14
+ const inject = await import('../lib/inject.js')
15
+ const rpc = await import('../lib/rpc.js')
16
+ const activity = await import('../lib/activity-log.js')
17
+ const { domainOf } = await import('../lib/memory.js')
18
+ const { loadPromptForDomain } = await import('../lib/prompts.js')
19
+
20
+ test.after(() => {
21
+ try { state.flushState() } catch { }
22
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch { }
23
+ })
24
+
25
+ // 「03_管理」:报告人的工作区名,不含任何 RP 关键词——detectDomain 判定为 coding。
26
+ const ws = path.join(home, '03_管理')
27
+ const RP_WS = path.join(home, '角色扮演-花园')
28
+
29
+ // 走生产的 pre-step 钩子路径(injectForStep + ensureUnifiedGuide),不是直接调
30
+ // 内部函数:guide 的投放与领域选择发生在钩子层,跳过它就不是「实际链路」。
31
+ const entries = []
32
+ {
33
+ const ctx = {
34
+ logger: { warn() { } },
35
+ inject() { },
36
+ on(event, fn) { entries.push({ event, fn }); return () => { } },
37
+ }
38
+ inject.registerInjection(ctx)
39
+ }
40
+ const preStep = entries.find((entry) => entry.event === 'agent/pre-step')
41
+ assert.ok(preStep, 'registerInjection must register the agent/pre-step listener')
42
+
43
+ const userText = (sessionId, text) => ({
44
+ id: sessionId + '-user-1',
45
+ role: 'user',
46
+ source: { kind: 'user' },
47
+ content: [{ type: 'text', text }],
48
+ })
49
+ const sessionEvent = entries.find((entry) => entry.event === 'session/event')
50
+ assert.ok(sessionEvent, 'registerInjection must register the session/event listener')
51
+ const sessions = new Map()
52
+ async function firstTurn(sessionId, cwd, text = '帮我整理一下这个月的待办') {
53
+ const session = { header: { id: sessionId, cwd, agentPreset: null, origin: 'user' }, messages: [] }
54
+ sessions.set(sessionId, session)
55
+ const out = await preStep.fn({
56
+ agent: { session },
57
+ turn: 1,
58
+ step: 1,
59
+ signal: { aborted: false },
60
+ }, async () => ({ kind: 'enter', messages: [userText(sessionId, text)] }))
61
+ assert.ok(!state.getSessionBinding(sessionId)?.guideRulesKey, 'a proposed guide is not yet admitted')
62
+ for (const message of out.messages) {
63
+ assert.ok(message.id && message.role === 'user', 'Native DSL requires an identified UserMessage')
64
+ if (!session.messages.some(item => item.id === message.id)) session.messages.push(message)
65
+ await sessionEvent.fn(session, { type: 'user/message', data: message })
66
+ }
67
+ return out
68
+ }
69
+ // 领域以真实入史的 guide 正文及 binding 的接纳记录交叉验证,不把 proposed 日志当成功。
70
+ function guideDomainOf(sessionId) {
71
+ const binding = state.getSessionBinding(sessionId)
72
+ const guide = sessions.get(sessionId)?.messages.find(message =>
73
+ message.source?.kind === 'plugin:dsh-memu-memory' && message.content?.[0]?.text?.startsWith('<memory-guide'))
74
+ assert.ok(guide, 'the guide must exist in host history')
75
+ assert.ok(binding.acceptedMemoryMessages?.some(record => record.messageId === guide.id && record.admittedAt),
76
+ 'the actual guide must have an admitted binding record')
77
+ const text = guide.content[0].text
78
+ assert.equal(/^<memory-guide rules="([^"]+)"/.exec(text)?.[1], binding.guideRulesKey)
79
+ const domain = domainOf(binding)
80
+ const settings = state.getSettings()
81
+ const rendered = loadPromptForDomain('system-guide', {
82
+ mustRememberCap: settings.mustRememberCap,
83
+ unpinBudget: settings.unpinBudgetPerSession ?? 2,
84
+ shortTermTtlHours: settings.shortTermTtlHours ?? 72,
85
+ anchorTokens: settings.anchorTokens,
86
+ turnTokens: settings.turnTokens,
87
+ }, domain).text.trim()
88
+ assert.ok(text.includes(rendered), 'the admitted guide content must match the binding domain')
89
+ return domain
90
+ }
91
+
92
+ test('新建会话:空白、无绑定,弹窗有权询问', async () => {
93
+ const st = await rpc.dispatch({}, 'getSessionPromptState', { sessionId: 'issue2-s1', cwd: ws })
94
+ assert.equal(st.binding, null, 'a fresh blank session must arrive unbound')
95
+ assert.equal(st.shouldPrompt, true)
96
+ assert.equal(st.settings.newSessionPromptDismissed, false)
97
+ })
98
+
99
+ test('重复只读检查不会创建会话绑定', async () => {
100
+ const st = await rpc.dispatch({}, 'getSessionPromptState', { sessionId: 'issue2-s1', cwd: ws })
101
+ assert.equal(st.binding, null, '稍后 must not write anything server-side')
102
+ })
103
+
104
+ test('首条消息:注入路径隐式建绑定,领域跟随 detectDomain 而不是硬编码 rp', async () => {
105
+ const out = await firstTurn('issue2-s1', ws)
106
+ assert.ok(Array.isArray(out.messages) && out.messages.length, 'the first turn injected nothing')
107
+ assert.ok(out.messages.some((message) => (message.content || []).some((part) => part?.type === 'text' && String(part.text).startsWith('<memory-guide'))),
108
+ 'the rules message was not delivered on the first turn')
109
+ const binding = state.getSessionBinding('issue2-s1')
110
+ assert.ok(binding, 'the injection path did not bind the session')
111
+ assert.equal(binding.domainOverride, 'coding',
112
+ 'an unasked conversation in 03_管理 must not start on the RP track (issue #2)')
113
+ assert.equal(binding.domainSource, 'auto', 'nobody answered yet: the binding stays implicit')
114
+ assert.equal(guideDomainOf('issue2-s1'), 'coding', 'the injected guide variant must match the binding domain')
115
+ })
116
+
117
+ test('隐式绑定可读取,显式领域确认写入 chosen 凭据', async () => {
118
+ const st = await rpc.dispatch({}, 'getSessionPromptState', { sessionId: 'issue2-s1', cwd: ws })
119
+ assert.equal(st.binding.domainSource, 'auto', 'the binding must still look implicit')
120
+ await rpc.dispatch({}, 'initSession', { sessionId: 'issue2-s1', cwd: ws, createLibrary: true })
121
+ await rpc.dispatch({}, 'setSessionScope', { sessionId: 'issue2-s1', useLibrary: true, useGlobal: true })
122
+ await rpc.dispatch({}, 'setDomain', { sessionId: 'issue2-s1', domain: 'coding' })
123
+ const answered = state.getSessionBinding('issue2-s1')
124
+ assert.equal(answered.domainOverride, 'coding')
125
+ assert.equal(answered.domainSource, 'chosen', 'an explicit answer must leave the chosen marker')
126
+
127
+ const after = await rpc.dispatch({}, 'getSessionPromptState', { sessionId: 'issue2-s1', cwd: ws })
128
+ assert.equal(after.binding.domainSource, 'chosen', 'the gate reads the chosen marker back')
129
+ })
130
+
131
+ test('RP 工作区名仍判为 rp:detectDomain 的判定口径没有松动', async () => {
132
+ await firstTurn('issue2-rp', RP_WS)
133
+ const binding = state.getSessionBinding('issue2-rp')
134
+ assert.equal(binding.domainOverride, 'rp', 'an RP-named folder must keep the RP track')
135
+ assert.equal(guideDomainOf('issue2-rp'), 'rp')
136
+ })
137
+
138
+ test('显式选择 general 也是真实选项,不会被 detectDomain 冲掉', async () => {
139
+ await firstTurn('issue2-general', ws)
140
+ await rpc.dispatch({}, 'setDomain', { sessionId: 'issue2-general', domain: 'general' })
141
+ const binding = state.getSessionBinding('issue2-general')
142
+ assert.equal(binding.domainOverride, 'general')
143
+ assert.equal(binding.domainSource, 'chosen')
144
+ // 重走 ensureSession(每一轮注入都会跑):显式答案必须存活。
145
+ const rebound = state.ensureSession('issue2-general', { cwd: ws, createLibrary: false })
146
+ assert.equal(rebound.domainOverride, 'general')
147
+ assert.equal(rebound.domainSource, 'chosen')
148
+ })
149
+
150
+ test('RPC 失败不再被当成已答,错误经 logClientEvent 落入活动日志', async () => {
151
+ const result = await rpc.dispatch({}, 'logClientEvent', {
152
+ sessionId: 'issue2-s1',
153
+ kind: 'error',
154
+ message: '新会话记忆询问检查失败,本轮跳过',
155
+ detail: 'Error: rpc failed: getSessionPromptState',
156
+ })
157
+ assert.ok(result.entry?.id, 'logClientEvent returned no entry')
158
+ const events = activity.listEvents({ sessionId: 'issue2-s1', limit: 10 })
159
+ assert.ok(events.some((event) => event.kind === 'error' && event.message.includes('新会话记忆询问检查失败')),
160
+ 'the client-side failure is missing from the activity log')
161
+ // 奇异输入也不抛错——日志失败不能雪上加霜。
162
+ const odd = await rpc.dispatch({}, 'logClientEvent', {})
163
+ assert.ok(odd.entry?.id)
164
+ })
165
+
166
+ test('bindingView 把 domainSource 带给客户端(WebUI 与侧栏的读取口径)', async () => {
167
+ const st = await rpc.dispatch({}, 'getState', { sessionId: 'issue2-s1' })
168
+ assert.equal(st.binding.domainSource, 'chosen')
169
+ })
@@ -5,6 +5,8 @@ import os from 'node:os'
5
5
  import path from 'node:path'
6
6
 
7
7
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-lexicon-inject-'))
8
+ process.env.DSH_HOME = home
9
+ process.env.DSH_MEMU_MEMORY_HOME = home
8
10
  process.env.DSH_MEMU_HOME = home
9
11
 
10
12
  const paths = await import('../lib/paths.js')
@@ -38,6 +40,22 @@ function agentFor(binding) {
38
40
  return { session: { header: { id: binding.sessionId, cwd: path.join(home, 'cwd-' + binding.sessionId), agentPreset: 'rp', origin: 'user' } } }
39
41
  }
40
42
 
43
+ function admissionHost(agent) {
44
+ agent.session.messages = []
45
+ const handlers = new Map()
46
+ const ctx = { logger: { warn() {} }, on(event, fn) { handlers.set(event, fn); return () => {} } }
47
+ inject.registerInjection(ctx)
48
+ const sessionEvent = handlers.get('session/event')
49
+ assert.equal(typeof sessionEvent, 'function')
50
+ return { ctx, async admit(out) {
51
+ for (const message of out.messages) {
52
+ assert.ok(message.id && message.role === 'user', 'Native DSL requires an identified UserMessage')
53
+ if (!agent.session.messages.some(item => item.id === message.id)) agent.session.messages.push(message)
54
+ await sessionEvent(agent.session, { type: 'user/message', data: message })
55
+ }
56
+ } }
57
+ }
58
+
41
59
  function userMessage(id, text) {
42
60
  return { id, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text }] }
43
61
  }
@@ -311,8 +329,9 @@ test('injectForStep appends the anchor lexicon summary and the B-channel hit blo
311
329
  batch: { type: inbound.INBOUND_TYPE, version: 1, producer: 'host.user', batchId: 'user:u1',
312
330
  messages: [{ id: 'u1', role: 'user', context: {}, content: [{ type: 'text', text: '这段太糖刀了' }] }] },
313
331
  })
332
+ const host = admissionHost(agent)
314
333
  const decision = { kind: 'enter', messages: [userMessage('u1', '这段太糖刀了')] }
315
- const out = await inject.injectForStep({ agent, decision, turn: 1, step: 1, signal: { aborted: false }, log: () => {}, ctx: null })
334
+ const out = await inject.injectForStep({ agent, decision, turn: 1, step: 1, signal: { aborted: false }, log: () => {}, ctx: host.ctx })
316
335
  const texts = pluginTexts(out)
317
336
  assert.equal(texts.length, 1, 'one plugin message carries anchor + lexicon')
318
337
  assert.match(texts[0], /===== memory anchor/)
@@ -322,9 +341,13 @@ test('injectForStep appends the anchor lexicon summary and the B-channel hit blo
322
341
  assert.match(texts[0], /<memory-lexicon>/, 'the B-channel hit block is in the same message')
323
342
  assert.match(texts[0], /糖刀」:表面发糖、实际虐心/)
324
343
 
325
- // 注入记账:candidate + injection 各一次,冷却已记。
326
344
  const lib = binding.libraryId
327
- const [entryId, entry] = Object.entries(lexicon.loadLexicon(lib).terms).find(([, t]) => t.normalizedTerm === '糖刀')
345
+ const [entryId, proposedEntry] = Object.entries(lexicon.loadLexicon(lib).terms).find(([, t]) => t.normalizedTerm === '糖刀')
346
+ assert.equal(proposedEntry.hitCounts.injection, 0, 'unadmitted output must not count as injection')
347
+ assert.equal(lexicon.lexiconOnCooldown(binding.sessionId, entryId), false, 'unadmitted output must not start cooldown')
348
+ await host.admit(out)
349
+ // 真实接纳后:candidate + injection 各一次,冷却已记。
350
+ const entry = lexicon.loadLexicon(lib).terms[entryId]
328
351
  assert.deepEqual(entry.hitCounts, { candidate: 1, injection: 1, query: 0 })
329
352
  assert.ok(lexicon.lexiconOnCooldown(binding.sessionId, entryId))
330
353
  })
@@ -332,13 +355,16 @@ test('injectForStep appends the anchor lexicon summary and the B-channel hit blo
332
355
  test('the second turn inside the cooldown window injects no lexicon block but still counts candidates', async () => {
333
356
  const binding = setupSession('e2e-cooldown', { terms: [{ term: '冷却验证词', kind: 'term', meaning: '含义' }] })
334
357
  const agent = agentFor(binding)
358
+ const host = admissionHost(agent)
335
359
  const send = async (id, text, turn) => {
336
360
  inbound.ingestInboundBatch({
337
361
  sessionId: binding.sessionId, session: agent.session, ctx: null,
338
362
  batch: { type: inbound.INBOUND_TYPE, version: 1, producer: 'host.user', batchId: `user:${id}`,
339
363
  messages: [{ id, role: 'user', context: {}, content: [{ type: 'text', text }] }] },
340
364
  })
341
- return inject.injectForStep({ agent, decision: { kind: 'enter', messages: [userMessage(id, text)] }, turn, step: 1, signal: { aborted: false }, log: () => {}, ctx: null })
365
+ const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [userMessage(id, text)] }, turn, step: 1, signal: { aborted: false }, log: () => {}, ctx: host.ctx })
366
+ await host.admit(out)
367
+ return out
342
368
  }
343
369
  await send('c1', '关于冷却验证词', 1)
344
370
  const second = await send('c2', '再说一次冷却验证词', 2)
@@ -353,12 +379,14 @@ test('the second turn inside the cooldown window injects no lexicon block but st
353
379
  test('the B channel also rides the real inbound batch path', async () => {
354
380
  const binding = setupSession('e2e-bridge', { terms: [{ term: '糖刀', kind: 'meme', meaning: '表面发糖、实际虐心' }] })
355
381
  const agent = agentFor(binding)
382
+ const host = admissionHost(agent)
356
383
  inbound.ingestInboundBatch({
357
384
  sessionId: binding.sessionId, session: agent.session, ctx: null,
358
385
  batch: { type: inbound.INBOUND_TYPE, version: 1, producer: 'friend-app', batchId: 'bridge:1',
359
386
  messages: [{ id: 'bridge-1', role: 'user', context: {}, content: [{ type: 'text', text: '这段太糖刀了' }] }] },
360
387
  })
361
- const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [] }, turn: 1, step: 1, signal: { aborted: false }, log: () => {}, ctx: null })
388
+ const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [] }, turn: 1, step: 1, signal: { aborted: false }, log: () => {}, ctx: host.ctx })
389
+ await host.admit(out)
362
390
  const texts = pluginTexts(out)
363
391
  assert.equal(texts.length, 1)
364
392
  assert.match(texts[0], /<memory-lexicon>/)