dsh-memu-memory 1.3.14 → 1.3.15

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.
package/lib/rpc.js CHANGED
@@ -36,6 +36,26 @@ import { runEnvironmentCheck, repairEnvironment, SAFE_REPAIRS, MANUAL_REPAIRS, R
36
36
  import { ALL_LEXICON_ID, GLOBAL_LEXICON_ID } from './lexicon.js'
37
37
  import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
38
38
 
39
+ let rejectionGuardWarned = false
40
+
41
+ function requestRejectionOf(connection, req) {
42
+ try {
43
+ if (typeof connection?.requestRejection === 'function') return connection.requestRejection(req)
44
+ if (typeof connection?.isTrustedApiRequest === 'function') {
45
+ return connection.isTrustedApiRequest(req) === true ? undefined : 401
46
+ }
47
+ } catch { return 403 }
48
+ if (!rejectionGuardWarned) {
49
+ rejectionGuardWarned = true
50
+ try {
51
+ warn('dsh-memu-memory: host exposes no request-rejection guard on connection; falling back to loopback-only admission for the memory RPC')
52
+ } catch {}
53
+ }
54
+ // 没有守卫能力时保持原语义(放行):仓库的取舍是「宁可降级并留一行日志,也不 fail
55
+ // closed」,而逐条库授权(authorizeLibrary)仍在每次请求里生效。风险写进诊断,不静默。
56
+ return undefined
57
+ }
58
+
39
59
  const ENDPOINT = '/dsh-memu-memory'
40
60
 
41
61
  function bindingView(binding) {
@@ -1142,6 +1162,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1142
1162
  'sleepConsolidation', 'sleepAfterIdleMinutes', 'autoCurateEveryHours', 'autoCurateSessionLimit',
1143
1163
  'memoryMode', 'memoryBackend', 'habitsInjection', 'purgeArchivedAfterDays',
1144
1164
  'shortTermTtlHours',
1165
+ // 回合中途补充召回的开关与阈值(lib/inject.js midTurnPolicy):不在名单里
1166
+ // 的 patch 会被静默丢弃,「midTurnRecall: false 可关」必须是可写的。
1167
+ 'midTurnRecall', 'midTurnMinSteps', 'midTurnMinUnits', 'midTurnMinChars',
1168
+ 'midTurnMaxPerTurn', 'midTurnCooldownMs', 'midTurnTokens', 'midTurnFullUnits', 'midTurnFullChars',
1145
1169
  'sidebarSettings', 'visionCaptionEnabled', 'inboundToolNames',
1146
1170
  // 全局提炼的审核模式(spec §6.1):不进 allowlist 的 patch 会被静默丢弃。
1147
1171
  'curatorReviewMode',
@@ -2252,15 +2276,20 @@ export function registerRpc(ctx) {
2252
2276
  kind: 'prefix',
2253
2277
  path: ENDPOINT,
2254
2278
  handler: async (req, res) => {
2279
+ // 入口守卫的能力探测(不写版本比较):
2280
+ // 1) 0.2.x:`connection.requestRejection(req)`;
2281
+ // 2) 更早的 rc.8 / 0.1.1:只有 `connection.isTrustedApiRequest(req)`;
2282
+ // 3) 0.2.3-alpha.2:两者都不在 connection 服务上(源码核对:只剩模块级
2283
+ // `isTrustedApiRequest(request, trustedHosts, bindHost, protocol)`)。
2284
+ // 第 3 种没有可用守卫:保持放行(仓库取舍:不 fail closed),但 warn 一次,
2285
+ // 免得「守卫在宿主升级后消失」这件事没人发现。
2255
2286
  // Capability probe, not a version check: `requestRejection` exists on
2256
2287
  // 0.1.2-rc.x and later of dsh-client-connection and not at all on the rc.8
2257
2288
  // / 0.1.1-rc.2 copies, where the service only exposes
2258
2289
  // `isTrustedApiRequest`. Calling it blindly threw a TypeError out of the
2259
2290
  // request handler, which the host turns into a 500 — an unauthenticated
2260
2291
  // caller then learned the route exists instead of being refused.
2261
- const rejection = typeof c.connection?.requestRejection === 'function'
2262
- ? c.connection.requestRejection(req)
2263
- : undefined
2292
+ const rejection = requestRejectionOf(c.connection, req)
2264
2293
  if (rejection !== undefined) {
2265
2294
  const status = rejection === 401 ? 401 : 403
2266
2295
  res.writeHead(status)
package/lib/state.js CHANGED
@@ -165,6 +165,18 @@ export const DEFAULT_SETTINGS = {
165
165
  consolidationTurnLogTools: 'none',
166
166
  // A positive age marks cleanup candidates; deletion always needs a user action.
167
167
  purgeArchivedAfterDays: 0,
168
+ // 回合中途补充召回(inject.js midTurnPolicy):默认开。这些键必须注册在这里——
169
+ // updateSettings 对 DEFAULT_SETTINGS 之外的键静默丢弃,文档里「midTurnRecall: false
170
+ // 可关」的承诺只有落了默认值与白名单才成立。阈值口径见 docs/memory-semantics.md §8.4。
171
+ midTurnRecall: true,
172
+ midTurnMinSteps: 4,
173
+ midTurnMinUnits: 3,
174
+ midTurnMinChars: 6000,
175
+ midTurnMaxPerTurn: 2,
176
+ midTurnCooldownMs: 60000,
177
+ midTurnTokens: 400,
178
+ midTurnFullUnits: 6,
179
+ midTurnFullChars: 15000,
168
180
  }
169
181
 
170
182
  function defaultState() {
@@ -421,6 +433,9 @@ export function updateSettings(patch) {
421
433
  autoCurateEveryHours: [0, 8760], autoCurateSessionLimit: [1, 10], purgeArchivedAfterDays: [0, 36500],
422
434
  activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
423
435
  activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
436
+ midTurnMinSteps: [1, 64], midTurnMinUnits: [1, 200], midTurnMinChars: [0, 200000],
437
+ midTurnMaxPerTurn: [1, 10], midTurnCooldownMs: [0, 600000], midTurnTokens: [120, 2000],
438
+ midTurnFullUnits: [1, 200], midTurnFullChars: [0, 200000],
424
439
  }
425
440
  const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'], consolidationTurnLog: ['on', 'off'], consolidationTurnLogTools: ['none', 'errors', 'summary'], consolidationRunner: ['worker', 'fork'] }
426
441
  for (const [key, value] of Object.entries(patch || {})) {
@@ -1076,6 +1091,64 @@ export function markInjectedRefs(sessionId, refs, memoryClock, options = {}) {
1076
1091
  return committed ? structuredClone(committed) : null
1077
1092
  }
1078
1093
 
1094
+ /**
1095
+ * 待接纳提案的**落盘**副本(2026-11-23)。
1096
+ *
1097
+ * `injectionAdmissions` 是进程内 Map:宿主重启、或同一个 home 被另一个进程观察时,
1098
+ * 提案会凭空消失,于是接纳永远不会发生——qq-dm 会话 333 个回合里
1099
+ * `acceptedMemoryMessages` 一次都没出现过,就是这么来的(同库的 qq-group 正常)。
1100
+ * 这里只存最小的提交凭据(按消息内容 digest 匹配),观察端换进程也能补完接纳。
1101
+ * 只保留最近 8 条:同一消息重投会被 digest 覆盖,过期条目自然被挤掉。
1102
+ */
1103
+ const PENDING_INJECTION_MAX = 8
1104
+ // 凭据只为「这一轮内的跨进程补认」服务:崩溃错过 turn/end 时它可能残留,
1105
+ // 同内容重投(锚点文本高度重复)会认领到最旧那条、把 turn 归属记错。
1106
+ // 读取时按 30 分钟 TTL 过滤并取最新匹配;写入时顺手清扫过期项。
1107
+ const PENDING_INJECTION_TTL_MS = 30 * 60 * 1000
1108
+
1109
+ function pendingInjectionFresh(item, now = Date.now()) {
1110
+ const at = Date.parse(item?.at || '')
1111
+ return Number.isFinite(at) && now - at < PENDING_INJECTION_TTL_MS
1112
+ }
1113
+
1114
+ export function rememberPendingInjection(sessionId, record = {}) {
1115
+ if (!sessionId || !record.digest || !record.messageId) return null
1116
+ return updateState((state) => {
1117
+ const binding = state.sessions[sessionId]
1118
+ if (!binding) return state
1119
+ const kept = (binding.pendingInjections || []).filter(item => item?.messageId !== record.messageId && pendingInjectionFresh(item))
1120
+ kept.push({
1121
+ digest: String(record.digest), messageId: String(record.messageId),
1122
+ turn: Number(record.turn) || 0, clock: Number(record.clock) || 0,
1123
+ generation: Number(record.generation) || 0, epoch: Number(record.epoch) || 0,
1124
+ refs: Array.isArray(record.refs) ? record.refs : [],
1125
+ actions: record.actions && typeof record.actions === 'object' ? record.actions : {},
1126
+ at: stamp(),
1127
+ })
1128
+ binding.pendingInjections = kept.slice(-PENDING_INJECTION_MAX)
1129
+ return state
1130
+ })
1131
+ }
1132
+
1133
+ export function findPendingInjection(sessionId, digest) {
1134
+ if (!sessionId || !digest) return null
1135
+ const rows = (getSessionBinding(sessionId)?.pendingInjections || [])
1136
+ .filter(item => item?.digest === digest && pendingInjectionFresh(item))
1137
+ return rows[rows.length - 1] || null
1138
+ }
1139
+
1140
+ export function forgetPendingInjection(sessionId, messageId) {
1141
+ if (!sessionId || !messageId) return null
1142
+ return updateState((state) => {
1143
+ const binding = state.sessions[sessionId]
1144
+ if (!binding?.pendingInjections) return state
1145
+ const kept = binding.pendingInjections.filter(item => item?.messageId !== messageId)
1146
+ if (kept.length) binding.pendingInjections = kept
1147
+ else delete binding.pendingInjections
1148
+ return state
1149
+ })
1150
+ }
1151
+
1079
1152
  export function markInjected(sessionId, ids, turn) {
1080
1153
  if (!sessionId) return
1081
1154
  return updateState((state) => {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memu-memory",
3
3
  "icon": "./assets/icon.png",
4
- "version": "1.3.14",
4
+ "version": "1.3.15",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -31,7 +31,8 @@ test('random cue is injected once and armed', async () => {
31
31
  const sessionEvent = handlers.get('session/event')
32
32
  assert.equal(typeof sessionEvent, 'function')
33
33
  const out = await inject.injectForStep({ agent, decision, turn: 2, step: 1, signal: { aborted: false }, ctx })
34
- const text = out.messages[0]?.content?.[0]?.text || ''
34
+ const pluginMessage = out.messages.find(message => message?.source?.kind === 'plugin:dsh-memu-memory')
35
+ const text = pluginMessage?.content?.[0]?.text || ''
35
36
  assert.ok(text.includes('<memory-cue id="'))
36
37
  assert.equal(state.getActiveCue('cue-session'), null, 'a proposal must not arm the cue')
37
38
  for (const message of out.messages) {
@@ -159,7 +159,7 @@ test('with the same anchorTokens, title cards expose at least as many ids as ful
159
159
  `title cards exposed ${anchor.ids.length} ids, full text ${legacy.ids.length}`)
160
160
  })
161
161
 
162
- test('pre-step inserts a plugin message before the user message', async () => {
162
+ test('pre-step inserts a plugin message right after the user message', async () => {
163
163
  const cwd = path.join(home, 'project-step')
164
164
  const binding = state.ensureSession('inject-step', { cwd, agentPreset: 'coding' })
165
165
  const index = state.loadPrivateIndex(binding.libraryId)
@@ -199,13 +199,13 @@ test('pre-step inserts a plugin message before the user message', async () => {
199
199
  const agent = { session: { header: { id: 'inject-step', cwd, agentPreset: 'coding', origin: 'user' } } }
200
200
  const out = await inject.injectForStep({ agent, decision, turn: 1, step: 1, signal: { aborted: false } })
201
201
  assert.equal(out.messages.length, 2)
202
- assert.equal(out.messages[0].role, 'user')
203
- assert.equal(out.messages[0].source.kind, 'plugin:dsh-memu-memory')
204
- assert.equal(out.messages[0].source.plugin, undefined)
205
- assert.equal(out.messages[0].source.form, 'recall')
206
- assert.equal(out.messages[1].source.kind, 'user')
202
+ assert.equal(out.messages[0].source.kind, 'user', 'the human message stays first')
203
+ assert.equal(out.messages[1].role, 'user')
204
+ assert.equal(out.messages[1].source.kind, 'plugin:dsh-memu-memory')
205
+ assert.equal(out.messages[1].source.plugin, undefined)
206
+ assert.equal(out.messages[1].source.form, 'recall')
207
207
 
208
- const injected = out.messages[0].content[0].text
208
+ const injected = out.messages[1].content[0].text
209
209
  assert.ok(injected.includes('[mem-recall]'), 'per-turn recall must surface the matching entry by id')
210
210
  assert.ok(injected.includes('Deploy convention'), 'the title is what reaches the prompt')
211
211
  assert.equal(injected.includes('The deploy script lives in tools/deploy.ps1'), false,
@@ -281,8 +281,8 @@ test('the hint ships in the same plugin message as the recall block', async () =
281
281
  const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [user] }, turn: 1, step: 1, signal: { aborted: false } })
282
282
 
283
283
  assert.equal(out.messages.length, 2)
284
- assert.equal(out.messages[0].source.kind, 'plugin:dsh-memu-memory')
285
- const text = out.messages[0].content[0].text
284
+ assert.equal(out.messages[1].source.kind, 'plugin:dsh-memu-memory', 'memory follows the human turn')
285
+ const text = out.messages[1].content[0].text
286
286
  assert.ok(text.includes('[mem-fresh-message]'))
287
287
  assert.equal((text.match(/<memory-freshness>/g) || []).length, 1)
288
288
  assert.ok(text.indexOf('<memory-freshness>') > text.lastIndexOf('</memory-context>'))
@@ -402,3 +402,41 @@ test('typed cooldown follows content revisions, library identity and a new injec
402
402
  const reinjected = await inject.buildRecall(state.getSessionBinding(id), '部署脚本的位置', 4, settings, exec, id)
403
403
  assert.ok(reinjected.ids.includes('mem-shared-id'))
404
404
  })
405
+
406
+ // ---------------------------------------------------------------- I: mid-turn recall
407
+ // 回合中途补充召回:只可能在非首步、批次无人类消息、inbound 没改动决策时出现;
408
+ // 门 = 步距 + 增量证据 + 每回合上限 + 冷却 + 空召回退避;midTurnRecall 必须是可写设置
409
+ // (1.3.15 审核修正:此前键未注册,updateSettings 会静默丢弃,「可关」是空头承诺)。
410
+
411
+ test('a long tool-only step gets one mid-turn hint card, gated by step distance', async () => {
412
+ const cwd = path.join(home, 'mid-turn')
413
+ state.ensureSession('mid-turn', { cwd, agentPreset: 'coding' })
414
+ const agent = { session: { header: { id: 'mid-turn', cwd, agentPreset: 'coding', origin: 'user' } } }
415
+ const toolMsgs = (n) => Array.from({ length: n }, (_, i) => ({
416
+ id: 'mid-tool-' + i, role: 'tool', source: { kind: 'tool' },
417
+ content: [{ type: 'text', text: 'x'.repeat(120) + ' #' + i }],
418
+ }))
419
+ const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs(3) }, turn: 11, step: 5, signal: { aborted: false } })
420
+ const plugin = out.messages.filter(m => m?.source?.kind === 'plugin:dsh-memu-memory')
421
+ .find(m => String(m?.content?.[0]?.text || '').includes('回合中途补充'))
422
+ assert.ok(plugin, 'step 5 with three distinct tool units earns the hint card')
423
+ const early = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs(3) }, turn: 12, step: 2, signal: { aborted: false } })
424
+ assert.ok(!early.messages.some(m => String(m?.content?.[0]?.text || '').includes('回合中途补充')), 'step 2 cannot clear the four-step gap')
425
+ })
426
+
427
+ test('midTurnRecall:false is a writable kill switch for mid-turn recall', async () => {
428
+ const cwd = path.join(home, 'mid-turn-off')
429
+ state.ensureSession('mid-turn-off', { cwd, agentPreset: 'coding' })
430
+ const agent = { session: { header: { id: 'mid-turn-off', cwd, agentPreset: 'coding', origin: 'user' } } }
431
+ const toolMsgs = Array.from({ length: 3 }, (_, i) => ({
432
+ id: 'off-tool-' + i, role: 'tool', source: { kind: 'tool' },
433
+ content: [{ type: 'text', text: 'y'.repeat(120) + ' #' + i }],
434
+ }))
435
+ const before = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs }, turn: 21, step: 6, signal: { aborted: false } })
436
+ assert.ok(before.messages.some(m => String(m?.content?.[0]?.text || '').includes('回合中途补充')), 'default-on proves the fixture actually reaches the gate')
437
+ const saved = state.updateSettings({ midTurnRecall: false })
438
+ assert.equal(saved.midTurnRecall, false, 'the switch survives updateSettings validation (it is a registered key now)')
439
+ const after = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: toolMsgs }, turn: 22, step: 6, signal: { aborted: false } })
440
+ assert.ok(!after.messages.some(m => String(m?.content?.[0]?.text || '').includes('回合中途补充')), 'the kill switch stops it')
441
+ state.updateSettings({ midTurnRecall: true })
442
+ })
@@ -314,18 +314,19 @@ for (const acceptedPart of ['guide', 'recall']) test(`partial ${acceptedPart} ad
314
314
  assert.deepEqual(facts(session.id), after, 'discarded partial sibling cannot commit late')
315
315
  })
316
316
 
317
- test('proposal reuse preserves pre-human ordering and missing human projection without duplicate IDs', async () => {
317
+ test('proposal reuse preserves post-human ordering and missing human projection without duplicate IDs', async () => {
318
318
  const session = makeSession('projection')
319
319
  const human = user('projection', '林眠的相机镜头修好了吗')
320
320
  const first = await step(session, 1, [human])
321
321
  const memory = first.find(message => ANCHOR_RE.test(textOf(message)))
322
322
  const second = await step(session, 1, [human])
323
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))
324
+ assert.ok(second.findIndex(message => message.id === memory.id) > second.findIndex(message => message.id === human.id),
325
+ 'memory sits after the human turn')
325
326
  const missing = await step(session, 1, [])
326
327
  assert.equal(missing.filter(message => message.id === human.id).length, 1, 'retry carries the pending human too')
327
328
  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
+ assert.ok(missing.findIndex(message => message.id === memory.id) > missing.findIndex(message => message.id === human.id))
329
330
  await accept(session, [human])
330
331
  const nativeAlready = await step(session, 1, [])
331
332
  assert.equal(nativeAlready.some(message => message.id === human.id), false, 'a Native-admitted human is not appended twice')
@@ -42,7 +42,10 @@ test('image-only turns retrieve a saved image and expose the image count in stat
42
42
  const message = { id: 'image-only-native-user', role: 'user', ...event(4).data }
43
43
  const decision = await inject.injectForStep({ agent: exec.agent, decision: { kind: 'enter', messages: [message] }, turn: 2, step: 1 })
44
44
  assert.ok(decision.messages.length > 1)
45
- assert.ok(decision.messages[0].content[0].text.includes(saved.id))
45
+ const injectedText = decision.messages
46
+ .filter(message => message?.source?.kind === 'plugin:dsh-memu-memory')
47
+ .map(message => String(message?.content?.[0]?.text || '')).join('\n')
48
+ assert.ok(injectedText.includes(saved.id))
46
49
  assert.equal(state.getSessionBinding('images').recentQueries.at(-1).imageCount, 1)
47
50
  const tools = []
48
51
  registerTools({ tools: { register: tool => { tools.push(tool); return () => {} } } })
@@ -110,9 +110,10 @@ test('the real tool → recall → injection chain is reachable and carries S1
110
110
  assert.match(datedText, /date=2026-11-07/, 'the resolved absolute date reaches the prompt')
111
111
  assert.match(datedText, /source=assistant_said/)
112
112
  assert.match(datedText, /speaker=assistant/)
113
- // The user message is untouched and the plugin message comes before it.
114
- assert.equal(dated.messages.at(-1).source.kind, 'user')
115
- assert.equal(dated.messages.at(-1).content[0].text, dateUser.content[0].text)
113
+ // The user message is untouched and the plugin message comes right after it.
114
+ assert.equal(dated.messages.at(-2).source.kind, 'user')
115
+ assert.equal(dated.messages.at(-2).content[0].text, dateUser.content[0].text)
116
+ assert.equal(dated.messages.at(-1).source.kind, 'plugin:dsh-memu-memory')
116
117
 
117
118
  const floorUser = {
118
119
  id: 'chain-u2', role: 'user', source: { kind: 'user' },
@@ -0,0 +1,107 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import crypto from 'node:crypto'
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-memory-pending-'))
9
+ process.env.DSH_HOME = home
10
+ process.env.DSH_MEMU_HOME = home
11
+ process.env.DSH_MEMU_MEMORY_HOME = home
12
+
13
+ const state = await import('../lib/state.js')
14
+ const inject = await import('../lib/inject.js')
15
+
16
+ test.after(() => {
17
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
18
+ })
19
+
20
+ const digestOf = (message) => crypto.createHash('sha256').update(JSON.stringify(message?.content ?? null)).digest('hex')
21
+ const NOW = () => new Date().toISOString()
22
+
23
+ function seed(sessionId, entryId) {
24
+ const cwd = path.join(home, sessionId)
25
+ const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
26
+ const index = state.loadPrivateIndex(binding.libraryId)
27
+ index.entries[entryId] = {
28
+ track: 'memory', layer: 'long_term', title: '部署脚本', content: '部署脚本放在 tools/deploy.ps1。',
29
+ status: 'active', confidence: 0.9, createdAt: NOW(), updatedAt: NOW(),
30
+ }
31
+ state.savePrivateIndex(binding.libraryId, index)
32
+ const user = { id: 'u-' + sessionId, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: '部署脚本放在哪里?' }] }
33
+ const agent = { session: { header: { id: sessionId, cwd, agentPreset: 'coding', origin: 'user' } } }
34
+ return { agent, user }
35
+ }
36
+
37
+ test('a proposal leaves a digest credential so another process can still finish the admission', async () => {
38
+ const sessionId = 'pending-cred'
39
+ const { agent, user } = seed(sessionId, 'mem-cred')
40
+ const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [user] }, turn: 1, step: 1, signal: { aborted: false } })
41
+ const plugin = out.messages.find((message) => message?.source?.kind === 'plugin:dsh-memu-memory')
42
+ assert.ok(plugin, 'a plugin message is proposed on the first step')
43
+ const credentials = state.getSessionBinding(sessionId).pendingInjections || []
44
+ assert.equal(credentials.length, 1, 'exactly one credential is persisted')
45
+ assert.equal(credentials[0].digest, digestOf(plugin))
46
+ assert.equal(state.findPendingInjection(sessionId, digestOf(plugin))?.messageId, plugin.id)
47
+ assert.ok(credentials[0].refs.length >= 1, 'the credential carries the refs needed to commit')
48
+ })
49
+
50
+ test('turn end invalidates the credential so a late identical message cannot revive a discarded proposal', async () => {
51
+ const sessionId = 'pending-drop'
52
+ const { agent, user } = seed(sessionId, 'mem-drop')
53
+ const handlers = new Map()
54
+ const ctx = { on (name, handler) { handlers.set(name, handler); return () => {} }, logger: { warn () {} }, inject () {} }
55
+ inject.registerInjection(ctx)
56
+ const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [user] }, turn: 1, step: 1, signal: { aborted: false } })
57
+ const plugin = out.messages.find((message) => message?.source?.kind === 'plugin:dsh-memu-memory')
58
+ const digest = digestOf(plugin)
59
+ assert.ok(state.findPendingInjection(sessionId, digest), 'credential exists while the turn is open')
60
+ await handlers.get('session/event')({ header: { id: sessionId } }, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } })
61
+ assert.equal(state.findPendingInjection(sessionId, digest), null, 'a closed turn leaves nothing to revive')
62
+ assert.deepEqual(state.getSessionBinding(sessionId).pendingInjections ?? [], [])
63
+ })
64
+
65
+ test('digest credentials expire after the TTL and the freshest same-digest match wins', () => {
66
+ const sessionId = 'pending-ttl'
67
+ state.ensureSession(sessionId, { cwd: path.join(home, sessionId) })
68
+ const stale = { digest: 'd-1', messageId: 'm-stale', turn: 0, clock: 0, at: new Date(Date.now() - 31 * 60_000).toISOString() }
69
+ const old = { digest: 'd-1', messageId: 'm-old', turn: 1, clock: 1, at: new Date(Date.now() - 5 * 60_000).toISOString() }
70
+ const fresh = { digest: 'd-1', messageId: 'm-fresh', turn: 2, clock: 2, at: new Date().toISOString() }
71
+ state.setSessionBinding(sessionId, { pendingInjections: [stale, old, fresh] })
72
+ assert.equal(state.findPendingInjection(sessionId, 'd-1').messageId, 'm-fresh', 'the newest same-digest credential wins')
73
+ state.setSessionBinding(sessionId, { pendingInjections: [stale] })
74
+ assert.equal(state.findPendingInjection(sessionId, 'd-1'), null, 'a 31-minute credential is dead')
75
+ state.rememberPendingInjection(sessionId, { digest: 'd-2', messageId: 'm-new', turn: 9, clock: 9 })
76
+ const rows = state.getSessionBinding(sessionId).pendingInjections
77
+ assert.deepEqual(rows.map(row => row.messageId), ['m-new'], 'remembering prunes the expired credential')
78
+ })
79
+
80
+ test('a cross-process admission commits once, forgets its own credential, and re-observation is quiet', async () => {
81
+ const sessionId = 'pending-store-admit'
82
+ seed(sessionId, 'mem-store')
83
+ const binding = state.getSessionBinding(sessionId)
84
+ // 模拟另一个进程投出的同内容锚点:本进程 Map 里没有提案,只有落盘凭据。
85
+ const lateMessage = { id: 'late-1', role: 'user', source: { kind: 'plugin:dsh-memu-memory' },
86
+ content: [{ type: 'text', text: '===== memory anchor =====\nstore-path fixture' }] }
87
+ state.setSessionBinding(sessionId, { pendingInjections: [{
88
+ digest: digestOf(lateMessage), messageId: 'm-store-cred', turn: 42, clock: 3,
89
+ generation: Number(binding.scopeGeneration || 0), epoch: Number(binding.injectionEpoch || 0),
90
+ refs: [{ scope: 'private', libraryId: binding.libraryId, id: 'mem-store', revision: 'rev-1' }],
91
+ actions: { patch: {} }, at: new Date().toISOString(),
92
+ }] })
93
+ const warns = []
94
+ const handlers = new Map()
95
+ const ctx = { on (name, handler) { handlers.set(name, handler); return () => {} }, logger: { warn: (m) => warns.push(String(m)) }, inject () {} }
96
+ inject.registerInjection(ctx)
97
+ const session = { header: { id: sessionId } }
98
+ await handlers.get('session/event')(session, { type: 'user/message', data: lateMessage })
99
+ const admitted = state.getSessionBinding(sessionId).acceptedMemoryMessages || []
100
+ assert.equal(admitted.length, 1, 'the credential admission commits exactly once')
101
+ assert.equal(admitted[0].messageId, 'late-1')
102
+ assert.equal((state.getSessionBinding(sessionId).pendingInjections || []).length, 0,
103
+ 'the credential is forgotten by its own messageId, not the observed id')
104
+ await handlers.get('session/event')(session, { type: 'user/message', data: lateMessage })
105
+ assert.equal((state.getSessionBinding(sessionId).acceptedMemoryMessages || []).length, 1, 'the second observation neither re-commits')
106
+ assert.equal(warns.filter(w => w.includes('未被接纳')).length, 0, 'nor warns — an admitted message observed twice is a success')
107
+ })