dsh-memu-memory 1.3.7 → 1.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +70 -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/host-adaptation.md +1 -1
  8. package/docs/memory-semantics.md +7 -6
  9. package/docs/troubleshooting.md +74 -7
  10. package/lib/auto-link/decide.js +0 -4
  11. package/lib/binding-diagnostics.js +2 -2
  12. package/lib/client.js +150 -81
  13. package/lib/consolidation-ledger.js +6 -2
  14. package/lib/curator.js +42 -10
  15. package/lib/cycle.js +28 -3
  16. package/lib/inbound.js +24 -9
  17. package/lib/inject.js +379 -215
  18. package/lib/local-vector-service.js +1 -10
  19. package/lib/memory.js +704 -181
  20. package/lib/paths.js +24 -0
  21. package/lib/private.js +294 -134
  22. package/lib/rpc.js +53 -6
  23. package/lib/snippet.js +49 -28
  24. package/lib/state.js +185 -26
  25. package/lib/tools.js +137 -28
  26. package/lib/webui.js +25 -1
  27. package/lib/worker-pool.js +260 -26
  28. package/package.json +1 -1
  29. package/scripts/check-i18n.mjs +19 -0
  30. package/scripts/recall-bench.mjs +4 -4
  31. package/scripts/simulate-injection.mjs +3 -0
  32. package/tests/activity-wiring.test.mjs +52 -0
  33. package/tests/client-render.test.mjs +207 -0
  34. package/tests/consolidation-feed.test.mjs +26 -0
  35. package/tests/consolidation-fork.test.mjs +587 -26
  36. package/tests/cross-library-recall.test.mjs +156 -0
  37. package/tests/cue.test.mjs +15 -2
  38. package/tests/curator-contract.test.mjs +191 -0
  39. package/tests/curator-probe.test.mjs +5 -5
  40. package/tests/curator.test.mjs +3 -1
  41. package/tests/hybrid-recall.test.mjs +488 -0
  42. package/tests/inbound.test.mjs +49 -4
  43. package/tests/inject-conflict.test.mjs +70 -9
  44. package/tests/inject-guide.test.mjs +13 -1
  45. package/tests/inject.test.mjs +10 -0
  46. package/tests/injection-budget.test.mjs +101 -0
  47. package/tests/injection-chain.test.mjs +37 -0
  48. package/tests/injection-rollback.test.mjs +172 -9
  49. package/tests/issue2-chain.test.mjs +169 -0
  50. package/tests/lexicon-inject.test.mjs +33 -5
  51. package/tests/managed-memory.test.mjs +625 -1
  52. package/tests/media.test.mjs +1 -1
  53. package/tests/new-session-gate.test.mjs +280 -25
  54. package/tests/open-loop-date.test.mjs +11 -1
  55. package/tests/recall-intent.test.mjs +52 -3
  56. package/tests/regression-sweep.test.mjs +281 -0
  57. package/tests/simulate-injection.test.mjs +4 -4
  58. package/tests/snippet.test.mjs +33 -1
  59. package/tests/state.test.mjs +8 -3
  60. package/tests/tool-schema.test.mjs +52 -0
  61. package/tests/tools.test.mjs +394 -0
  62. package/tests/webui.test.mjs +16 -2
  63. package/tests/worker-lifecycle.test.mjs +419 -36
@@ -5,7 +5,9 @@ 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-conflict-inject-'))
8
+ process.env.DSH_HOME = home
8
9
  process.env.DSH_MEMU_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
9
11
 
10
12
  const state = await import('../lib/state.js')
11
13
  const memory = await import('../lib/memory.js')
@@ -40,10 +42,15 @@ test('a recalled conflict brings both sides and one compact card', async () => {
40
42
  factKey: 'home:living_floor_color', absoluteDate: '2026-11-05',
41
43
  })
42
44
 
43
- const recalled = await memory.privateRecall({ exec, query: '客厅地板颜色是什么', topK: 1, relevanceThreshold: 0 })
45
+ const recalled = await memory.privateRecall({ exec, query: '客厅地板颜色是什么', topK: 1, relevanceThreshold: 0, purpose: 'automatic' })
44
46
  const ids = recalled.files.map((file) => file.name)
45
47
  assert.ok(ids.includes(left.id) && ids.includes(right.id), 'topK=1 still yields the pair, not half a contradiction')
46
48
  assert.equal(recalled.conflictPairs.length, 1)
49
+ const explicit = await memory.privateRecall({ exec, query: '客厅地板颜色是什么', topK: 1, relevanceThreshold: 0 })
50
+ assert.equal(explicit.files.length, 1, 'explicit topK=1 returns one body, not a conflict pair')
51
+ assert.equal(explicit.files[0].conflictComplete, false)
52
+ assert.equal(explicit.files[0].related.find(item => item.kind === 'conflict')?.complete, false)
53
+ assert.ok(!explicit.files[0].related.find(item => item.kind === 'conflict')?.content)
47
54
 
48
55
  const binding = state.getSessionBinding(sessionId)
49
56
  const build = await inject.buildRecall(binding, '客厅地板颜色是什么', 1, {
@@ -89,7 +96,7 @@ test('the card orders sides by local authority and observed time', () => {
89
96
  assert.match(newer, /- A \[mem-new\]/, 'equal authority falls back to the newer observation')
90
97
  })
91
98
 
92
- test('a conflict card that cannot fit falls back to the ordinary title cards', async () => {
99
+ test('a conflict card that cannot fit is omitted atomically, never shown as one ordinary version', async () => {
93
100
  const { exec, sessionId } = session('conflict-budget')
94
101
  const longTitle = '非常长的旅行目的地描述'.repeat(8)
95
102
  const longKey = 'trip:' + 'x'.repeat(180)
@@ -100,13 +107,67 @@ test('a conflict card that cannot fit falls back to the ordinary title cards', a
100
107
  exec, title: longTitle + '乙', content: '说好不去冰岛,去挪威。', factKey: longKey,
101
108
  })
102
109
  const binding = state.getSessionBinding(sessionId)
103
- // The card's fact_key + two long titles cannot fit; a one-line title card still can.
104
110
  const build = await inject.buildRecall(binding, '旅行目的地', 1, {
105
- ...state.getSettings(), privateTopK: 5, relevanceThreshold: 0, turnTokens: 110,
111
+ ...state.getSettings(), privateTopK: 5, relevanceThreshold: 0, turnTokens: 50,
106
112
  }, exec, sessionId)
107
- assert.deepEqual(build.errors, [])
108
- assert.equal(build.text.includes('冲突 ·'), false)
109
- assert.ok(build.text.length > 0)
110
- assert.ok(build.ids.length >= 1)
111
- assert.ok([left.id, right.id].some((id) => build.text.includes(`[${id}]`)))
113
+ assert.equal(build.text, '')
114
+ assert.deepEqual(build.ids, [])
115
+ assert.deepEqual(build.refs, [])
116
+ assert.equal(build.counts.budgetOmittedGroups, 1)
117
+ assert.ok(!build.text.includes(`[${left.id}]`) && !build.text.includes(`[${right.id}]`))
118
+ })
119
+
120
+ test('a compact conflict group preserves both ids and uncertainty within the token budget', async () => {
121
+ const { exec, sessionId } = session('compact-pair')
122
+ const a = await memory.privateRemember({ exec, title: '长标题'.repeat(30), content: '计划去冰岛。', factKey: 'trip:' + 'x'.repeat(160) })
123
+ const b = await memory.privateRemember({ exec, title: '长标题乙'.repeat(30), content: '计划改去挪威。', factKey: 'trip:' + 'x'.repeat(160) })
124
+ const build = await inject.buildRecall(state.getSessionBinding(sessionId), '计划旅行', 1, { ...state.getSettings(), privateTopK: 1, turnTokens: 110, relevanceThreshold: 0 }, exec, sessionId)
125
+ assert.match(build.text, /未确认哪版为准/)
126
+ assert.ok(build.text.includes(`[${a.id}]`) && build.text.includes(`[${b.id}]`))
127
+ assert.equal(build.groups.length, 1)
128
+ assert.equal(build.refs.length, 2)
129
+ assert.ok(estTokens(build.text) <= 110)
130
+ })
131
+
132
+ test('an unavailable conflict version is explicitly uncertain and does not disclose its title', async () => {
133
+ const { exec, sessionId } = session('invisible-version')
134
+ const binding = state.getSessionBinding(sessionId)
135
+ state.savePrivateIndex(binding.libraryId, { entries: {
136
+ 'mem-visible-version': { title: '客厅地板颜色记录', content: '客厅地板是木色。', layer: 'long_term', status: 'active', strength: 1, conflicts_with: 'mem-invisible-version' },
137
+ 'mem-invisible-version': { title: '不能泄露的版本标题', content: '另一个私密版本内容', layer: 'long_term', status: 'active', strength: 1, visibility: 'secret', conflicts_with: 'mem-visible-version' },
138
+ } })
139
+ const build = await inject.buildRecall(binding, '客厅地板颜色', 1, { ...state.getSettings(), privateTopK: 1, relevanceThreshold: 0, turnTokens: 800 }, exec, sessionId)
140
+ assert.match(build.text, /不可见\/不可用版本/)
141
+ assert.match(build.text, /未确认哪版为准/)
142
+ assert.ok(!build.text.includes('不能泄露') && !build.text.includes('私密版本内容'))
143
+ assert.deepEqual(build.refs.map(ref => ref.id), ['mem-visible-version'])
144
+ assert.equal(build.groups[0].complete, false)
145
+ })
146
+
147
+ test('a changed conflict member reintroduces the complete group even when its partner was seen', async () => {
148
+ const { exec, sessionId } = session('changed-conflict')
149
+ const a = await memory.privateRemember({ exec, title: '客厅地板木色', content: '客厅地板是木色。', factKey: 'floor:color' })
150
+ const b = await memory.privateRemember({ exec, title: '客厅地板灰色', content: '客厅地板是灰色。', factKey: 'floor:color' })
151
+ const binding = state.getSessionBinding(sessionId)
152
+ const initial = await memory.privateRecall({ exec, query: '客厅地板', topK: 1, relevanceThreshold: 0, purpose: 'automatic' })
153
+ state.markInjectedRefs(sessionId, initial.refs, 1, { messageId: 'admitted-conflict-before-change', hostTurn: 1 })
154
+ state.updatePrivateIndex(binding.libraryId, index => { index.entries[b.id].content += ' 后来确认使用瓷砖。' })
155
+ const result = await memory.privateRecall({ exec, query: '客厅地板', topK: 1, relevanceThreshold: 0, purpose: 'automatic', excludedRefs: state.recentMemoryRefs(state.getSessionBinding(sessionId), 2, 16) })
156
+ assert.deepEqual(new Set(result.files.map(file => file.name)), new Set([a.id, b.id]))
157
+ assert.equal(result.groups.length, 1)
158
+ assert.equal(result.groups[0].reintroducedForConflict, true)
159
+ assert.equal(result.trace.counts.selectedRows, 2)
160
+ assert.equal(result.trace.counts.selectedGroups, 1)
161
+ })
162
+
163
+ test('large conflict cycles are bounded and omitted instead of splitting a fact into ordinary versions', async () => {
164
+ const { exec, sessionId } = session('large-conflict-cycle')
165
+ const binding = state.getSessionBinding(sessionId)
166
+ const entries = {}
167
+ for (let i = 0; i < 9; i++) entries['mem-cycle-' + i] = { title: '冲突链节点' + i, content: '冲突关系的第' + i + '个版本', layer: 'long_term', status: 'active', strength: 1, conflicts_with: 'mem-cycle-' + ((i + 1) % 9) }
168
+ state.savePrivateIndex(binding.libraryId, { entries })
169
+ const result = await memory.privateRecall({ exec, query: '冲突关系', topK: 2, relevanceThreshold: 0, purpose: 'automatic' })
170
+ assert.deepEqual(result.files, [])
171
+ assert.equal(result.trace.counts.oversizedGroups, 1)
172
+ assert.equal(result.omittedGroups[0].members, 9)
112
173
  })
@@ -9,7 +9,9 @@ import path from 'node:path'
9
9
  // plugin section; rulesKey decides when the message must be replaced or restored.
10
10
 
11
11
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-guide-'))
12
+ process.env.DSH_HOME = home
12
13
  process.env.DSH_MEMU_HOME = home
14
+ process.env.DSH_MEMU_MEMORY_HOME = home
13
15
 
14
16
  const state = await import('../lib/state.js')
15
17
  const inject = await import('../lib/inject.js')
@@ -44,7 +46,17 @@ function mountGuide() {
44
46
  ctx,
45
47
  logger,
46
48
  entries,
47
- run(payload, decision) { return pre.fn(payload, async () => decision) },
49
+ async run(payload, decision) {
50
+ const out = await pre.fn(payload, async () => decision)
51
+ const handler = entries.find(entry => entry.event === 'session/event')
52
+ const history = payload.agent.session.messages ||= []
53
+ for (const message of out?.messages || []) {
54
+ if (history.some(item => item.id === message.id)) continue
55
+ history.push(message)
56
+ if (message.role === 'user') await handler.fn(payload.agent.session, { type: 'user/message', data: message })
57
+ }
58
+ return out
59
+ },
48
60
  async compact(sessionId) {
49
61
  const handler = entries.find((entry) => entry.event === 'session/event')
50
62
  assert.ok(handler, 'registerInjection must listen for compaction events')
@@ -5,7 +5,9 @@ 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-inject-'))
8
+ process.env.DSH_HOME = home
8
9
  process.env.DSH_MEMU_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
9
11
 
10
12
  const state = await import('../lib/state.js')
11
13
  const inject = await import('../lib/inject.js')
@@ -208,6 +210,14 @@ test('pre-step inserts a plugin message before the user message', async () => {
208
210
  assert.ok(injected.includes('Deploy convention'), 'the title is what reaches the prompt')
209
211
  assert.equal(injected.includes('The deploy script lives in tools/deploy.ps1'), false,
210
212
  'the turn block is a title card; the body stays behind memu_private_recall')
213
+ assert.ok(!state.getSessionBinding('inject-step').injectedIds.includes('mem-recall'), 'returning a proposal is not admission')
214
+ const handlers = new Map()
215
+ inject.registerInjection({ on: (name, handler) => { handlers.set(name, handler); return () => {} }, logger: { warn() {} } })
216
+ agent.session.messages = []
217
+ for (const message of out.messages) {
218
+ agent.session.messages.push(message)
219
+ await handlers.get('session/event')(agent.session, { type: 'user/message', data: message })
220
+ }
211
221
  assert.ok(state.getSessionBinding('inject-step').injectedIds.includes('mem-recall'))
212
222
  assert.equal(state.getSessionBinding('inject-step').lastRecallError, undefined)
213
223
 
@@ -5,7 +5,9 @@ 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-injection-budget-'))
8
+ process.env.DSH_HOME = home
8
9
  process.env.DSH_MEMU_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
9
11
 
10
12
  const state = await import('../lib/state.js')
11
13
  const inject = await import('../lib/inject.js')
@@ -62,3 +64,102 @@ test('turnTokens stays the recall budget while injectionTotalTokens gates the wh
62
64
  assert.ok(used <= 2000, 'used ' + used)
63
65
  assert.ok(used <= 640 + 200, 'the recall block is capped by turnTokens, not the total: ' + used)
64
66
  })
67
+
68
+ test('budget-omitted display callbacks never mark unseen entries, dates or nudges', async () => {
69
+ const id = 'budget-callbacks'
70
+ const cwd = path.join(home, id)
71
+ const binding = state.ensureSession(id, { cwd, agentPreset: 'coding' })
72
+ state.setSessionBinding(id, { useGlobal: false })
73
+ const previous = state.getSettings()
74
+ state.updateSettings({ autoInject: 'anchor-only', anchorTokens: 300, injectionTotalTokens: 300, randomCueChance: 0, habitsInjection: false })
75
+ const now = new Date()
76
+ const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
77
+ state.updatePrivateIndex(binding.libraryId, index => {
78
+ for (let i = 0; i < 16; i++) index.entries[`mem-callback-${i}`] = { title: `永久记忆 ${i}`, content: 'only the title may display', track: 'memory',
79
+ layer: 'must_remember', status: 'active', strength: 1 - i / 20, createdAt: now.toISOString(), updatedAt: now.toISOString() }
80
+ index.entries['mem-callback-due'] = { title: '到期承诺'.repeat(150), content: 'not displayed', track: 'memory', layer: 'long_term', status: 'active',
81
+ salientDate: today, openLoop: true, createdAt: new Date(Date.now() - 5 * 86400000).toISOString(), updatedAt: now.toISOString() }
82
+ })
83
+ const turn = makeTurn(id, { cwd, agentPreset: 'coding', text: '请继续' })
84
+ const out = await inject.injectForStep({ agent: turn.agent, decision: turn.decision, turn: 1, step: 1 })
85
+ assert.ok(pluginMessages(out.messages).length > 0)
86
+ assert.equal((state.getSessionBinding(id).acceptedMemoryMessages || []).length, 0, 'nothing accepted before append')
87
+ const handlers = new Map()
88
+ inject.registerInjection({ on: (topic, fn) => { handlers.set(topic, fn); return () => {} }, logger: { warn() {} } })
89
+ turn.agent.session.messages = []
90
+ for (const message of out.messages) {
91
+ turn.agent.session.messages.push(message)
92
+ await handlers.get('session/event')(turn.agent.session, { type: 'user/message', data: message })
93
+ }
94
+ const accepted = state.getSessionBinding(id)
95
+ const text = pluginText(out.messages)
96
+ assert.ok(budget.estTokens(text) <= 300)
97
+ const refs = accepted.acceptedMemoryMessages.flatMap(record => record.refs)
98
+ assert.ok(refs.length > 0 && refs.length < 16)
99
+ for (const ref of refs) assert.ok(text.includes(`[${ref.id}]`))
100
+ const entries = state.loadPrivateIndex(binding.libraryId).entries
101
+ for (const [entryId, entry] of Object.entries(entries)) {
102
+ assert.equal(Number(entry.injectCount || 0), refs.some(ref => ref.id === entryId) ? 1 : 0, `callback count follows displayed ${entryId}`)
103
+ }
104
+ assert.deepEqual(accepted.anniversariesShown || {}, {}, 'omitted date block never marks a day')
105
+ assert.deepEqual(accepted.openLoopRemindedAt || {}, {}, 'omitted nudge never starts a cooldown')
106
+ // A duplicate history notification cannot charge the display callbacks twice.
107
+ for (const message of pluginMessages(out.messages)) await handlers.get('session/event')(turn.agent.session, { type: 'user/message', data: message })
108
+ for (const ref of refs) assert.equal(state.loadPrivateIndex(binding.libraryId).entries[ref.id].injectCount, 1)
109
+ state.updateSettings(previous)
110
+ })
111
+
112
+ test('anchor uses one atomic shared conflict group across pin/core partitions', () => {
113
+ const id = 'budget-anchor-conflict'
114
+ const binding = state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
115
+ state.setSessionBinding(id, { useGlobal: false })
116
+ state.updatePrivateIndex(binding.libraryId, index => {
117
+ index.entries['mem-group-pin'] = { title: '部署使用旧路径', content: 'old body', status: 'active', layer: 'must_remember', conflicts_with: 'mem-group-core' }
118
+ index.entries['mem-group-core'] = { title: '部署使用新路径', content: 'new body', status: 'active', layer: 'long_term', conflicts_with: 'mem-group-pin' }
119
+ })
120
+ const anchor = inject.buildAnchor(state.getSessionBinding(id), { ...state.getSettings(), anchorTokens: 2000 }, id)
121
+ assert.match(anchor.text, /冲突/)
122
+ assert.match(anchor.text, /未确认哪版为准/)
123
+ assert.equal((anchor.text.match(/\[mem-group-pin\]/g) || []).length, 1)
124
+ assert.equal((anchor.text.match(/\[mem-group-core\]/g) || []).length, 1)
125
+ assert.equal(anchor.refs.length, 2)
126
+ assert.equal(anchor.refs[0].groupKey, anchor.refs[1].groupKey)
127
+ assert.equal(anchor.refs[0].groupRevision, anchor.refs[1].groupRevision)
128
+ const tiny = inject.buildAnchor(state.getSessionBinding(id), { ...state.getSettings(), anchorTokens: 160 }, id)
129
+ assert.equal(tiny.text.includes('[mem-group-pin]'), tiny.text.includes('[mem-group-core]'), 'a budget cannot publish a single certain side')
130
+ })
131
+
132
+ test('accepted replay restores context without renewing typed cooldown or inject callbacks', async () => {
133
+ const id = 'budget-replay-cooldown'
134
+ const cwd = path.join(home, id)
135
+ const binding = state.ensureSession(id, { cwd, agentPreset: 'coding' })
136
+ const memoryId = 'mem-replay-' + 'x'.repeat(140)
137
+ const entry = { title: '旧记忆', content: 'already shown body', status: 'active', layer: 'must_remember' }
138
+ state.updatePrivateIndex(binding.libraryId, index => { index.entries[memoryId] = entry })
139
+ const { memoryRef } = await import('../lib/paths.js')
140
+ state.setSessionBinding(id, { useGlobal: false })
141
+ state.markInjectedRefs(id, [memoryRef({ scope: 'private', libraryId: binding.libraryId, id: memoryId, entry })], 1, { messageId: 'replay-original', hostTurn: 1 })
142
+ state.setSessionBinding(id, { reinjectPending: true, replayIds: [memoryId] })
143
+ // Pin partition is too small for the whole id, while the independent replay fits.
144
+ const previous = state.getSettings()
145
+ state.updateSettings({ anchorTokens: 160, injectionTotalTokens: 400, randomCueChance: 0, habitsInjection: false })
146
+ try {
147
+ const turn = makeTurn(id, { cwd, agentPreset: 'coding', text: '请继续' })
148
+ const out = await inject.injectForStep({ agent: turn.agent, decision: turn.decision, turn: 2, step: 1 })
149
+ assert.ok(pluginText(out.messages).includes('[replay'))
150
+ assert.ok(pluginText(out.messages).includes(`[${memoryId}]`))
151
+ assert.deepEqual(state.getSessionBinding(id).replayIds, [memoryId], 'a proposed replay does not consume its IDs')
152
+ const handlers = new Map()
153
+ inject.registerInjection({ on: (topic, fn) => { handlers.set(topic, fn); return () => {} }, logger: { warn() {} } })
154
+ turn.agent.session.messages = []
155
+ for (const message of out.messages) {
156
+ turn.agent.session.messages.push(message)
157
+ await handlers.get('session/event')(turn.agent.session, { type: 'user/message', data: message })
158
+ }
159
+ const after = state.getSessionBinding(id)
160
+ assert.deepEqual(after.replayIds, [])
161
+ assert.deepEqual(after.acceptedMemoryMessages.at(-1).refs, [], 'replay is not a fresh typed display')
162
+ assert.equal(Number(state.loadPrivateIndex(binding.libraryId).entries[memoryId].injectCount || 0), 0)
163
+ assert.deepEqual(state.recentMemoryRefs(after, 17, 16), [], 'the original cooldown expires at its original clock')
164
+ } finally { state.updateSettings(previous) }
165
+ })
@@ -6,7 +6,9 @@ import path from 'node:path'
6
6
  import { fileURLToPath } from 'node:url'
7
7
 
8
8
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-chain-'))
9
+ process.env.DSH_HOME = home
9
10
  process.env.DSH_MEMU_HOME = home
11
+ process.env.DSH_MEMU_MEMORY_HOME = home
10
12
 
11
13
  const state = await import('../lib/state.js')
12
14
  const memory = await import('../lib/memory.js')
@@ -269,6 +271,7 @@ test('the hint ships in the same plugin message as the recall block', async () =
269
271
  const cwd = path.join(home, 'project-freshness-message')
270
272
  const binding = state.ensureSession('chain-freshness-message', { cwd, agentPreset: 'coding' })
271
273
  seedRecallEntry(binding, 'mem-fresh-message', { updatedAt: new Date(Date.now() - 45 * DAY_MS).toISOString() })
274
+ state.markInjected('chain-freshness-message', ['__anchor__'], 0)
272
275
 
273
276
  const user = {
274
277
  id: 'u-freshness', role: 'user', source: { kind: 'user' },
@@ -365,3 +368,37 @@ test('no recall means no freshness hint', async () => {
365
368
  assert.deepEqual(recall.ids, [])
366
369
  assert.equal(recall.text.includes('<memory-freshness>'), false)
367
370
  })
371
+
372
+ test('typed cooldown follows content revisions, library identity and a new injection epoch', async () => {
373
+ const id = 'chain-ref-revision'
374
+ const binding = state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
375
+ state.setSessionBinding(id, { useGlobal: false })
376
+ seedRecallEntry(binding, 'mem-shared-id')
377
+ const exec = { agent: { session: { header: { id, agentPreset: 'coding' } } } }
378
+ const settings = { ...state.getSettings(), relevanceThreshold: 0, dedupeTurns: 16 }
379
+ const first = await inject.buildRecall(state.getSessionBinding(id), '部署脚本的位置', 1, settings, exec, id)
380
+ assert.ok(first.refs?.some(ref => ref.id === 'mem-shared-id' && ref.libraryId === binding.libraryId), 'buildRecall returns typed refs')
381
+ state.markInjectedRefs(id, first.refs, 1, { messageId: 'revision-first', hostTurn: 1 })
382
+ const unchanged = await inject.buildRecall(state.getSessionBinding(id), '部署脚本的位置', 2, settings, exec, id)
383
+ assert.ok(!unchanged.ids.includes('mem-shared-id'), 'unchanged content is suppressed only after admission')
384
+ state.updatePrivateIndex(binding.libraryId, index => {
385
+ index.entries['mem-shared-id'].content = '改稿后的部署脚本放在 tools/deploy-v2.ps1。'
386
+ index.entries['mem-shared-id'].title = '部署脚本的位置新版'
387
+ })
388
+ const revised = await inject.buildRecall(state.getSessionBinding(id), '部署脚本的位置', 2, settings, exec, id)
389
+ assert.ok(revised.ids.includes('mem-shared-id'), 'same id with edited content is eligible immediately')
390
+ assert.notEqual(revised.refs.find(ref => ref.id === 'mem-shared-id').revision, first.refs.find(ref => ref.id === 'mem-shared-id').revision)
391
+ state.markInjectedRefs(id, revised.refs, 2, { messageId: 'revision-second', hostTurn: 2 })
392
+ const other = state.createLibrary({ name: 'same-id-other', scopeKey: path.join(home, 'other-ref-library') })
393
+ const { memoryRef, memoryRefKey } = await import('../lib/paths.js')
394
+ const otherRef = memoryRef({ scope: 'private', libraryId: other.id, id: 'mem-shared-id', entry: { title: 'same id in another library', content: 'independent body' } })
395
+ state.markInjectedRefs(id, [otherRef], 3, { messageId: 'revision-other', hostTurn: 3 })
396
+ const recent = state.recentMemoryRefs(state.getSessionBinding(id), 3, 16)
397
+ assert.equal(recent.length, 2)
398
+ assert.notEqual(memoryRefKey(recent[0]), memoryRefKey(recent[1]), 'two library owners cannot collapse into a bare id')
399
+ assert.equal(recent.find(ref => ref.libraryId === binding.libraryId).revision, revised.refs[0].revision)
400
+ state.markReinjectPending(id)
401
+ assert.deepEqual(state.recentMemoryRefs(state.getSessionBinding(id), 4, 16), [], 'old-epoch refs are not proof for a reinjection')
402
+ const reinjected = await inject.buildRecall(state.getSessionBinding(id), '部署脚本的位置', 4, settings, exec, id)
403
+ assert.ok(reinjected.ids.includes('mem-shared-id'))
404
+ })
@@ -9,7 +9,9 @@ import path from 'node:path'
9
9
  // 不再投,整段对话只是"记忆像没接上",一句错都不报。判据是本轮那几条注入消息到底进过转录没有:
10
10
  // 进过(请求已经发出去)就保住记账,没进过才撤回。这里把撤与不撤两面都钉住。
11
11
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-rollback-'))
12
+ process.env.DSH_HOME = home
12
13
  process.env.DSH_MEMU_HOME = home
14
+ process.env.DSH_MEMU_MEMORY_HOME = home
13
15
 
14
16
  const state = await import('../lib/state.js')
15
17
  const inject = await import('../lib/inject.js')
@@ -67,6 +69,15 @@ async function step(session, turn, messages) {
67
69
  return out?.messages || messages
68
70
  }
69
71
 
72
+ async function accept(session, messages) {
73
+ const history = session.messages ||= []
74
+ for (const message of messages) {
75
+ if (history.some(item => item.id === message.id)) continue
76
+ history.push(message)
77
+ if (message.role === 'user') await sessionEvent({ header: { id: session.id } }, { type: 'user/message', data: message })
78
+ }
79
+ }
80
+
70
81
  function failTurn(session, turn) {
71
82
  return sessionEvent(
72
83
  { header: { id: session.id } },
@@ -94,7 +105,10 @@ test('a failed turn gives back the one-shot accounting, and the next turn re-pla
94
105
  assert.equal(countWith(first, GUIDE_RE), 1, 'turn 1 places the guide')
95
106
  assert.equal(countWith(first, ANCHOR_RE), 1, 'turn 1 places the anchor')
96
107
  const placed = facts(session.id)
97
- assert.ok(placed.guide && placed.anchor && placed.injected > 0, 'the accounting says everything was delivered')
108
+ assert.equal(placed.guide, null, 'the returned guide is only proposed')
109
+ assert.equal(placed.anchor, false, 'the returned anchor is only proposed')
110
+ assert.equal(placed.injected, 0, 'unadmitted refs do not enter history')
111
+ assert.deepEqual(session.messages || [], [], 'Native history is still empty')
98
112
 
99
113
  await failTurn(session, 1)
100
114
  const rolled = facts(session.id)
@@ -102,9 +116,9 @@ test('a failed turn gives back the one-shot accounting, and the next turn re-pla
102
116
  assert.equal(rolled.anchor, false, 'anchor sentinel rolled back')
103
117
  assert.equal(rolled.injected, 0, 'the recall ids of that turn are forgotten too')
104
118
  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')
119
+ assert.ok(warns.some((line) => /discarded .* unadmitted injection proposals/.test(line)), 'discarding proposals leaves a log signal')
106
120
  const events = activity.listEvents({ limit: 50, kind: 'system' })
107
- assert.ok(events.some((event) => event.sessionId === session.id && /已撤回本轮的注入记账/.test(event.message || '')),
121
+ assert.ok(events.some((event) => event.sessionId === session.id && /未接纳的记忆提案已丢弃/.test(event.message || '')),
108
122
  'and an activity-log row explains what happened')
109
123
 
110
124
  // 下一轮:宿主给的转录里没有任何一次性的东西,必须重新投出来。
@@ -117,6 +131,7 @@ test('a completed turn keeps its accounting, so nothing is re-placed', async ()
117
131
  const session = makeSession('rb-ok')
118
132
  const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
119
133
  assert.equal(countWith(first, GUIDE_RE), 1)
134
+ await accept(session, first)
120
135
  await completeTurn(session, 1)
121
136
 
122
137
  const kept = facts(session.id)
@@ -133,7 +148,9 @@ test('a completed turn consumes its record, so a late error cannot un-place what
133
148
  const session = makeSession('rb-stale')
134
149
  const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
135
150
  assert.equal(countWith(first, GUIDE_RE), 1)
136
- assert.ok(facts(session.id).rollback, 'the turn that just delivered leaves a rollback record')
151
+ await accept(session, first)
152
+ assert.equal(state.getSessionBinding(session.id).acceptedMemoryMessages.length, 2, 'each accepted message has its own immutable record')
153
+ assert.equal(facts(session.id).rollback, null, 'proposals do not use legacy rollback accounting')
137
154
 
138
155
  await completeTurn(session, 1)
139
156
  const kept = facts(session.id)
@@ -164,7 +181,7 @@ test('a failure after the injection reached the transcript keeps the accounting'
164
181
 
165
182
  // 宿主在第一次尝试里就把 decision.messages 逐条追加进转录,之后才连模型。上游 500 / 超时
166
183
  // 属于这一类:内容已经在转录里,撤回记账只会让下一轮多出第二份规则消息与锚点。
167
- await sessionEvent({ header: { id: session.id } }, { type: 'user/message', data: injected })
184
+ await accept(session, first)
168
185
  await failTurn(session, 1)
169
186
  const kept = facts(session.id)
170
187
  assert.ok(kept.guide, 'the rules message stays accounted')
@@ -219,10 +236,11 @@ test('rollback also clears the day marks so dated blocks can return', async () =
219
236
  }
220
237
  })
221
238
 
222
- await step(session, 1, [user(1, '明天有什么我要办的事')])
239
+ const dated = await step(session, 1, [user(1, '明天有什么我要办的事')])
240
+ assert.ok(dated.some(message => /memory-due|open loop/.test(textOf(message))), 'dated blocks were proposed')
223
241
  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')
242
+ assert.equal(Object.keys(binding.anniversariesShown || {}).length, 0, 'unaccepted dated blocks do not mark a day')
243
+ assert.equal(Object.keys(binding.openLoopRemindedAt || {}).length, 0, 'unaccepted nudges do not start cooldown')
226
244
  await failTurn(session, 1)
227
245
  const after = state.getSessionBinding(session.id)
228
246
  assert.equal(Object.keys(after.anniversariesShown || {}).length, 0, 'the day mark is withdrawn with the turn')
@@ -232,6 +250,7 @@ test('rollback also clears the day marks so dated blocks can return', async () =
232
250
  test('the same real user message gets one injection pass when the host emits two enter decisions', async () => {
233
251
  const session = makeSession('dup-step')
234
252
  const first = await step(session, 221, [user(1, '林眠的相机镜头维修到哪一步了?')])
253
+ await accept(session, first)
235
254
  const afterFirst = state.getSessionBinding(session.id)
236
255
  assert.equal(afterFirst.lastInjectedUserMessageId, 'u-1', 'the first pass marks the message it handled')
237
256
  const clockAfterFirst = afterFirst.inbound?.clock
@@ -253,7 +272,7 @@ test('a rolled-back turn clears the one-pass marker so a real retry injects agai
253
272
  const session = makeSession('dup-retry')
254
273
  const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
255
274
  assert.equal(countWith(first, ANCHOR_RE), 1)
256
- assert.equal(state.getSessionBinding(session.id).lastInjectedUserMessageId, 'u-1')
275
+ assert.equal(state.getSessionBinding(session.id).lastInjectedUserMessageId, undefined, 'one-pass marker waits for history')
257
276
 
258
277
  await failTurn(session, 1)
259
278
  assert.equal(state.getSessionBinding(session.id).lastInjectedUserMessageId, undefined,
@@ -262,3 +281,147 @@ test('a rolled-back turn clears the one-pass marker so a real retry injects agai
262
281
  const retry = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
263
282
  assert.equal(countWith(retry, ANCHOR_RE), 1, 'the retry places the anchor again')
264
283
  })
284
+
285
+ for (const kind of ['completed', 'error', 'aborted', 'stopped']) test(`${kind} ends unadmitted proposals; a late exact message cannot revive them`, async () => {
286
+ const session = makeSession('end-' + kind)
287
+ const first = await step(session, 1, [user(kind, '林眠的相机镜头修好了吗')])
288
+ assert.equal(facts(session.id).injected, 0)
289
+ await sessionEvent({ header: { id: session.id } }, { type: 'turn/end', data: { turn: 1, reason: { kind } } })
290
+ for (const message of first.filter(item => item.source?.kind === 'plugin:dsh-memu-memory')) {
291
+ await sessionEvent({ header: { id: session.id } }, { type: 'user/message', data: message })
292
+ }
293
+ assert.equal(facts(session.id).guide, null)
294
+ assert.equal(facts(session.id).anchor, false)
295
+ assert.equal(facts(session.id).injected, 0)
296
+ assert.equal(state.getSessionBinding(session.id).inbound.pending.length, 1, 'unaccepted input stays retryable')
297
+ })
298
+
299
+ for (const acceptedPart of ['guide', 'recall']) test(`partial ${acceptedPart} admission never represents the other message`, async () => {
300
+ const session = makeSession('partial-' + acceptedPart)
301
+ const first = await step(session, 1, [user(acceptedPart, '林眠的相机镜头修好了吗')])
302
+ const plugin = first.filter(message => message.source?.kind === 'plugin:dsh-memu-memory')
303
+ const selected = plugin.find(message => GUIDE_RE.test(textOf(message)) === (acceptedPart === 'guide'))
304
+ await accept(session, [selected])
305
+ const before = facts(session.id)
306
+ assert.equal(Boolean(before.guide), acceptedPart === 'guide')
307
+ assert.equal(before.anchor, acceptedPart === 'recall')
308
+ assert.equal(state.getSessionBinding(session.id).inbound.pending.length, 1, 'the real human has not entered history')
309
+ await failTurn(session, 1)
310
+ const after = facts(session.id)
311
+ assert.deepEqual(after, before, 'model failure does not roll back admitted history')
312
+ const late = plugin.find(message => message.id !== selected.id)
313
+ await sessionEvent({ header: { id: session.id } }, { type: 'user/message', data: late })
314
+ assert.deepEqual(facts(session.id), after, 'discarded partial sibling cannot commit late')
315
+ })
316
+
317
+ test('proposal reuse preserves pre-human ordering and missing human projection without duplicate IDs', async () => {
318
+ const session = makeSession('projection')
319
+ const human = user('projection', '林眠的相机镜头修好了吗')
320
+ const first = await step(session, 1, [human])
321
+ const memory = first.find(message => ANCHOR_RE.test(textOf(message)))
322
+ const second = await step(session, 1, [human])
323
+ assert.equal(second.find(message => ANCHOR_RE.test(textOf(message))).id, memory.id)
324
+ assert.ok(second.findIndex(message => message.id === memory.id) < second.findIndex(message => message.id === human.id))
325
+ const missing = await step(session, 1, [])
326
+ assert.equal(missing.filter(message => message.id === human.id).length, 1, 'retry carries the pending human too')
327
+ assert.equal(missing.filter(message => message.id === memory.id).length, 1)
328
+ assert.ok(missing.findIndex(message => message.id === memory.id) < missing.findIndex(message => message.id === human.id))
329
+ await accept(session, [human])
330
+ const nativeAlready = await step(session, 1, [])
331
+ assert.equal(nativeAlready.some(message => message.id === human.id), false, 'a Native-admitted human is not appended twice')
332
+ assert.equal(nativeAlready.filter(message => message.id === memory.id).length, 1)
333
+ })
334
+
335
+ test('a reused proposal belongs to its latest turn without extending its original memory clock', async () => {
336
+ const session = makeSession('reused-turn-owner')
337
+ const human = user('turn-owner', '林眠的相机镜头修好了吗')
338
+ const first = await step(session, 1, [human])
339
+ const second = await step(session, 2, [human])
340
+ assert.equal(second.find(message => ANCHOR_RE.test(textOf(message))).id, first.find(message => ANCHOR_RE.test(textOf(message))).id)
341
+ await failTurn(session, 1)
342
+ await accept(session, second)
343
+ const binding = state.getSessionBinding(session.id)
344
+ assert.equal(binding.anchorPushed, true, 'a late old-turn end cannot discard the current owner')
345
+ assert.ok(binding.guideRulesKey)
346
+ assert.ok(binding.acceptedMemoryMessages.every(record => record.hostTurn === 2))
347
+ assert.ok(binding.acceptedMemoryMessages.every(record => record.memoryClock === 1), 'reusing does not extend cooldown')
348
+ })
349
+
350
+ test('digest/source mismatch and mutable returned bodies cannot commit a different proposal', async () => {
351
+ const session = makeSession('digest')
352
+ const first = await step(session, 1, [user('digest', '林眠的相机镜头修好了吗')])
353
+ const memory = first.find(message => ANCHOR_RE.test(textOf(message)))
354
+ await sessionEvent({ header: { id: session.id } }, { type: 'user/message', data: { ...memory, source: { kind: 'plugin:other' } } })
355
+ const altered = { ...memory, content: [{ type: 'text', text: 'not the proposed body' }] }
356
+ await sessionEvent({ header: { id: session.id } }, { type: 'user/message', data: altered })
357
+ assert.equal(facts(session.id).anchor, false)
358
+ const originalText = textOf(memory)
359
+ memory.content[0].text = 'caller-mutated returned proposal body'
360
+ const replay = await step(session, 1, [user('digest', '林眠的相机镜头修好了吗')])
361
+ assert.equal(textOf(replay.find(message => message.id === memory.id)), originalText, 'stored body remains an independent snapshot')
362
+ await accept(session, replay)
363
+ assert.equal(facts(session.id).anchor, true)
364
+ })
365
+
366
+ test('a turn ending while recall awaits cannot publish a late proposal', async () => {
367
+ const session = makeSession('inflight-end')
368
+ const pending = step(session, 1, [user('inflight', '林眠的相机镜头修好了吗')])
369
+ await completeTurn(session, 1)
370
+ const out = await pending
371
+ assert.equal(out.some(message => message.source?.kind === 'plugin:dsh-memu-memory'), false)
372
+ assert.equal(facts(session.id).injected, 0)
373
+ })
374
+
375
+ test('typed effects and refs are independent; late rollback never erases new owner counters', async () => {
376
+ const session = makeSession('owner-counters')
377
+ const ref = { scope: 'private', libraryId: state.getSessionBinding(session.id).libraryId, id: 'same', revision: 'r1', entry: { content: 'do not store body' } }
378
+ const actions = { patch: { replayIds: ['old'], textureKey: 'old', lastInjectedUserMessageId: 'old' }, anniversaries: { same: 'old-day' }, nudgeIds: ['same'] }
379
+ const one = state.markInjectedRefs(session.id, [ref], 1, { messageId: 'owner-old', hostTurn: 1, actions })
380
+ ref.revision = 'mutated'
381
+ actions.patch.replayIds.push('mutated')
382
+ one.effects.replayIds.value = ['mutated-return']
383
+ one.refs[0].revision = 'mutated-return'
384
+ const two = state.markInjectedRefs(session.id, [{ ...ref, revision: 'r2' }], 2, { messageId: 'owner-new', hostTurn: 2,
385
+ actions: { patch: { replayIds: ['new'], textureKey: 'new', lastInjectedUserMessageId: 'new' }, anniversaries: { same: 'new-day' }, nudgeIds: ['same'] } })
386
+ const before = state.getSessionBinding(session.id)
387
+ assert.equal(before.acceptedMemoryMessages[0].refs[0].revision, 'r1')
388
+ assert.equal(before.acceptedMemoryMessages[0].refs[0].entry, undefined)
389
+ assert.deepEqual(two.effects.replayIds.value, ['old'])
390
+ state.rollbackInjectionForTurn(session.id, 1, { messageIds: ['owner-old'] })
391
+ const after = state.getSessionBinding(session.id)
392
+ assert.deepEqual(after.replayIds, ['new'])
393
+ assert.equal(after.textureKey, 'new')
394
+ assert.equal(after.lastInjectedUserMessageId, 'new')
395
+ assert.equal(after.anniversariesShown.same, 'new-day')
396
+ assert.equal(after.openLoopRemindedAt.same, before.openLoopRemindedAt.same)
397
+ assert.equal(after.injectedAt.same, 2)
398
+ // A late older admission records history but cannot take ownership back.
399
+ state.markInjectedRefs(session.id, [ref], 1, { messageId: 'owner-late', hostTurn: 1, actions })
400
+ assert.equal(state.getSessionBinding(session.id).textureKey, 'new')
401
+ assert.equal(state.getSessionBinding(session.id).anniversariesShown.same, 'new-day')
402
+ })
403
+
404
+ test('same-value legacy rewrites and a new epoch protect markers from old rollback', () => {
405
+ const session = makeSession('legacy-owners')
406
+ state.markInjected(session.id, ['same', '__anchor__'], 1)
407
+ state.markAnniversaryShown(session.id, 'same', 'day')
408
+ state.markOpenLoopReminded(session.id, 'same')
409
+ state.setSessionBinding(session.id, { lastInjectedUserMessageId: 'human', guideRulesKey: 'rules', guideMessageAt: 'at' })
410
+ state.recordInjectionRollback(session.id, { hostTurn: 1, ids: ['same', '__anchor__'], guideKey: 'rules', nudgeIds: ['same'], anniversaryIds: ['same'] })
411
+ state.markInjected(session.id, ['same', '__anchor__'], 1)
412
+ state.markAnniversaryShown(session.id, 'same', 'day')
413
+ state.markOpenLoopReminded(session.id, 'same')
414
+ state.setSessionBinding(session.id, { lastInjectedUserMessageId: 'human', guideRulesKey: 'rules', guideMessageAt: 'at' })
415
+ state.rollbackInjectionForTurn(session.id, 1)
416
+ const kept = state.getSessionBinding(session.id)
417
+ assert.equal(kept.anchorPushed, true)
418
+ assert.equal(kept.lastInjectedUserMessageId, 'human')
419
+ assert.equal(kept.guideRulesKey, 'rules')
420
+ assert.equal(kept.injectedAt.same, 1)
421
+ assert.equal(kept.anniversariesShown.same, 'day')
422
+ assert.ok(kept.openLoopRemindedAt.same)
423
+ state.recordInjectionRollback(session.id, { hostTurn: 2, ids: ['same', '__anchor__'], guideKey: 'rules' })
424
+ state.markReinjectPending(session.id)
425
+ state.rollbackInjectionForTurn(session.id, 2)
426
+ assert.equal(state.getSessionBinding(session.id).anchorPushed, true)
427
+ })