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,298 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * EVALUATION ONLY — 离线注入模拟器(工单 B 量具的一半,与 mock-llm 配套)。
4
+ *
5
+ * 它回答的问题:注入管线**在当前设置下**每回合真的往模型请求里新加了哪些块、加了几次。
6
+ * 与真机跑(scripts/drive-session.mjs)的分工:这里用真实的 lib/inject.js、真实的
7
+ * registerInjection('agent/pre-step') 与真实的 lib/state.js 索引,但宿主侧的消息组装、
8
+ * 真实模型的 tool 轮**不在**覆盖范围内。产数是"插件自己决定了什么",不是"真实装机上
9
+ * 模型收到了什么";两者对不上时以真机为准。
10
+ *
11
+ * 为什么不碰真实数据:记忆库写进一个临时 DSH_MEMU_HOME(或 --home 指定的空目录),模型请求
12
+ * 打到只监听 127.0.0.1 的 mock-llm,日志仍只有长度/哈希/标记计数。
13
+ *
14
+ * 转录是累积的(和宿主一样把已发过的插件消息留在上下文里)。这不是偷懒的反面:
15
+ * ensureUnifiedGuide 会检查 decision.messages 里有没有当前规则的 guide,历史里没有 guide
16
+ * 就每轮重投一条,guide 计数会变成 50/50 而不是 1/50 —— 那种数只能证明驱动错了。
17
+ *
18
+ * Usage:
19
+ * node scripts/simulate-injection.mjs # 50 轮,cue 概率置 0 便于复现
20
+ * node scripts/simulate-injection.mjs --turns 20 --out ./sim-run
21
+ * node scripts/simulate-injection.mjs --cue 0.02 --home ./sim-home
22
+ *
23
+ * Options:
24
+ * --turns <n> 轮数,1..500。默认 50。
25
+ * --home <p> 当 DSH_MEMU_HOME 用的目录(不存在则创建)。默认临时目录。
26
+ * --out <p> 产物目录(report.md / mock-llm.jsonl / settings-snapshot.json)。默认临时目录。
27
+ * --port <n> 伪端点端口,0 = 系统分配。默认 0。
28
+ * --cue <p> 覆盖 settings.randomCueChance。默认 0(出货默认是 0.02,随机会让跑数不可复现)。
29
+ * --json 只打印一行 JSON 摘要。
30
+ *
31
+ * Exit codes: 0 ok / 2 usage error / 3 注入链路报了 warn(模拟器把 warn 当失败,不当噪声)。
32
+ */
33
+ import fs from 'node:fs'
34
+ import os from 'node:os'
35
+ import path from 'node:path'
36
+ import { registerHooks } from 'node:module'
37
+
38
+ const REPO_URL = new URL('../', import.meta.url)
39
+
40
+ function parseArgs(argv) {
41
+ const options = { turns: 50, home: null, out: null, port: 0, cue: 0, json: false }
42
+ const take = (index) => {
43
+ const value = argv[index]
44
+ if (value === undefined || value.startsWith('--')) throw new Error('missing value')
45
+ return value
46
+ }
47
+ for (let i = 0; i < argv.length; i += 1) {
48
+ const arg = argv[i]
49
+ switch (arg) {
50
+ case '--turns': options.turns = Number(take(++i)); break
51
+ case '--home': options.home = path.resolve(take(++i)); break
52
+ case '--out': options.out = path.resolve(take(++i)); break
53
+ case '--port': options.port = Number(take(++i)); break
54
+ case '--cue': options.cue = Number(take(++i)); break
55
+ case '--json': options.json = true; break
56
+ case '-h':
57
+ case '--help':
58
+ console.log(`EVALUATION ONLY — offline injection simulator (pairs with scripts/mock-llm.mjs).
59
+
60
+ node scripts/simulate-injection.mjs [--turns 50] [--home <dir>] [--out <dir>]
61
+ [--port <n>] [--cue <chance>] [--json]
62
+
63
+ Drives the real lib/inject.js through registerInjection('agent/pre-step') against a seeded
64
+ library in a throwaway DSH_MEMU_HOME, and posts every assembled request to a loopback mock
65
+ LLM. Writes report.md, mock-llm.jsonl and settings-snapshot.json under --out, plus a JSON
66
+ summary on stdout. Not real-engine evidence: host-side assembly and real tool rounds are
67
+ out of scope.`)
68
+ process.exit(0)
69
+ break
70
+ default: throw new Error('unknown option ' + arg)
71
+ }
72
+ }
73
+ if (!Number.isInteger(options.turns) || options.turns < 1 || options.turns > 500) throw new Error('--turns must be 1..500')
74
+ if (!Number.isFinite(options.cue) || options.cue < 0 || options.cue > 1) throw new Error('--cue must be 0..1')
75
+ return options
76
+ }
77
+
78
+ let parsed
79
+ try {
80
+ parsed = parseArgs(process.argv.slice(2))
81
+ } catch (error) {
82
+ console.error('simulate-injection: ' + error.message)
83
+ process.exit(2)
84
+ }
85
+
86
+ const work = parsed.home || fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-sim-'))
87
+ const outDir = parsed.out || fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-sim-out-'))
88
+ fs.mkdirSync(work, { recursive: true })
89
+ fs.mkdirSync(outDir, { recursive: true })
90
+ process.env.DSH_MEMU_HOME = work
91
+ process.env.DSH_MEMU_MEMORY_HOME = work
92
+
93
+ // lib/inject.js imports the host's createUserMessage; reuse the test stubs so this runs
94
+ // straight from a checkout with no host present.
95
+ registerHooks({
96
+ resolve(specifier, context, nextResolve) {
97
+ if (specifier === '@deepseek-ai/dsh-llm') return { url: new URL('tests/stubs/dsh-llm.js', REPO_URL).href, shortCircuit: true }
98
+ if (specifier === '@deepseek-ai/dsh-tools') return { url: new URL('tests/stubs/dsh-tools.js', REPO_URL).href, shortCircuit: true }
99
+ if (specifier === '@deepseek-ai/dsh-session') return { url: new URL('tests/stubs/dsh-session.js', REPO_URL).href, shortCircuit: true }
100
+ return nextResolve(specifier, context)
101
+ },
102
+ })
103
+
104
+ const state = await import(new URL('lib/state.js', REPO_URL))
105
+ const inject = await import(new URL('lib/inject.js', REPO_URL))
106
+ const mock = await import(new URL('scripts/mock-llm.mjs', REPO_URL))
107
+
108
+ const SESSION = 'sim-session'
109
+ const cwd = path.join(work, 'project')
110
+ const binding = state.ensureSession(SESSION, { cwd, agentPreset: 'rp' })
111
+ const libraryId = binding.libraryId
112
+ state.setSessionBinding(SESSION, { useLibrary: true, useGlobal: false })
113
+ state.updateSettings({ randomCueChance: parsed.cue })
114
+
115
+ const day = (offset, hour = 12) => {
116
+ const value = new Date()
117
+ value.setDate(value.getDate() + offset)
118
+ value.setHours(hour, 0, 0, 0)
119
+ return value
120
+ }
121
+ const ymd = (value) => `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`
122
+ const mmdd = (value) => `${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`
123
+
124
+ let seeded = 0
125
+ function seed(patch) {
126
+ const id = `mem-sim-${String(++seeded).padStart(2, '0')}`
127
+ state.updatePrivateIndex(libraryId, (index) => {
128
+ index.entries[id] = {
129
+ id,
130
+ track: 'memory',
131
+ layer: 'long_term',
132
+ title: id,
133
+ content: `${id} 的正文,涉及林眠、老周与城南那家咖啡店。`,
134
+ status: 'active',
135
+ disclosure: 'can_tell',
136
+ visibility: 'shared',
137
+ owner: 'me',
138
+ createdAt: day(-40).toISOString(),
139
+ updatedAt: day(-40).toISOString(),
140
+ ...patch,
141
+ }
142
+ })
143
+ return id
144
+ }
145
+
146
+ // 播种库是量具,不是任何人生活的样本:每种可注入的块都刻意放一条,报告里出现 0 才意味着
147
+ // "管线这次没选它",而不是"库里没有可说的"。
148
+ function seedScenario() {
149
+ seed({ title: '明天要还给林眠的相机镜头', salientDate: ymd(day(1)), openLoop: true, updatedAt: day(-2).toISOString(), createdAt: day(-2).toISOString() })
150
+ seed({ title: '今天答应陪老周体检', salientDate: ymd(day(0)), openLoop: true, updatedAt: day(-1).toISOString(), createdAt: day(-1).toISOString() })
151
+ seed({ title: '上周说过要回复的合同修改意见', salientDate: ymd(day(-6)), openLoop: true, updatedAt: day(-7).toISOString(), createdAt: day(-7).toISOString() })
152
+ seed({ title: '答应给林眠带城南的咖啡豆,一直没做', openLoop: true, updatedAt: day(-5).toISOString(), createdAt: day(-5).toISOString() })
153
+ seed({ title: '答应陪林眠去看海,日期未定', openLoop: true, updatedAt: day(-9).toISOString(), createdAt: day(-9).toISOString() })
154
+ seed({ title: '一起看海的纪念日', salientDate: mmdd(day(0)), updatedAt: day(-200).toISOString(), createdAt: day(-200).toISOString() })
155
+ seed({ title: '林眠说她的最新版本渲染器会崩', content: '林眠反馈最新版本渲染器崩溃,日志里是显存不足。', updatedAt: day(-3).toISOString(), createdAt: day(-3).toISOString() })
156
+ seed({ title: '城南咖啡店最近的豆子价格', content: '城南咖啡店最近的豆子价格:半磅 88 元,现在是活动价。', updatedAt: day(-4).toISOString(), createdAt: day(-4).toISOString() })
157
+ seed({ title: '老周现在的治疗方案的最新结论', content: '老周目前的治疗方案,医生给的最新结论是保守观察。', updatedAt: day(-8).toISOString(), createdAt: day(-8).toISOString() })
158
+ seed({ title: '四个月前记下的相机型号对比', content: '四个月前对比过两台机器的宽容度与价格。', updatedAt: day(-120).toISOString(), createdAt: day(-120).toISOString() })
159
+ seed({ title: '林眠讨厌在别人讲故事时看手机', updatedAt: day(-60).toISOString(), createdAt: day(-60).toISOString() })
160
+ seed({ title: '老周的女儿今年高考', updatedAt: day(-30).toISOString(), createdAt: day(-30).toISOString() })
161
+ // 近似重复的一对主题:该只回一次,不该连着推两次。
162
+ seed({ title: '林眠的相机镜头跑焦问题', updatedAt: day(-15).toISOString(), createdAt: day(-15).toISOString() })
163
+ seed({ title: '林眠镜头跑焦的维修报价', updatedAt: day(-16).toISOString(), createdAt: day(-16).toISOString() })
164
+ for (let index = 15; index <= 26; index += 1) {
165
+ seed({ title: `日常片段 ${index}:和老周下棋、给植物浇水、整理书架`, updatedAt: day(-index).toISOString(), createdAt: day(-index).toISOString() })
166
+ }
167
+ }
168
+ seedScenario()
169
+
170
+ const PROMPTS = [
171
+ '我们上次说到哪儿了?',
172
+ '你还记得林眠的相机吗?',
173
+ '明天有什么我要办的事?',
174
+ '嗯',
175
+ '城南那家店现在豆子多少钱?',
176
+ '老周最近怎么样?',
177
+ '帮我理一下今天要做的事。',
178
+ '我是不是答应过你什么事没做?',
179
+ '林眠说的渲染器最新版本靠谱吗?',
180
+ '聊聊别的,比如我最近在读的书。',
181
+ '体检那件事后来怎么处理的?',
182
+ '你还记得我们约好看海吗?',
183
+ '把上次那个合同的事再说一遍。',
184
+ '今天有点累,随便聊聊吧。',
185
+ ]
186
+
187
+ const SYSTEM_PROMPT = '你是这个角色扮演与陪伴对话里的助手。请按用户的请求自然回应,必要时使用记忆。'
188
+ const REPLY = mock.DEFAULT_REPLY
189
+
190
+ const warns = []
191
+ const handlers = new Map()
192
+ const ctx = {
193
+ on: (topic, handler) => { handlers.set(topic, handler); return () => {} },
194
+ get: () => undefined,
195
+ logger: { warn: (message) => warns.push(String(message)), info: () => {}, error: (message) => warns.push(String(message)) },
196
+ effect: (fn) => { try { fn() } catch {} },
197
+ slots: { inject: () => {} },
198
+ webServer: { register: () => {} },
199
+ }
200
+ const disposeInjection = inject.registerInjection(ctx)
201
+ const preStep = handlers.get('agent/pre-step')
202
+ if (typeof preStep !== 'function') throw new Error('agent/pre-step handler was not registered')
203
+
204
+ const logPath = path.join(outDir, 'mock-llm.jsonl')
205
+ const instance = await mock.startMockLlm({ port: parsed.port, log: logPath, reply: REPLY })
206
+
207
+ const agent = { session: { header: { id: SESSION, cwd, agentPreset: 'rp', origin: 'user' } } }
208
+ const textOf = (message) => (typeof message?.content === 'string'
209
+ ? message.content
210
+ : (message?.content || []).map((part) => part?.text || '').join(''))
211
+
212
+ const deltaTotals = Object.fromEntries(mock.MARKER_KEYS.map((key) => [key, 0]))
213
+ const roundsWithBlock = Object.fromEntries(mock.MARKER_KEYS.map((key) => [key, 0]))
214
+ let roundsWithInjection = 0
215
+ let titleCardBodyLineMax = 0
216
+ let sendFailures = 0
217
+
218
+ let history = []
219
+ for (let turn = 1; turn <= parsed.turns; turn += 1) {
220
+ const known = new Set(history)
221
+ history = [...history, {
222
+ id: `u-${turn}`,
223
+ role: 'user',
224
+ source: { kind: 'user' },
225
+ content: [{ type: 'text', text: PROMPTS[(turn - 1) % PROMPTS.length] }],
226
+ }]
227
+ const out = await preStep({ agent, turn, step: 1, signal: { aborted: false } }, async () => ({ kind: 'enter', messages: history }))
228
+ const messages = Array.isArray(out?.messages) ? out.messages : history
229
+ if (messages.length > history.length) roundsWithInjection += 1
230
+ for (const message of messages.filter((item) => !known.has(item))) {
231
+ const analysis = mock.analyzeMessage({ role: 'user', content: textOf(message) })
232
+ for (const key of mock.MARKER_KEYS) {
233
+ const count = Number(analysis.markers?.[key] || 0)
234
+ if (!count) continue
235
+ deltaTotals[key] += count
236
+ roundsWithBlock[key] += 1
237
+ }
238
+ titleCardBodyLineMax = Math.max(titleCardBodyLineMax, Number(analysis.context?.bodyLines || 0))
239
+ }
240
+ history = messages
241
+ const payload = [
242
+ { role: 'system', content: SYSTEM_PROMPT },
243
+ ...messages.map((message) => ({ role: message.role === 'assistant' ? 'assistant' : 'user', content: textOf(message) })),
244
+ ]
245
+ const response = await fetch(`${instance.url}/v1/chat/completions`, {
246
+ method: 'POST',
247
+ headers: { 'content-type': 'application/json' },
248
+ body: JSON.stringify({ model: instance.model, stream: true, messages: payload }),
249
+ })
250
+ if (!response.ok) sendFailures += 1
251
+ await response.text()
252
+ history = [...history, { id: `a-${turn}`, role: 'assistant', content: [{ type: 'text', text: REPLY }] }]
253
+ }
254
+
255
+ instance.close()
256
+ try { disposeInjection() } catch {}
257
+
258
+ const settings = state.getSettings()
259
+ const finalBinding = state.getSessionBinding(SESSION)
260
+ const uniqueInjected = (finalBinding?.injectedIds || []).filter((id) => id !== inject.ANCHOR_SENTINEL).length
261
+ const snapshotPath = path.join(outDir, 'settings-snapshot.json')
262
+ fs.writeFileSync(snapshotPath, JSON.stringify({
263
+ takenAt: new Date().toISOString(),
264
+ note: '报告证明不了设置值,这份快照就是读数口径',
265
+ run: { turns: parsed.turns, entries: seeded, session: SESSION, agentPreset: 'rp', driver: "registerInjection('agent/pre-step')" },
266
+ settings: {
267
+ autoInject: settings.autoInject, privateTopK: settings.privateTopK, globalTopK: settings.globalTopK,
268
+ anchorTokens: settings.anchorTokens, turnTokens: settings.turnTokens, injectionTotalTokens: settings.injectionTotalTokens,
269
+ dedupeTurns: settings.dedupeTurns, minUserChars: settings.minUserChars, randomCueChance: settings.randomCueChance,
270
+ openLoopRemindDays: settings.openLoopRemindDays, freshnessHint: settings.freshnessHint, freshnessDays: settings.freshnessDays,
271
+ salientWake: settings.salientWake,
272
+ },
273
+ }, null, 2))
274
+
275
+ const reportPath = path.join(outDir, 'report.md')
276
+ fs.writeFileSync(reportPath, mock.renderReport(fs.readFileSync(logPath, 'utf8'), { logPath }))
277
+
278
+ const summary = {
279
+ turns: parsed.turns,
280
+ roundsWithInjection,
281
+ injectionRate: Math.round((roundsWithInjection / parsed.turns) * 100) / 100,
282
+ deltaTotals,
283
+ roundsWithBlock,
284
+ titleCardBodyLineMax,
285
+ uniqueInjectedIds: uniqueInjected,
286
+ sendFailures,
287
+ warnCount: warns.length,
288
+ firstWarns: warns.slice(0, 3),
289
+ entries: seeded,
290
+ home: work,
291
+ out: outDir,
292
+ reportPath,
293
+ logPath,
294
+ snapshotPath,
295
+ }
296
+ console.log(parsed.json ? JSON.stringify(summary) : JSON.stringify(summary, null, 2))
297
+
298
+ if (warns.length > 0) process.exitCode = 3
@@ -267,11 +267,27 @@ test('the sidebar context-scope card cannot be flex-shrunk and keeps a two-colum
267
267
  assert.match(src, /\.dshm-scope-form\{[^}]*grid-template-columns:repeat\(2,minmax\(0,1fr\)\)/, 'four scope fields must wrap into two readable columns')
268
268
  })
269
269
 
270
+ test('the memory UI renders the read-only arousal/dominance/emotionSource line', () => {
271
+ const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
272
+ for (const key of ['arousalLabel', 'dominanceLabel', 'emotionSourceLabel', 'emotionSourceModel', 'emotionSourceSession', 'emotionSourceContent', 'emotionSourceUnknown']) {
273
+ assert.ok(src.includes(key), `missing ${key}`)
274
+ }
275
+ assert.match(src, /emotionMetaText\(f, t\)/, 'the card tag must expose affect metadata in its title')
276
+ assert.match(src, /emotionMetaText\(shown, t\)/, 'the drawer must render the read-only affect line')
277
+ })
278
+
270
279
  test('the sidebar run log keeps five rows and links its header to the WebUI logs page', () => {
271
280
  const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
272
- assert.match(src, /runLog\.slice\(0, 5\)/, 'the sidebar shows the five newest runs, not an unbounded list')
281
+ // 侧栏只显示正常流水(失败由「整理提醒」负责),列表仍是最近 5 条。
282
+ assert.match(src, /runLog\.filter\(\(row\) => logRowState\(row\) !== 'failed'\)/, 'the sidebar run log must drop failed rows')
283
+ assert.match(src, /sidebarRuns\.slice\(0, 5\)/, 'the sidebar shows the five newest runs, not an unbounded list')
273
284
  assert.match(src, /openWebUiPage\('logs'\)/, 'the run-log header must open the WebUI logs page')
274
285
  assert.match(src, /runLogOpen/, 'the jump needs a visible label')
286
+ // 红色只属于 WebUI 的总日志页:侧栏整段不过 logRowClass(失败行已被过滤),
287
+ // 判据仍集中在 logRowState 一处,改口径只改那一处。
288
+ assert.equal((src.match(/className: logRowClass\(row\)/g) || []).length, 1, 'only the WebUI logs page marks row state')
289
+ assert.ok(src.includes('const sidebarRuns = runLog.filter('), 'the sidebar must filter failed rows before rendering')
290
+ assert.ok(!/tone: row\.level === 'error' \? 'warn'/.test(src), 'the old level-only predicate must not come back')
275
291
  })
276
292
 
277
293
  // The browser row is the only place a human can see that a memory is marked
@@ -318,7 +334,10 @@ test('the memory browser badges what a memory is allowed to say', async () => {
318
334
  disclosure: 'never_say',
319
335
  visibility: 'secret',
320
336
  owner: 'about_user',
321
- expiresAt: '2026-11-01T09:30:00.000Z',
337
+ // 相对时间,不写死当天某一刻:短条目一旦过期就变成 inactive,行内编辑器不再渲染,
338
+ // 这条测试就会在下午闪红(曾经 pin 在 2026-11-01T09:30Z)。它要断言的是「草稿看得到
339
+ // 自己什么时候死」,所以留出 6 小时余量即可。
340
+ expiresAt: new Date(Date.now() + 6 * 3600 * 1000).toISOString(),
322
341
  },
323
342
  { id: 'mem-loud', title: 'shared fact', content: 'anything', layer: 'long_term', status: 'active', decay: 0.9, disclosure: 'can_tell', visibility: 'shared', owner: 'me' },
324
343
  ],
@@ -851,6 +870,54 @@ test('API vector settings render provider fields and hide the managed local cata
851
870
  assert.ok(!nodes.some((node) => node.type === 'progress'))
852
871
  })
853
872
 
873
+ // 日志行的三档视觉状态。真实读数里整理超时记的是 level=warn + ok=false
874
+ //(lib/private.js 的超时路径),所以「只看 level==='error'」会把它显示成正常行——
875
+ // 用户看到的就是「失败长得好普通」。这条钉的是行为:哪一行该红、哪一行该橙、
876
+ // 哪一行什么都不该标。
877
+ test('failed and degraded activity rows are visually distinguished from normal rows', async () => {
878
+ const failed = {
879
+ id: 'act-failed', at: '2026-11-02T07:58:29.775Z', kind: 'consolidate', level: 'warn',
880
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1', ok: false,
881
+ message: '整理超时 · 空闲 · fork f-7535be · timeout:consolidation timed out after 180s', detail: null, refs: [],
882
+ }
883
+ const degraded = {
884
+ id: 'act-degraded', at: '2026-11-02T07:59:00.000Z', kind: 'vector', level: 'warn',
885
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
886
+ message: '向量未激活,写入已降级为索引+引擎', detail: { reason: 'no active vector generation' }, refs: [],
887
+ }
888
+ const normal = {
889
+ id: 'act-normal', at: '2026-11-02T08:02:40.988Z', kind: 'consolidate', level: 'info',
890
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
891
+ message: '整理完成 · 空闲 · fork 1-2b16be · 索引 +1', detail: null, refs: [],
892
+ }
893
+ const ctx = fakeCtx({
894
+ answers: { getActivityLog: { events: [failed, degraded, normal], stats: { total: 3, capped: 2000, bytes: 1024 } } },
895
+ })
896
+ globalThis.__dshMemuExports.apply(ctx)
897
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
898
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
899
+ collectPageHook()
900
+ for (const effect of first.effects) effect.fn()
901
+ await new Promise((resolve) => setTimeout(resolve, 0))
902
+ const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
903
+ for (const effect of mid.effects) effect.fn()
904
+ await new Promise((resolve) => setTimeout(resolve, 0))
905
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
906
+ const rows = new Map()
907
+ const labels = []
908
+ walkNodes(tree, (node) => {
909
+ if (typeof node.props?.key === 'string' && node.props.key.startsWith('act-')) rows.set(node.props.key, node.props)
910
+ if (node.props?.children === 'logStateFailed' || node.props?.children === 'logDegraded') labels.push(node.props)
911
+ })
912
+ assert.equal(rows.size, 3, 'the log page rendered none of the fixture rows')
913
+ assert.match(String(rows.get('act-failed')?.className), /dshm-logrow is-failed/, 'the timeout row must carry the failed state class')
914
+ assert.match(String(rows.get('act-degraded')?.className), /dshm-logrow is-degraded/, 'a fallback-path row is degraded, not failed')
915
+ assert.equal(rows.get('act-normal')?.className, 'dshm-logrow', 'normal rows must not pick up any state class')
916
+ assert.ok(labels.some((props) => props.children === 'logStateFailed'), 'the failed row needs a 失败 label, not only colour')
917
+ assert.ok(labels.some((props) => props.children === 'logDegraded'), 'degraded rows need their own word')
918
+ assert.ok(labels.every((props) => typeof props.title === 'string' && props.title.length > 0), 'every state tag must explain itself on hover')
919
+ })
920
+
854
921
  test('clicking the API source tab sends the explicit setEmbeddingSource RPC only', async (t) => {
855
922
  const { nodes, rpcCalls } = await renderVectorSettings(t, {
856
923
  settings: { memoryBackend: 'api', vectorSource: 'local' },
@@ -9,7 +9,7 @@ process.env.DSH_MEMU_HOME = home
9
9
 
10
10
  const state = await import('../lib/state.js')
11
11
  const activity = await import('../lib/activity-log.js')
12
- const { requestPrivateConsolidation, isConsolidating } = await import('../lib/private.js')
12
+ const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY } = await import('../lib/private.js')
13
13
 
14
14
  test.after(() => {
15
15
  try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
@@ -489,3 +489,16 @@ test('a non-PTC header without write tools still refuses to fork', async () => {
489
489
  assert.equal(result.reasonCode, 'worker-tools-missing')
490
490
  assert.equal(ctx.rec.created.length, 0, 'no fork when the model surface provably lacks the write tools')
491
491
  })
492
+
493
+ // 超时预算按范围大小推:935 条事件那次实测「180 s 到点只写了 3 条,退避重试 131 s 完成」,
494
+ // 约 0.14–0.2 s/事件;政策取 0.35 s/事件(≈2 倍余量)并夹在 [180 s, 600 s]。
495
+ test('the consolidation wait budget scales with the transcript, not a fixed 180 s', () => {
496
+ assert.equal(consolidationWaitBudget(0), CONSOLIDATION_WAIT_POLICY.minMs, 'an empty range still gets the old floor')
497
+ assert.equal(consolidationWaitBudget(100), 180_000, 'small sessions keep the original three minutes')
498
+ assert.equal(consolidationWaitBudget(200), 190_000)
499
+ assert.equal(consolidationWaitBudget(935), 447_250, 'the session that timed out gets ~7.5 minutes')
500
+ assert.equal(consolidationWaitBudget(5_000), CONSOLIDATION_WAIT_POLICY.maxMs, 'a wedged fork still dies inside ten minutes')
501
+ assert.equal(consolidationWaitBudget(undefined), CONSOLIDATION_WAIT_POLICY.minMs)
502
+ assert.equal(consolidationWaitBudget('not-a-number'), CONSOLIDATION_WAIT_POLICY.minMs)
503
+ assert.ok(CONSOLIDATION_WAIT_POLICY.minMs <= CONSOLIDATION_WAIT_POLICY.maxMs)
504
+ })
@@ -0,0 +1,152 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import http from 'node:http'
4
+
5
+ // drive-session 之前一条测试都没有,于是它的 RPC envelope 一直是错的:网关按**参数名**包参数,
6
+ // 单参数 remote 必须是 `{ args: { request: … } }`,直接铺请求字段会在到达宿主前被拒
7
+ // (gateway/arguments-invalid: missing "request")。第一次真机对接才暴露。这里钉住形状。
8
+ const mod = await import('../scripts/drive-session.mjs')
9
+
10
+ test('the prompt envelope names the remote parameter, as the gateway carrier requires', () => {
11
+ const request = {
12
+ requestId: 'memu-eval-x-001-ab',
13
+ sessionId: 'session-1',
14
+ mode: 'queue',
15
+ content: [{ type: 'text', text: '你还记得林眠的相机吗?' }],
16
+ clientTimeZone: 'Asia/Shanghai',
17
+ }
18
+ const envelope = mod.buildPromptEnvelope(request, 'rpc-1')
19
+ assert.equal(envelope.type, 'client-request')
20
+ assert.equal(envelope.rpcId, 'rpc-1')
21
+ assert.equal(envelope.method, 'session/prompt')
22
+ assert.deepEqual(envelope.payload, { args: { request } })
23
+ // 铺平发送会被宿主拒绝:这条断言就是那个 bug 的回归。
24
+ assert.notDeepEqual(envelope.payload.args, request)
25
+ assert.equal(envelope.payload.args.request, request)
26
+
27
+ const auto = mod.buildPromptEnvelope(request)
28
+ assert.match(auto.rpcId, /^[0-9a-f-]{36}$/, 'each send needs its own correlation id')
29
+ assert.notEqual(auto.rpcId, mod.buildPromptEnvelope(request).rpcId)
30
+ })
31
+
32
+ test('request builders give every turn one identity and cycle the prompts', () => {
33
+ const requests = mod.buildRequests({
34
+ sessionId: 'session-9',
35
+ turns: 5,
36
+ prompts: ['第一条', '第二条'],
37
+ clientTimeZone: 'UTC',
38
+ })
39
+ assert.equal(requests.length, 5)
40
+ assert.deepEqual(requests.map((item) => item.turn), [1, 2, 3, 4, 5])
41
+ assert.deepEqual(requests.map((item) => item.request.content[0].text),
42
+ ['第一条', '第二条', '第一条', '第二条', '第一条'])
43
+ assert.equal(new Set(requests.map((item) => item.requestId)).size, 5, 'requestIds must never repeat')
44
+ for (const item of requests) {
45
+ assert.equal(item.request.sessionId, 'session-9')
46
+ assert.equal(item.request.mode, 'queue')
47
+ assert.equal(item.request.clientTimeZone, 'UTC')
48
+ // 日志匹配用的 id 和发出去的 id 必须同源,否则轮次永远判不出完成。
49
+ assert.equal(item.requestId, item.request.requestId)
50
+ }
51
+ })
52
+
53
+ test('completion is read from the transcript, not from an accepted response', () => {
54
+ const requestId = 'memu-eval-run-001-ab'
55
+ const admitted = [{ type: 'agent/inbox/spliced', data: { inserted: [{ source: { rpcId: requestId } }] } }]
56
+ assert.equal(mod.promptAdmitted(admitted, requestId), true, 'a spliced inbox item proves the host took the prompt')
57
+ assert.equal(mod.promptAdmitted([], requestId), false)
58
+ assert.equal(mod.promptAdmitted(admitted, 'other-id'), false)
59
+
60
+ const events = [
61
+ ...admitted,
62
+ { type: 'turn/start', data: { turn: 7 } },
63
+ { type: 'user/message', data: { source: { rpcId: requestId } } },
64
+ { type: 'step/end', data: {} },
65
+ ]
66
+ const claim = mod.promptClaimIndex(events, requestId)
67
+ assert.equal(claim, 2, 'the newest claim for this requestId wins')
68
+ assert.equal(mod.enclosingTurn(events, claim), 7, 'the turn that opened before the claim is the one to wait for')
69
+ // 一条已结束的回合之后再来消息,不属于任何还在跑的回合。
70
+ const after = [...events, { type: 'turn/end', data: { reason: { kind: 'completed' } } },
71
+ { type: 'user/message', data: { source: { rpcId: 'next-id' } } }]
72
+ assert.equal(mod.promptClaimIndex(after, 'next-id'), after.length - 1)
73
+ assert.equal(mod.enclosingTurn(after, after.length - 1), null, 'turn/end closes the window')
74
+ assert.equal(mod.enclosingTurn(events, 0), null, 'nothing encloses a claim with no turn/start before it')
75
+ })
76
+
77
+ test('path segments are encoded so any session id maps to one directory', () => {
78
+ assert.equal(mod.encodeSegment('plain-Name_1.2'), 'plain-Name_1.2')
79
+ assert.equal(mod.encodeSegment('a/b'), 'a~002Fb')
80
+ assert.equal(mod.encodeSegment('a~b'), 'a~007Eb')
81
+ assert.notEqual(mod.encodeSegment('a/b'), mod.encodeSegment('a_b'), 'separators must not collide with names')
82
+ })
83
+
84
+ test('prompt text is read from every accepted text-file shape', () => {
85
+ assert.equal(mod.textOfPromptItem(' 一条 ', 0), '一条')
86
+ assert.equal(mod.textOfPromptItem({ text: 'A' }, 0), 'A')
87
+ assert.equal(mod.textOfPromptItem({ prompt: 'B' }, 1), 'B')
88
+ assert.equal(mod.textOfPromptItem({ content: [{ type: 'text', text: 'C' }, { type: 'text', text: 'D' }] }, 2), 'C\nD')
89
+ assert.throws(() => mod.textOfPromptItem(42, 3), /not a string or object/)
90
+ })
91
+
92
+ // 传输层连错两次(参数没按名字包、返回体引用了不存在的变量),因为一直没有东西真的跑过
93
+ // sendPrompt。用一个 loopback 假网关把它钉住:请求形状、cookie 透传、相关 id 校验、401 提示。
94
+ async function fakeGateway(handler) {
95
+ const server = http.createServer((req, res) => {
96
+ let raw = ''
97
+ req.on('data', (chunk) => { raw += chunk })
98
+ req.on('end', () => handler({ raw, body: JSON.parse(raw), req, res }))
99
+ })
100
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
101
+ return { base: `http://127.0.0.1:${server.address().port}`, close: () => new Promise((resolve) => server.close(resolve)) }
102
+ }
103
+
104
+ test('sendPrompt sends the named-parameter envelope the gateway accepts', async () => {
105
+ const seen = []
106
+ const gateway = await fakeGateway(({ body, req, res }) => {
107
+ seen.push({ body, cookie: req.headers.cookie })
108
+ res.writeHead(200, { 'content-type': 'application/json' })
109
+ res.end(JSON.stringify({ type: 'server-response', rpcId: body.rpcId, result: { ok: true, value: { accepted: true } } }))
110
+ })
111
+ const request = { requestId: 'r-1', sessionId: 'session-1', mode: 'queue', content: [{ type: 'text', text: '第一条' }] }
112
+ try {
113
+ const out = await mod.sendPrompt({ base: gateway.base, request, timeoutMs: 5000, cookie: 'dsh-auth=abc' })
114
+ assert.equal(typeof out.rpcId, 'string', 'the correlation id comes back from the envelope that was actually sent')
115
+ assert.equal(seen[0].body.type, 'client-request')
116
+ assert.equal(seen[0].body.method, 'session/prompt')
117
+ assert.deepEqual(seen[0].body.payload.args.request, request, 'the remote parameter must be named "request"')
118
+ assert.equal(seen[0].cookie, 'dsh-auth=abc', 'the host session cookie is forwarded')
119
+ } finally {
120
+ await gateway.close()
121
+ }
122
+ })
123
+
124
+ test('sendPrompt refuses an unrelated response and says what a 401 needs', async () => {
125
+ const mismatched = await fakeGateway(({ res }) => {
126
+ res.writeHead(200, { 'content-type': 'application/json' })
127
+ res.end(JSON.stringify({ type: 'server-response', rpcId: 'not-the-same', result: { ok: true, value: { accepted: true } } }))
128
+ })
129
+ await assert.rejects(
130
+ mod.sendPrompt({ base: mismatched.base, request: { requestId: 'r' }, timeoutMs: 5000 }),
131
+ /matching Connection RPC envelope/,
132
+ )
133
+ await mismatched.close()
134
+
135
+ const unauthorized = await fakeGateway(({ res }) => { res.writeHead(401); res.end('unauthorized') })
136
+ await assert.rejects(
137
+ mod.sendPrompt({ base: unauthorized.base, request: { requestId: 'r' }, timeoutMs: 5000 }),
138
+ /--cookie-file/,
139
+ 'a 401 has to name the fix, not just the status'
140
+ )
141
+ await unauthorized.close()
142
+
143
+ const rejected = await fakeGateway(({ body, res }) => {
144
+ res.writeHead(200, { 'content-type': 'application/json' })
145
+ res.end(JSON.stringify({ type: 'server-response', rpcId: body.rpcId, result: { ok: false, error: { code: 'gateway/arguments-invalid', message: 'missing "request"' } } }))
146
+ })
147
+ await assert.rejects(
148
+ mod.sendPrompt({ base: rejected.base, request: { requestId: 'r' }, timeoutMs: 5000 }),
149
+ /gateway\/arguments-invalid/,
150
+ )
151
+ await rejected.close()
152
+ })