dsh-memu-memory 1.3.3 → 1.3.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.
- package/AGENTS.md +6 -1
- package/CHANGELOG.md +27 -3
- package/README.md +1 -7
- package/README.zh.md +1 -7
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/stats.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +10 -0
- package/docs/contributing.md +1 -0
- package/docs/memory-semantics.md +17 -0
- package/docs/troubleshooting.md +29 -0
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +34 -21
- package/lib/consolidation-snapshot.js +101 -5
- package/lib/consolidation-worker.js +1 -1
- package/lib/cycle.js +19 -1
- package/lib/index.js +83 -2
- package/lib/private.js +450 -165
- package/lib/rpc.js +8 -0
- package/lib/state.js +11 -1
- package/lib/turn-log.js +522 -0
- package/lib/webui/standalone.css +4 -29
- package/lib/worker-pool.js +741 -0
- package/package.json +1 -1
- package/scripts/acceptance-local.mjs +6 -5
- package/scripts/check-idle-compositing.mjs +61 -0
- package/scripts/prune-turnlogs.mjs +30 -0
- package/tests/consolidation-snapshot.test.mjs +89 -1
- package/tests/loader.mjs +2 -0
- package/tests/salience-domain.test.mjs +139 -0
- package/tests/settings-coverage.test.mjs +97 -0
- package/tests/stubs/dsh-session-query.js +26 -0
- package/tests/turn-log.test.mjs +474 -0
- package/tests/webui.test.mjs +19 -0
- package/tests/worker-lifecycle.test.mjs +1046 -0
- package/docs/recall-benchmark.md +0 -238
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
|
|
7
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-turn-log-'))
|
|
8
|
+
process.env.DSH_MEMU_HOME = home
|
|
9
|
+
process.env.DSH_MEMU_MEMORY_HOME = home
|
|
10
|
+
|
|
11
|
+
const state = await import('../lib/state.js')
|
|
12
|
+
const turnLog = await import('../lib/turn-log.js')
|
|
13
|
+
const rpc = await import('../lib/rpc.js')
|
|
14
|
+
const { registerTurnLogRecorder } = await import('../lib/index.js')
|
|
15
|
+
|
|
16
|
+
test.after(() => {
|
|
17
|
+
state.flushState()
|
|
18
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
// —— 宿主事件 fixture(形状与 consolidation-snapshot/private 的口径一致) ——————
|
|
22
|
+
|
|
23
|
+
let clock = 0
|
|
24
|
+
function userMessage(seq, text, { sceneTime, kind = 'user' } = {}) {
|
|
25
|
+
clock += 1000
|
|
26
|
+
return { type: 'user/message', seq, time: clock, data: { id: `u${seq}`, source: { kind }, content: [{ type: 'text', text }], ...(sceneTime ? { sceneTime } : {}) } }
|
|
27
|
+
}
|
|
28
|
+
function assistantMessage(seq, text, blocks = []) {
|
|
29
|
+
clock += 1000
|
|
30
|
+
return { type: 'assistant/message', seq, time: clock, data: { message: { content: [{ type: 'text', text }, ...blocks] } } }
|
|
31
|
+
}
|
|
32
|
+
function toolCallEvent(seq, callId, name, args) {
|
|
33
|
+
return { type: 'tool/call', seq, time: clock, data: { callId, name, arguments: args } }
|
|
34
|
+
}
|
|
35
|
+
function toolResultEvent(seq, callId, text, { isError = false } = {}) {
|
|
36
|
+
return { type: 'tool/result', seq, time: clock, data: { message: { callId, content: [{ type: 'text', text }], isError } } }
|
|
37
|
+
}
|
|
38
|
+
function turnStart(seq, turn = 1) {
|
|
39
|
+
return { type: 'turn/start', seq, time: clock, data: { turn } }
|
|
40
|
+
}
|
|
41
|
+
function turnEnd(seq, { kind = 'completed', turn = 1, time } = {}) {
|
|
42
|
+
return { type: 'turn/end', seq, ...(time !== undefined ? { time } : { time: (clock += 1000) }), data: { turn, reason: { kind } } }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function oneTurn({ user, assistant, scene, kind = 'completed', startSeq = 10, tools = [] } = {}) {
|
|
46
|
+
const events = [turnStart(startSeq)]
|
|
47
|
+
let seq = startSeq + 1
|
|
48
|
+
if (user !== undefined) events.push(userMessage(seq++, user, { sceneTime: scene }))
|
|
49
|
+
for (const [callId, name, args, result, isError] of tools) {
|
|
50
|
+
events.push(assistantMessage(seq++, '', [{ type: 'tool-call', id: callId, name, arguments: args }]))
|
|
51
|
+
events.push(toolCallEvent(seq++, callId, name, args))
|
|
52
|
+
if (result !== undefined) events.push(toolResultEvent(seq++, callId, result, { isError }))
|
|
53
|
+
}
|
|
54
|
+
if (assistant !== undefined) events.push(assistantMessage(seq++, assistant))
|
|
55
|
+
events.push(turnEnd(seq, { kind }))
|
|
56
|
+
return events
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// —— 记录规则(§3.1) ———————————————————————————————————————
|
|
60
|
+
|
|
61
|
+
test('one closed turn is one record: seq interval, scene, and the filtering rules', () => {
|
|
62
|
+
const events = [
|
|
63
|
+
turnStart(10),
|
|
64
|
+
userMessage(11, '帮我看看明天要不要带伞', { sceneTime: '第三日夜' }),
|
|
65
|
+
userMessage(12, '(插件注入的提示)', { kind: 'plugin:dsh-memu-memory' }),
|
|
66
|
+
toolCallEvent(13, 'c1', 'weather', '{"city":"杭州"}'),
|
|
67
|
+
assistantMessage(14, '明天有雨,建议带伞。'),
|
|
68
|
+
toolResultEvent(15, 'c1', 'rain'),
|
|
69
|
+
userMessage(16, '谢谢', { sceneTime: '第四日晨' }),
|
|
70
|
+
turnEnd(17),
|
|
71
|
+
]
|
|
72
|
+
const records = turnLog.buildTurnRecords(events)
|
|
73
|
+
assert.equal(records.length, 1)
|
|
74
|
+
assert.deepEqual(records[0].seq, [10, 17])
|
|
75
|
+
// scene 取回合内最后一个带 sceneTime 的 user 事件值;插件注入不进 user 文本。
|
|
76
|
+
assert.equal(records[0].scene, '第四日晨')
|
|
77
|
+
assert.equal(records[0].user, '帮我看看明天要不要带伞\n谢谢')
|
|
78
|
+
assert.equal(records[0].model, '明天有雨,建议带伞。')
|
|
79
|
+
assert.equal(records[0].interrupted, undefined)
|
|
80
|
+
assert.ok(records[0].at, 'the turn/end timestamp lands on the record')
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
test('an open tail turn and a heartbeat-only turn produce no record', () => {
|
|
84
|
+
const openTail = oneTurn({ user: '未闭合的回合' })
|
|
85
|
+
openTail.pop() // 拿掉 turn/end:半回合不产出记录
|
|
86
|
+
assert.deepEqual(turnLog.buildTurnRecords(openTail), [])
|
|
87
|
+
|
|
88
|
+
// 心跳/调度回合:没有真人消息也没有工具 → 不落行。
|
|
89
|
+
const heartbeat = [turnStart(50), userMessage(51, 'heartbeat', { kind: 'plugin:heartbeat' }), turnEnd(52)]
|
|
90
|
+
assert.deepEqual(turnLog.buildTurnRecords(heartbeat), [])
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
test('an aborted turn is marked interrupted', () => {
|
|
94
|
+
const records = turnLog.buildTurnRecords(oneTurn({ user: '说到一半被打断', kind: 'aborted' }))
|
|
95
|
+
assert.equal(records.length, 1)
|
|
96
|
+
assert.equal(records[0].interrupted, true)
|
|
97
|
+
assert.equal(records[0].seq[0], 10)
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
test('redactSecrets is applied to user, model and tool text at record time', () => {
|
|
101
|
+
const secret = 'sk-abcdefghijklmnopqrstuvwxyz123456'
|
|
102
|
+
const events = [
|
|
103
|
+
turnStart(10),
|
|
104
|
+
userMessage(11, `我的 key 是 ${secret} 别外传`),
|
|
105
|
+
toolCallEvent(12, 'c1', 'deploy', '{}'),
|
|
106
|
+
toolResultEvent(13, 'c1', `failed with ${secret}`, { isError: true }),
|
|
107
|
+
assistantMessage(14, `收到,key ${secret} 已记下`),
|
|
108
|
+
turnEnd(15),
|
|
109
|
+
]
|
|
110
|
+
const records = turnLog.buildTurnRecords(events, { tools: 'errors' })
|
|
111
|
+
assert.equal(records.length, 1)
|
|
112
|
+
const flat = JSON.stringify(records[0])
|
|
113
|
+
assert.ok(!flat.includes(secret), 'the raw secret must never reach the log')
|
|
114
|
+
assert.ok(flat.includes('[REDACTED_KEY]'))
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
// —— 工具行三档(§3.1) ——————————————————————————————————————
|
|
118
|
+
|
|
119
|
+
const TOOL_FIXTURE = [
|
|
120
|
+
['c1', 'edit_memory', '{"id":"m1"}', '修改成功', false],
|
|
121
|
+
['c2', 'readSession', '{"path":"a.ts"}', 'not found', true],
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
test('tools mode none (the default) records pure dialogue without a tools field', () => {
|
|
125
|
+
const events = oneTurn({ user: '改一下记忆', tools: TOOL_FIXTURE })
|
|
126
|
+
const record = turnLog.buildTurnRecords(events)[0]
|
|
127
|
+
assert.equal(record.tools, undefined)
|
|
128
|
+
// 默认值走设置而不是参数:默认档就是 none。
|
|
129
|
+
assert.equal(turnLog.buildTurnRecords(events)[0].tools, undefined)
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
test('tools mode errors keeps only the isError result line', () => {
|
|
133
|
+
const record = turnLog.buildTurnRecords(oneTurn({ user: '查一下', tools: TOOL_FIXTURE }), { tools: 'errors' })[0]
|
|
134
|
+
assert.equal(record.tools.length, 1)
|
|
135
|
+
assert.match(record.tools[0], /readSession → 失败: not found/)
|
|
136
|
+
assert.ok(!record.tools.some((line) => line.includes('edit_memory')), 'the successful call is not in errors mode')
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
test('tools mode summary pairs calls with results and flags calls without one', () => {
|
|
140
|
+
const tools = [...TOOL_FIXTURE, ['c3', 'interruptedTool', '{"x":1}']] // 没有结果:被打断的调用
|
|
141
|
+
const record = turnLog.buildTurnRecords(oneTurn({ user: '干活', tools }), { tools: 'summary' })[0]
|
|
142
|
+
assert.equal(record.tools.length, 3)
|
|
143
|
+
assert.match(record.tools[0], /edit_memory\(\{"id":"m1"\}\) → 成功/)
|
|
144
|
+
assert.match(record.tools[1], /readSession\(\{"path":"a.ts"\}\) → 失败: not found/)
|
|
145
|
+
assert.match(record.tools[2], /interruptedTool\(\{"x":1\}\) → 无结果/)
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
test('the assistant tool-call block is not double-counted next to its tool/call event', () => {
|
|
149
|
+
const events = [
|
|
150
|
+
turnStart(10),
|
|
151
|
+
userMessage(11, '只算一次'),
|
|
152
|
+
assistantMessage(12, '', [{ type: 'tool-call', id: 'c9', name: 'dupTool', arguments: '{}' }]),
|
|
153
|
+
toolCallEvent(13, 'c9', 'dupTool', '{}'),
|
|
154
|
+
toolResultEvent(14, 'c9', 'ok'),
|
|
155
|
+
turnEnd(15),
|
|
156
|
+
]
|
|
157
|
+
const record = turnLog.buildTurnRecords(events, { tools: 'summary' })[0]
|
|
158
|
+
assert.equal(record.tools.length, 1)
|
|
159
|
+
assert.match(record.tools[0], /dupTool\(\{\}\) → 成功/)
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
// —— 三层 caps(§3.1) ———————————————————————————————————————
|
|
163
|
+
|
|
164
|
+
test('user and model text are each capped at 2000 chars and always kept in full within that', () => {
|
|
165
|
+
const longUser = 'u'.repeat(3000)
|
|
166
|
+
const longModel = 'm'.repeat(3000)
|
|
167
|
+
const record = turnLog.buildTurnRecords(oneTurn({ user: longUser, assistant: longModel }))[0]
|
|
168
|
+
assert.ok(record.user.length <= turnLog.TURNLOG_USER_MODEL_CHARS + 1)
|
|
169
|
+
assert.ok(record.user.startsWith('u'.repeat(50)))
|
|
170
|
+
assert.ok(record.model.length <= turnLog.TURNLOG_USER_MODEL_CHARS + 1)
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
test('each tool line is capped at 160 chars', () => {
|
|
174
|
+
const tools = [['c1', 'tool', '{}', 'e'.repeat(500), true]]
|
|
175
|
+
const record = turnLog.buildTurnRecords(oneTurn({ user: 'hi', tools }), { tools: 'errors' })[0]
|
|
176
|
+
assert.ok(record.tools[0].length <= turnLog.TURNLOG_TOOL_LINE_CHARS + 1)
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
test('the 4000-char record cap cuts tool lines from the tail, never user/model', () => {
|
|
180
|
+
const pad = 'p'.repeat(130)
|
|
181
|
+
const tools = Array.from({ length: 30 }, (_, i) => [`c${i}`, `tool${i}`, `{"n":${i},"pad":"${pad}"}`, `r${String(i).repeat(140)}`, false])
|
|
182
|
+
const record = turnLog.buildTurnRecords(oneTurn({ user: '短问题', assistant: '短回答', tools }), { tools: 'summary' })[0]
|
|
183
|
+
assert.ok(JSON.stringify(record).length <= turnLog.TURNLOG_RECORD_CHARS, 'the serialized record fits the total cap')
|
|
184
|
+
assert.equal(record.user, '短问题')
|
|
185
|
+
assert.equal(record.model, '短回答')
|
|
186
|
+
const marker = record.tools[record.tools.length - 1]
|
|
187
|
+
assert.match(marker, /…\[另有 \d+ 条工具调用已省略\]/)
|
|
188
|
+
// 保留行按原始顺序装,来自头部;行格式与未超预算时一致(args 同样 120 字截断)。
|
|
189
|
+
const kept = record.tools.slice(0, -1)
|
|
190
|
+
const expectedLine = ([, name, args]) => `${name}(${args.length > 120 ? `${args.slice(0, 120)}…` : args}) → 成功`
|
|
191
|
+
assert.deepEqual(kept, tools.slice(0, kept.length).map(expectedLine))
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
// —— 设置面(§10.1 / 构件 4) ———————————————————————————————————
|
|
195
|
+
|
|
196
|
+
test('the two new settings survive the setSettings allowlist and reset to their defaults', async () => {
|
|
197
|
+
await rpc.dispatch({}, 'setSettings', { patch: { consolidationTurnLog: 'off', consolidationTurnLogTools: 'summary' } })
|
|
198
|
+
assert.equal(state.getSettings().consolidationTurnLog, 'off')
|
|
199
|
+
assert.equal(state.getSettings().consolidationTurnLogTools, 'summary')
|
|
200
|
+
// 设置档驱动默认 tools 档(无参数调用读设置)。
|
|
201
|
+
const record = turnLog.buildTurnRecords(oneTurn({ user: '看档位', tools: TOOL_FIXTURE }))[0]
|
|
202
|
+
assert.equal(record.tools.length, 2, 'the settings-chosen summary mode is now the default')
|
|
203
|
+
await assert.rejects(
|
|
204
|
+
rpc.dispatch({}, 'setSettings', { patch: { consolidationTurnLogTools: 'all' } }),
|
|
205
|
+
/invalid setting consolidationTurnLogTools/,
|
|
206
|
+
)
|
|
207
|
+
const reset = await rpc.dispatch({}, 'resetSettings', {})
|
|
208
|
+
assert.equal(reset.consolidationTurnLog, 'on')
|
|
209
|
+
assert.equal(reset.consolidationTurnLogTools, 'none')
|
|
210
|
+
})
|
|
211
|
+
|
|
212
|
+
// —— 落盘、增量读取与对账(§3.3) ————————————————————————————————
|
|
213
|
+
|
|
214
|
+
test('recordTurn appends one JSON line per turn and readIncrement returns whole turns only', () => {
|
|
215
|
+
const sessionId = 'incr-turns'
|
|
216
|
+
turnLog.recordTurn(sessionId, { seq: [0, 10], at: '2026-11-13T21:00:00.000Z', scene: null, user: '一', model: '甲' })
|
|
217
|
+
turnLog.recordTurn(sessionId, { seq: [11, 20], at: '2026-11-13T21:01:00.000Z', scene: null, user: '二', model: '乙' })
|
|
218
|
+
turnLog.recordTurn(sessionId, { seq: [21, 30], at: '2026-11-13T21:02:00.000Z', scene: null, user: '三', model: '丙' })
|
|
219
|
+
|
|
220
|
+
// afterSeq 落在回合中间(15):按 seqStart > afterSeq 过滤,[11,20] 整回合让位——
|
|
221
|
+
// 返回的永远只有完整回合,绝无半回合。
|
|
222
|
+
assert.deepEqual(turnLog.readIncrement(sessionId, 15).records.map((r) => r.seq), [[21, 30]])
|
|
223
|
+
assert.deepEqual(turnLog.readIncrement(sessionId, 10).records.map((r) => r.seq), [[11, 20], [21, 30]])
|
|
224
|
+
assert.deepEqual(turnLog.readIncrement(sessionId, 30).records, [])
|
|
225
|
+
assert.equal(turnLog.readIncrement(sessionId, -1).records.length, 3)
|
|
226
|
+
assert.equal(turnLog.readIncrement(sessionId, undefined).records.length, 3, 'a missing cursor reads the whole log')
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
test('recordTurn fills a missing timestamp and refuses records without a seq range', () => {
|
|
230
|
+
const sessionId = 'at-fill'
|
|
231
|
+
turnLog.recordTurn(sessionId, { seq: [0, 5], scene: null, user: 'a', model: 'b' })
|
|
232
|
+
const line = fs.readFileSync(turnLog.turnLogPath(sessionId), 'utf8').trim().split('\n')[0]
|
|
233
|
+
assert.ok(JSON.parse(line).at, 'recordTurn stamps the record when the turn/end had no time')
|
|
234
|
+
assert.equal(turnLog.recordTurn(sessionId, { user: 'no seq' }), null, 'unanchorable records are rejected with a warn')
|
|
235
|
+
})
|
|
236
|
+
|
|
237
|
+
test('verifyGap finds holes between and around records', () => {
|
|
238
|
+
const sessionId = 'gap-check'
|
|
239
|
+
turnLog.recordTurn(sessionId, { seq: [0, 10], at: 't', scene: null, user: 'a', model: 'b' })
|
|
240
|
+
turnLog.recordTurn(sessionId, { seq: [21, 30], at: 't', scene: null, user: 'c', model: 'd' })
|
|
241
|
+
const hole = turnLog.verifyGap(sessionId, 0, 30)
|
|
242
|
+
assert.equal(hole.ok, false)
|
|
243
|
+
assert.deepEqual(hole.missingRanges, [[11, 20]])
|
|
244
|
+
assert.equal(turnLog.verifyGap(sessionId, 0, 10).ok, true)
|
|
245
|
+
const empty = turnLog.verifyGap('gap-never-written', 5, 50)
|
|
246
|
+
assert.deepEqual(empty.missingRanges, [[5, 50]])
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
test('rebuildRange fills exactly the missing range from host events and is idempotent', () => {
|
|
250
|
+
const sessionId = 'rebuild'
|
|
251
|
+
const events = [
|
|
252
|
+
...oneTurn({ user: '第一回合', startSeq: 0 }),
|
|
253
|
+
...oneTurn({ user: '第二回合', startSeq: 40 }),
|
|
254
|
+
...oneTurn({ user: '第三回合', startSeq: 80 }),
|
|
255
|
+
]
|
|
256
|
+
// 只记了第一回合,中间与尾部都是洞。
|
|
257
|
+
turnLog.recordTurn(sessionId, { seq: [0, 17], at: 't', scene: null, user: '第一回合', model: '' })
|
|
258
|
+
|
|
259
|
+
const first = turnLog.rebuildRange(sessionId, 18, 120, events)
|
|
260
|
+
assert.equal(first.ok, true)
|
|
261
|
+
assert.equal(first.rebuilt, 2)
|
|
262
|
+
const { records } = turnLog.readIncrement(sessionId, 17)
|
|
263
|
+
assert.deepEqual(records.map((r) => r.seq[0]), [40, 80])
|
|
264
|
+
|
|
265
|
+
// 再跑一遍不产生重复行:重建幂等。
|
|
266
|
+
const second = turnLog.rebuildRange(sessionId, 0, 120, events)
|
|
267
|
+
assert.equal(second.rebuilt, 0)
|
|
268
|
+
assert.equal(turnLog.readIncrement(sessionId, -1).records.length, 3)
|
|
269
|
+
// 请求区间之外的事件不进日志。
|
|
270
|
+
const outside = turnLog.rebuildRange(sessionId, 1000, 2000, events)
|
|
271
|
+
assert.equal(outside.rebuilt, 0)
|
|
272
|
+
})
|
|
273
|
+
|
|
274
|
+
test('readers tolerate bad lines: skipped, counted, never thrown', () => {
|
|
275
|
+
const sessionId = 'bad-lines'
|
|
276
|
+
turnLog.recordTurn(sessionId, { seq: [0, 10], at: 't', scene: null, user: 'a', model: 'b' })
|
|
277
|
+
fs.appendFileSync(turnLog.turnLogPath(sessionId), '{this is not json\n', 'utf8')
|
|
278
|
+
turnLog.recordTurn(sessionId, { seq: [11, 20], at: 't', scene: null, user: 'c', model: 'd' })
|
|
279
|
+
|
|
280
|
+
const inc = turnLog.readIncrement(sessionId, -1)
|
|
281
|
+
assert.equal(inc.records.length, 2)
|
|
282
|
+
assert.equal(inc.badLines, 1)
|
|
283
|
+
assert.equal(turnLog.verifyGap(sessionId, 0, 20).badLines, 1)
|
|
284
|
+
assert.equal(turnLog.tailSlice(sessionId, 10_000).records.length, 2)
|
|
285
|
+
})
|
|
286
|
+
|
|
287
|
+
// —— 头部裁剪(§3.4:绝不裁进未结算区间) ————————————————————————————
|
|
288
|
+
|
|
289
|
+
function writeBulkyTurns(sessionId, count) {
|
|
290
|
+
for (let i = 0; i < count; i++) {
|
|
291
|
+
turnLog.recordTurn(sessionId, { seq: [i * 10, i * 10 + 9], at: 't', scene: null, user: `回合${i}`.padEnd(40, '字'), model: '' })
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
test('pruneHead drops settled head records down to the budget, never past lastSleepSeq', () => {
|
|
296
|
+
const sessionId = 'prune-head'
|
|
297
|
+
writeBulkyTurns(sessionId, 6)
|
|
298
|
+
// lastSleepSeq = 49:前 5 条已结算,最后一条(seqEnd 59)未结算。
|
|
299
|
+
const report = turnLog.pruneHead(sessionId, 300, 49)
|
|
300
|
+
assert.ok(report.pruned > 0, 'settled head records were cut')
|
|
301
|
+
assert.ok(report.charsAfter <= 300)
|
|
302
|
+
const after = turnLog.readIncrement(sessionId, -1).records
|
|
303
|
+
assert.deepEqual(after.map((r) => r.seq[0]), [30, 40, 50], 'the cut stops inside settled range only; the unsettled turn survives')
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
test('pruneHead lets the file stay over budget rather than cut into the unsettled range', () => {
|
|
307
|
+
const sessionId = 'prune-head-over'
|
|
308
|
+
writeBulkyTurns(sessionId, 6)
|
|
309
|
+
// lastSleepSeq = 19:只有前两条可裁,预算再小也不越过 seqEnd 19。
|
|
310
|
+
const report = turnLog.pruneHead(sessionId, 100, 19)
|
|
311
|
+
assert.ok(report.pruned > 0)
|
|
312
|
+
assert.ok(report.charsAfter > 100, 'the file may stay over budget instead of pruning unsettled turns')
|
|
313
|
+
const after = turnLog.readIncrement(sessionId, -1).records
|
|
314
|
+
assert.ok(after.every((r) => r.seq[0] >= 20), 'every settled head record was taken; the unsettled tail is intact')
|
|
315
|
+
|
|
316
|
+
// 没有结算游标:整份日志都是未结算段,一条不裁。
|
|
317
|
+
const sessionId2 = 'prune-head-unsettled'
|
|
318
|
+
writeBulkyTurns(sessionId2, 3)
|
|
319
|
+
const untouched = turnLog.pruneHead(sessionId2, 50, null)
|
|
320
|
+
assert.equal(untouched.pruned, 0)
|
|
321
|
+
assert.equal(turnLog.readIncrement(sessionId2, -1).records.length, 3)
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
test('pruneHead preserves bad lines instead of dropping what it could not read', () => {
|
|
325
|
+
const sessionId = 'prune-bad'
|
|
326
|
+
turnLog.recordTurn(sessionId, { seq: [0, 9], at: 't', scene: null, user: 'a'.repeat(60), model: '' })
|
|
327
|
+
fs.appendFileSync(turnLog.turnLogPath(sessionId), 'garbage line\n', 'utf8')
|
|
328
|
+
turnLog.recordTurn(sessionId, { seq: [10, 19], at: 't', scene: null, user: 'b'.repeat(60), model: '' })
|
|
329
|
+
turnLog.pruneHead(sessionId, 80, 100)
|
|
330
|
+
const raw = fs.readFileSync(turnLog.turnLogPath(sessionId), 'utf8')
|
|
331
|
+
assert.ok(raw.includes('garbage line'), 'a bad line cannot be proven settled, so it is kept')
|
|
332
|
+
})
|
|
333
|
+
|
|
334
|
+
// —— tailSlice(§5.1 交接尾部的来源) ——————————————————————————————
|
|
335
|
+
|
|
336
|
+
test('tailSlice takes whole turns from the tail within the char budget', () => {
|
|
337
|
+
const sessionId = 'tail'
|
|
338
|
+
turnLog.recordTurn(sessionId, { seq: [0, 9], at: 't', scene: null, user: 'a'.repeat(100), model: '' })
|
|
339
|
+
turnLog.recordTurn(sessionId, { seq: [10, 19], at: 't', scene: null, user: 'b'.repeat(100), model: '' })
|
|
340
|
+
turnLog.recordTurn(sessionId, { seq: [20, 29], at: 't', scene: null, user: 'c'.repeat(100), model: '' })
|
|
341
|
+
const slice = turnLog.tailSlice(sessionId, 400)
|
|
342
|
+
assert.deepEqual(slice.records.map((r) => r.seq[0]), [10, 20], 'whole turns from the tail, chronological')
|
|
343
|
+
assert.ok(slice.chars <= 400)
|
|
344
|
+
assert.ok(!slice.text.includes('aaaa'), 'the oldest turn did not fit the budget and was left out')
|
|
345
|
+
assert.equal(slice.text.split('\n').length, 2, 'the text is whole-turn JSONL from the tail')
|
|
346
|
+
})
|
|
347
|
+
|
|
348
|
+
// —— 删除与休眠 GC(§3.4) ——————————————————————————————————————
|
|
349
|
+
|
|
350
|
+
test('deleteTurnLog removes the file and tolerates a missing one', () => {
|
|
351
|
+
const sessionId = 'delete-me'
|
|
352
|
+
turnLog.recordTurn(sessionId, { seq: [0, 1], at: 't', scene: null, user: 'a', model: 'b' })
|
|
353
|
+
assert.ok(fs.existsSync(turnLog.turnLogPath(sessionId)))
|
|
354
|
+
assert.equal(turnLog.deleteTurnLog(sessionId).ok, true)
|
|
355
|
+
assert.equal(fs.existsSync(turnLog.turnLogPath(sessionId)), false)
|
|
356
|
+
assert.equal(turnLog.deleteTurnLog(sessionId).ok, true, 'deleting a missing log is a no-op')
|
|
357
|
+
})
|
|
358
|
+
|
|
359
|
+
test('gcTurnLogs deletes only when idle past the threshold AND fully settled', () => {
|
|
360
|
+
const now = Date.now()
|
|
361
|
+
const old = new Date(now - 40 * 86_400_000).toISOString()
|
|
362
|
+
const fresh = new Date(now - 1 * 86_400_000).toISOString()
|
|
363
|
+
const writeLog = (sessionId, lastSeqEnd) => {
|
|
364
|
+
turnLog.recordTurn(sessionId, { seq: [0, lastSeqEnd], at: 't', scene: null, user: 'a', model: 'b' })
|
|
365
|
+
}
|
|
366
|
+
writeLog('gc-settled', 30)
|
|
367
|
+
writeLog('gc-unsettled', 30)
|
|
368
|
+
writeLog('gc-recent', 30)
|
|
369
|
+
writeLog('gc-never-settled', 30)
|
|
370
|
+
|
|
371
|
+
const bindings = [
|
|
372
|
+
{ sessionId: 'gc-settled', lastTurnAt: old, lastSleepSeq: 30 },
|
|
373
|
+
{ sessionId: 'gc-unsettled', lastTurnAt: old, lastSleepSeq: 10 },
|
|
374
|
+
{ sessionId: 'gc-recent', lastTurnAt: fresh, lastSleepSeq: 30 },
|
|
375
|
+
{ sessionId: 'gc-never-settled', lastTurnAt: old },
|
|
376
|
+
{ sessionId: 'gc-no-log', lastTurnAt: old, lastSleepSeq: 30 },
|
|
377
|
+
]
|
|
378
|
+
const dry = turnLog.gcTurnLogs(bindings, { now, dryRun: true })
|
|
379
|
+
assert.deepEqual(dry.deleted, ['gc-settled'])
|
|
380
|
+
assert.ok(fs.existsSync(turnLog.turnLogPath('gc-settled')), 'dry-run must not delete')
|
|
381
|
+
assert.ok(dry.kept.some((k) => k.sessionId === 'gc-unsettled' && k.reason === 'unsettled-increment'))
|
|
382
|
+
assert.ok(dry.kept.some((k) => k.sessionId === 'gc-recent' && k.reason === 'recent-activity'))
|
|
383
|
+
assert.ok(dry.kept.some((k) => k.sessionId === 'gc-never-settled' && k.reason === 'never-settled'))
|
|
384
|
+
assert.ok(!dry.deleted.includes('gc-no-log') && !dry.kept.some((k) => k.sessionId === 'gc-no-log'), 'a session without a log is not reported')
|
|
385
|
+
|
|
386
|
+
const applied = turnLog.gcTurnLogs(bindings, { now })
|
|
387
|
+
assert.deepEqual(applied.deleted, ['gc-settled'])
|
|
388
|
+
assert.equal(fs.existsSync(turnLog.turnLogPath('gc-settled')), false)
|
|
389
|
+
assert.ok(fs.existsSync(turnLog.turnLogPath('gc-unsettled')), 'the unsettled log is the increment source and stays')
|
|
390
|
+
})
|
|
391
|
+
|
|
392
|
+
// —— 订阅接线(§3.2:session/event 全局订阅,worker 会话绝不记) ————————————
|
|
393
|
+
|
|
394
|
+
function fakeCtx() {
|
|
395
|
+
const handlers = new Map()
|
|
396
|
+
return {
|
|
397
|
+
ctx: { on: (name, handler) => { if (!handlers.has(name)) handlers.set(name, []); handlers.get(name).push(handler); return () => { handlers.set(name, handlers.get(name).filter((h) => h !== handler)) } } },
|
|
398
|
+
emit(name, ...args) { for (const handler of handlers.get(name) || []) handler(...args) },
|
|
399
|
+
off(name) { handlers.delete(name) },
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function bindSession(sessionId, { origin, useLibrary, sessionGone } = {}) {
|
|
404
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'ws', sessionId) })
|
|
405
|
+
const patch = {}
|
|
406
|
+
if (useLibrary !== undefined) patch.useLibrary = useLibrary
|
|
407
|
+
if (sessionGone !== undefined) patch.sessionGone = sessionGone
|
|
408
|
+
if (Object.keys(patch).length > 0) state.setSessionBinding(sessionId, patch)
|
|
409
|
+
return { header: { id: sessionId, origin, cwd: path.join(home, 'ws', sessionId) } }
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
test('the session/event recorder writes one line per turn for admitted sessions', () => {
|
|
413
|
+
const { ctx, emit } = fakeCtx()
|
|
414
|
+
const dispose = registerTurnLogRecorder(ctx)
|
|
415
|
+
const session = bindSession('rec-on')
|
|
416
|
+
emit('session/event', session, turnStart(0, 1))
|
|
417
|
+
emit('session/event', session, userMessage(1, '记下这一句'))
|
|
418
|
+
emit('session/event', session, assistantMessage(2, '好的。'))
|
|
419
|
+
emit('session/event', session, turnEnd(3, { turn: 1 }))
|
|
420
|
+
|
|
421
|
+
const { records } = turnLog.readIncrement('rec-on', -1)
|
|
422
|
+
assert.equal(records.length, 1)
|
|
423
|
+
assert.equal(records[0].user, '记下这一句')
|
|
424
|
+
assert.equal(records[0].model, '好的。')
|
|
425
|
+
dispose()
|
|
426
|
+
})
|
|
427
|
+
|
|
428
|
+
test('worker (subagent) sessions, unbound sessions and the off switch never record', () => {
|
|
429
|
+
const { ctx, emit } = fakeCtx()
|
|
430
|
+
const dispose = registerTurnLogRecorder(ctx)
|
|
431
|
+
const subagent = bindSession('rec-subagent', { origin: 'subagent' })
|
|
432
|
+
state.ensureSession('rec-subagent', { cwd: path.join(home, 'ws', 'rec-subagent') })
|
|
433
|
+
emit('session/event', subagent, turnStart(0))
|
|
434
|
+
emit('session/event', subagent, userMessage(1, 'worker 的回合'))
|
|
435
|
+
emit('session/event', subagent, turnEnd(2))
|
|
436
|
+
assert.equal(fs.existsSync(turnLog.turnLogPath('rec-subagent')), false, 'worker sessions are never recorded')
|
|
437
|
+
|
|
438
|
+
const unbound = { header: { id: 'rec-unbound', origin: undefined } }
|
|
439
|
+
emit('session/event', unbound, turnStart(0))
|
|
440
|
+
emit('session/event', unbound, userMessage(1, '没有绑定'))
|
|
441
|
+
emit('session/event', unbound, turnEnd(2))
|
|
442
|
+
assert.equal(fs.existsSync(turnLog.turnLogPath('rec-unbound')), false)
|
|
443
|
+
|
|
444
|
+
const offSession = bindSession('rec-off', { useLibrary: false })
|
|
445
|
+
emit('session/event', offSession, turnStart(0))
|
|
446
|
+
emit('session/event', offSession, userMessage(1, '库关了'))
|
|
447
|
+
emit('session/event', offSession, turnEnd(2))
|
|
448
|
+
assert.equal(fs.existsSync(turnLog.turnLogPath('rec-off')), false, 'useLibrary === false sessions are skipped')
|
|
449
|
+
|
|
450
|
+
state.updateSettings({ consolidationTurnLog: 'off' })
|
|
451
|
+
const switchOff = bindSession('rec-switch-off')
|
|
452
|
+
emit('session/event', switchOff, turnStart(0))
|
|
453
|
+
emit('session/event', switchOff, userMessage(1, '开关关了'))
|
|
454
|
+
emit('session/event', switchOff, turnEnd(2))
|
|
455
|
+
assert.equal(fs.existsSync(turnLog.turnLogPath('rec-switch-off')), false, 'the off switch stops the recorder')
|
|
456
|
+
state.updateSettings({ consolidationTurnLog: 'on' })
|
|
457
|
+
dispose()
|
|
458
|
+
})
|
|
459
|
+
|
|
460
|
+
test('a deleted session (sessionGone) loses its log on session/disposed', () => {
|
|
461
|
+
const { ctx, emit } = fakeCtx()
|
|
462
|
+
const dispose = registerTurnLogRecorder(ctx)
|
|
463
|
+
const session = bindSession('rec-gone', { sessionGone: true })
|
|
464
|
+
turnLog.recordTurn('rec-gone', { seq: [0, 5], at: 't', scene: null, user: 'a', model: 'b' })
|
|
465
|
+
assert.ok(fs.existsSync(turnLog.turnLogPath('rec-gone')))
|
|
466
|
+
emit('session/disposed', session)
|
|
467
|
+
assert.equal(fs.existsSync(turnLog.turnLogPath('rec-gone')), false, 'sessionGone bindings get their log deleted')
|
|
468
|
+
// 未标 sessionGone 的销毁(进程内卸载)不删:日志比会话活得长。
|
|
469
|
+
const alive = bindSession('rec-alive')
|
|
470
|
+
turnLog.recordTurn('rec-alive', { seq: [0, 5], at: 't', scene: null, user: 'a', model: 'b' })
|
|
471
|
+
emit('session/disposed', alive)
|
|
472
|
+
assert.ok(fs.existsSync(turnLog.turnLogPath('rec-alive')))
|
|
473
|
+
dispose()
|
|
474
|
+
})
|
package/tests/webui.test.mjs
CHANGED
|
@@ -217,6 +217,25 @@ test('the settings button preserves the host SPA and links to individual pages',
|
|
|
217
217
|
assert.match(client, /h\(SettingsPage, \{ ctx, t, embedded: false, standalone: true \}\)/)
|
|
218
218
|
assert.match(client, /mountStandalone/)
|
|
219
219
|
})
|
|
220
|
+
test('the shell keeps no always-on compositor drivers', () => {
|
|
221
|
+
// GPU 占用高的根因不是算力,是「空闲期仍在持续产帧」:无限 CSS 动画让合成器
|
|
222
|
+
// 永远不睡(1.3.3 实测空闲 ~99fps),全屏 backdrop-filter 再每帧重算模糊。
|
|
223
|
+
// 守卫用 scripts/check-idle-compositing.mjs 真机数帧;这里静态拦复发。
|
|
224
|
+
const css = fs.readFileSync(new URL('../lib/webui/standalone.css', import.meta.url), 'utf8')
|
|
225
|
+
.replace(/\/\*[\s\S]*?\*\//g, '') // 注释里会引用旧写法(will-change / infinite),不能算声明
|
|
226
|
+
const client = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
|
|
227
|
+
const infinite = [...css.matchAll(/animation:[^;]*infinite[^;]*/g)].map(m => m[0])
|
|
228
|
+
assert.ok(infinite.every(rule => /boot-ring|boot-shimmer/.test(rule)),
|
|
229
|
+
`always-on animation outside the boot veil: ${infinite.join(' | ')}`)
|
|
230
|
+
const ambient = css.slice(css.indexOf('.ambient i {'), css.indexOf('}', css.indexOf('.ambient i {')))
|
|
231
|
+
assert.ok(!/will-change|animation/.test(ambient), 'the ambient blobs must stay static, unlayered')
|
|
232
|
+
const blurred = css.split('}').filter(block => /backdrop-filter:/.test(block))
|
|
233
|
+
assert.ok(blurred.every(block => /\.topbar\s*\{|\.boot-card\s*\{/.test(block)),
|
|
234
|
+
'blur belongs to small chrome only, never to the rail, cards or drawer')
|
|
235
|
+
assert.ok(!/backdrop-filter:/.test(client), 'the shared UI must not blur full-screen surfaces')
|
|
236
|
+
assert.ok(!/const timer = setInterval\(paint/.test(client), 'the minimap is driven by onPaint, not a poll')
|
|
237
|
+
assert.match(client, /notifyRef\.current = paint/)
|
|
238
|
+
})
|
|
220
239
|
test('RPC still uses stable envelopes and rejects non-UI GETs', async () => {
|
|
221
240
|
const res = await request('/dsh-memu-memory/listLibraries', 'POST', { type: 'client-request', rpcId: 'wall-test', method: 'listLibraries', payload: {} })
|
|
222
241
|
assert.equal(res.status, 200)
|