dsh-memu-memory 1.3.2 → 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 +11 -3
- package/CHANGELOG.md +57 -3
- package/README.md +6 -11
- package/README.zh.md +6 -11
- 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 +21 -0
- package/docs/contributing.md +5 -2
- package/docs/memory-semantics.md +17 -0
- package/docs/troubleshooting.md +44 -0
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +125 -18
- 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 +14 -1
- package/lib/state.js +11 -1
- package/lib/turn-log.js +522 -0
- package/lib/webui/graph-view.bundle.js +1 -1
- package/lib/webui/graph-view.js +53 -25
- 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/build-graph.mjs +32 -4
- package/scripts/check-all.mjs +2 -0
- package/scripts/check-idle-compositing.mjs +61 -0
- package/scripts/make-readme-shots.mjs +59 -0
- package/scripts/prune-turnlogs.mjs +30 -0
- package/tests/browser.test.mjs +27 -0
- package/tests/client-render.test.mjs +171 -0
- package/tests/consolidation-snapshot.test.mjs +89 -1
- package/tests/graph-view.test.mjs +60 -3
- 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,1046 @@
|
|
|
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-worker-lifecycle-'))
|
|
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 workerPool = await import('../lib/worker-pool.js')
|
|
13
|
+
const turnLog = await import('../lib/turn-log.js')
|
|
14
|
+
const { privateRemember } = await import('../lib/memory.js')
|
|
15
|
+
const { requestPrivateConsolidation, requestHistoricalConsolidation, alignWindowToTurn, selectWorkerWindow } = await import('../lib/private.js')
|
|
16
|
+
|
|
17
|
+
// 默认推理强度不参与本文件的断言(路由继承由 consolidation-fork.test.mjs 单独覆盖)。
|
|
18
|
+
state.updateSettings({ consolidationReasoningEffort: 'inherit' })
|
|
19
|
+
|
|
20
|
+
/** 给会话绑定的库写一条记忆:目录头(memoryCatalogEvent)只在库非空时才有内容。 */
|
|
21
|
+
async function seedMemory(sessionId, title, content) {
|
|
22
|
+
const result = await privateRemember({
|
|
23
|
+
exec: { agent: { session: { header: { id: sessionId } } } },
|
|
24
|
+
content,
|
|
25
|
+
title,
|
|
26
|
+
source: 'inferred',
|
|
27
|
+
})
|
|
28
|
+
assert.ok(result?.id, 'the seeded memory landed: ' + JSON.stringify(result).slice(0, 200))
|
|
29
|
+
return result.id
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
test.after(() => {
|
|
33
|
+
try { state.flushState() } catch {}
|
|
34
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
// —— 宿主事件 fixture(带 turn 包装:turn-log 缺口重建依赖闭合回合) ——————————
|
|
38
|
+
|
|
39
|
+
function wrappedTurn(seed, { user = '帮我看看这个整理 worker 为什么一直建不起来', sceneTime = null } = {}) {
|
|
40
|
+
const events = [
|
|
41
|
+
{ seq: seed, type: 'turn/start', data: { turn: 1 } },
|
|
42
|
+
{ seq: seed + 1, type: 'user/message', time: seed, data: { source: { kind: 'user' }, content: [{ type: 'text', text: user }], ...(sceneTime ? { sceneTime } : {}) } },
|
|
43
|
+
{ seq: seed + 2, type: 'assistant/message', time: seed, data: { message: { content: [{ type: 'tool-call', id: 'c1', name: 'read', arguments: '{}' }] } } },
|
|
44
|
+
{ seq: seed + 3, type: 'tool/call', time: seed, data: { callId: 'c1', name: 'read', arguments: '{}' } },
|
|
45
|
+
{ seq: seed + 4, type: 'tool/result', time: seed, data: { message: { callId: 'c1', content: [{ type: 'text', text: 'ok' }] } } },
|
|
46
|
+
{ seq: seed + 5, type: 'assistant/message', time: seed, data: { message: { content: [{ type: 'text', text: '看到了' }] } } },
|
|
47
|
+
{ seq: seed + 6, type: 'turn/end', time: seed, data: { turn: 1, reason: { kind: 'completed' } } },
|
|
48
|
+
]
|
|
49
|
+
return events
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// —— 宿主 mock(形状沿用 consolidation-fork.test.mjs 的 host(),另加:
|
|
53
|
+
// 持久 worker 的进程内注册表 / resume 能力位 / whenIdle 计数) ————————
|
|
54
|
+
|
|
55
|
+
const META_KEYS = ['cwd', 'parentSession', 'isSeeded', 'origin', 'delegationDepth', 'agentPreset']
|
|
56
|
+
|
|
57
|
+
function assertHostCreateAccepts(spec = {}) {
|
|
58
|
+
const meta = spec.meta ?? {}
|
|
59
|
+
for (const key of Object.keys(meta)) {
|
|
60
|
+
if (!META_KEYS.includes(key)) throw new Error(`session meta "${key}" is not a header field`)
|
|
61
|
+
}
|
|
62
|
+
if (meta.isSeeded === true) {
|
|
63
|
+
if (spec.seed === undefined) throw new Error('seeded session requires an explicit constructor seed')
|
|
64
|
+
if (spec.inheritedEventCount === undefined) throw new Error('seeded session requires an inherited event count')
|
|
65
|
+
} else if (spec.inheritedEventCount !== undefined && spec.inheritedEventCount !== 0) {
|
|
66
|
+
throw new Error('unseeded session inherited event count must be 0')
|
|
67
|
+
} else if (spec.seed !== undefined) {
|
|
68
|
+
throw new Error('unseeded session must not carry a seed')
|
|
69
|
+
}
|
|
70
|
+
if (spec.agentOptions !== undefined) {
|
|
71
|
+
if (!spec.agentOptions || typeof spec.agentOptions.provider !== 'string' || typeof spec.agentOptions.model !== 'string') {
|
|
72
|
+
throw new Error('agentOptions must carry the parent provider and model')
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const RECEIPT_TICK = String.fromCharCode(96)
|
|
78
|
+
function receiptFence(range, identity) {
|
|
79
|
+
return [
|
|
80
|
+
RECEIPT_TICK + RECEIPT_TICK + RECEIPT_TICK + 'memu-consolidation-receipt',
|
|
81
|
+
JSON.stringify({
|
|
82
|
+
version: 1, ...identity,
|
|
83
|
+
status: 'completed', outcome: 'no_value', checkedRange: range,
|
|
84
|
+
createdIds: [], updatedIds: [], heldIds: [], reasonCode: null, retryable: false,
|
|
85
|
+
}),
|
|
86
|
+
RECEIPT_TICK + RECEIPT_TICK + RECEIPT_TICK,
|
|
87
|
+
].join('\n')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* worker 模式宿主 mock。resume: 'none'(宿主没有 resume 服务)| 'works' | 'fails'。
|
|
92
|
+
* whenIdleCalls:前 N 次 whenIdle() 挂起(供超时用例),之后立即 resolve
|
|
93
|
+
* (retireWorker 的 bounded 等待不能挂住测试)。
|
|
94
|
+
*/
|
|
95
|
+
function host({
|
|
96
|
+
live = true,
|
|
97
|
+
resume = 'none',
|
|
98
|
+
turnReason = { kind: 'completed' },
|
|
99
|
+
emitTurnEnd = true,
|
|
100
|
+
delayTurn = false,
|
|
101
|
+
headerTools = null,
|
|
102
|
+
parentOptions = true,
|
|
103
|
+
} = {}) {
|
|
104
|
+
const rec = {
|
|
105
|
+
liveFollowups: [], created: [], forkFollowups: [], disposed: [], resumed: [],
|
|
106
|
+
sessionHandlers: [],
|
|
107
|
+
}
|
|
108
|
+
const registry = new Map() // 进程内 agent 注册表:agents.get 只查这里
|
|
109
|
+
// delayTurnMode=true 时 followup 不立即发回合事件,而是把回合挂起(whenIdle 等待),
|
|
110
|
+
// 直到 ctx.completeTurn() 才落地——真实模拟"超时后上一回合还在跑"的时序(A1)。
|
|
111
|
+
let delayTurnMode = delayTurn
|
|
112
|
+
let childSeq = 0
|
|
113
|
+
const transcript = [...wrappedTurn(0)]
|
|
114
|
+
|
|
115
|
+
const makeRecord = (id) => {
|
|
116
|
+
const childSession = { id } // 宿主语义:handle.agent.session 与 session/event 的 session 是同一个对象
|
|
117
|
+
let pending = null // 在跑回合:{ promise, finish }
|
|
118
|
+
const emitTurn = () => {
|
|
119
|
+
childSeq += 1
|
|
120
|
+
const child = state.getSessionBinding(id)
|
|
121
|
+
const fromSeq = Number.isSafeInteger(child?.snapshotFromSeq) ? child.snapshotFromSeq : 0
|
|
122
|
+
const throughSeq = Number.isSafeInteger(child?.snapshotThroughSeq) ? child.snapshotThroughSeq : 6
|
|
123
|
+
const text = turnReason?.kind === 'completed' ? receiptFence({ fromSeq, throughSeq }, child || {}) : ''
|
|
124
|
+
for (const handler of rec.sessionHandlers) {
|
|
125
|
+
if (text) handler(childSession, { type: 'assistant/message', seq: 900 + childSeq, data: { message: { content: [{ type: 'text', text }] } } })
|
|
126
|
+
}
|
|
127
|
+
for (const handler of rec.sessionHandlers) {
|
|
128
|
+
handler(childSession, { type: 'turn/end', seq: 901 + childSeq, data: { turn: childSeq, reason: turnReason } })
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
agent: {
|
|
133
|
+
session: childSession,
|
|
134
|
+
followup: (message) => {
|
|
135
|
+
rec.forkFollowups.push({ child: id, message })
|
|
136
|
+
if (!emitTurnEnd) return
|
|
137
|
+
if (delayTurnMode) {
|
|
138
|
+
let resolve
|
|
139
|
+
const promise = new Promise((r) => { resolve = r })
|
|
140
|
+
pending = { promise, finish: () => { pending = null; emitTurn(); resolve() } }
|
|
141
|
+
} else {
|
|
142
|
+
emitTurn()
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
// 真实语义:回合落地(pending 清空)whenIdle 才 resolve;回合在跑则一直等。
|
|
146
|
+
whenIdle: async () => { if (pending) await pending.promise },
|
|
147
|
+
// 保真:真实宿主 agents.get 返回裸 Agent,dispose 在裸 Agent 上(retireWorker 用)。
|
|
148
|
+
dispose: async () => { rec.disposed.push(id) },
|
|
149
|
+
},
|
|
150
|
+
dispose: async () => { rec.disposed.push(id) },
|
|
151
|
+
_finishTurn: () => { if (pending) pending.finish() },
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const parentRecord = live
|
|
156
|
+
? {
|
|
157
|
+
followup: (message) => rec.liveFollowups.push({ message }),
|
|
158
|
+
...(parentOptions ? { options: { provider: 'test-provider', model: 'test-model' } } : {}),
|
|
159
|
+
...(headerTools ? { session: { requestHeader: () => ({ tools: headerTools.map((name) => ({ name })) }) } } : {}),
|
|
160
|
+
}
|
|
161
|
+
: null
|
|
162
|
+
|
|
163
|
+
const ctx = {
|
|
164
|
+
rec,
|
|
165
|
+
restart: () => registry.clear(),
|
|
166
|
+
on: (name, handler) => {
|
|
167
|
+
if (name !== 'session/event') return () => {}
|
|
168
|
+
rec.sessionHandlers.push(handler)
|
|
169
|
+
return () => {
|
|
170
|
+
const index = rec.sessionHandlers.indexOf(handler)
|
|
171
|
+
if (index >= 0) rec.sessionHandlers.splice(index, 1)
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
get: (name) => {
|
|
175
|
+
if (name === 'agents') {
|
|
176
|
+
const agents = {
|
|
177
|
+
// 保真(bench 实测 bug #1):真实宿主 get 返回**裸 Agent**(core/agent/src/index.ts:580
|
|
178
|
+
// `store.get(id)?.agent`),create/resume 返回 handle 包装({agent,...})。
|
|
179
|
+
// mock 曾让 get 也返回包装——恰好掩盖了复用派发读 handle.agent 崩溃的 bug。
|
|
180
|
+
get: (id) => {
|
|
181
|
+
const hit = registry.get(id)
|
|
182
|
+
if (hit) return hit.agent
|
|
183
|
+
return live && id === currentSession ? parentRecord : undefined
|
|
184
|
+
},
|
|
185
|
+
create: async (spec) => {
|
|
186
|
+
assertHostCreateAccepts(spec)
|
|
187
|
+
// 真实宿主语义:同 id 会话文件已存在时拒绝 create(bench 实测 already exists 连挂)。
|
|
188
|
+
if (registry.has(spec.sessionId)) {
|
|
189
|
+
throw new Error('session "' + spec.sessionId + '" already exists')
|
|
190
|
+
}
|
|
191
|
+
rec.created.push(spec)
|
|
192
|
+
const record = makeRecord(spec.sessionId)
|
|
193
|
+
registry.set(spec.sessionId, record)
|
|
194
|
+
return record
|
|
195
|
+
},
|
|
196
|
+
}
|
|
197
|
+
if (resume !== 'none') {
|
|
198
|
+
agents.resume = async ({ resumeSessionId } = {}) => {
|
|
199
|
+
rec.resumed.push(resumeSessionId)
|
|
200
|
+
if (resume === 'works') {
|
|
201
|
+
const hit = registry.get(resumeSessionId)
|
|
202
|
+
if (hit) return hit
|
|
203
|
+
const record = makeRecord(resumeSessionId)
|
|
204
|
+
registry.set(resumeSessionId, record)
|
|
205
|
+
return record
|
|
206
|
+
}
|
|
207
|
+
throw new Error('no live agent for ' + String(resumeSessionId))
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return agents
|
|
211
|
+
}
|
|
212
|
+
if (name === 'sessionQuery') {
|
|
213
|
+
return {
|
|
214
|
+
readSession: async () => ({ events: [...transcript], session: { cwd: path.join(home, 'proj'), agentPreset: 'coding' } }),
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return undefined
|
|
218
|
+
},
|
|
219
|
+
pushTurn: (events) => { transcript.push(...events) },
|
|
220
|
+
// A1 时序控制:切换"回合延迟落地"模式;completeTurn 让所有在跑回合落地(发事件 + resolve whenIdle)。
|
|
221
|
+
setDelayTurn: (value) => { delayTurnMode = Boolean(value) },
|
|
222
|
+
completeTurn: () => { for (const record of registry.values()) record._finishTurn() },
|
|
223
|
+
}
|
|
224
|
+
let currentSession = null
|
|
225
|
+
ctx.bindSession = (sessionId) => {
|
|
226
|
+
currentSession = sessionId
|
|
227
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
|
|
228
|
+
return sessionId
|
|
229
|
+
}
|
|
230
|
+
return ctx
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function textOf(followup) {
|
|
234
|
+
const content = followup?.message?.content
|
|
235
|
+
if (typeof content === 'string') return content
|
|
236
|
+
return (Array.isArray(content) ? content : []).map((block) => (block?.type === 'text' && typeof block.text === 'string' ? block.text : '')).join('\n')
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function runWorkerWindow(ctx, sessionId, options = {}) {
|
|
240
|
+
return requestHistoricalConsolidation(ctx, sessionId, options)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// —— 设置面(§10.1/§10.2) ————————————————————————————————————————
|
|
244
|
+
|
|
245
|
+
test('consolidationRunner defaults to fork, round-trips through rpc, and validates its enum', async () => {
|
|
246
|
+
const rpc = await import('../lib/rpc.js')
|
|
247
|
+
assert.equal(state.DEFAULT_SETTINGS.consolidationRunner, 'fork', 'T1 默认保持现状路径')
|
|
248
|
+
await rpc.dispatch({}, 'setSettings', { patch: { consolidationRunner: 'worker' } })
|
|
249
|
+
assert.equal(state.getSettings().consolidationRunner, 'worker')
|
|
250
|
+
await assert.rejects(
|
|
251
|
+
rpc.dispatch({}, 'setSettings', { patch: { consolidationRunner: 'thread' } }),
|
|
252
|
+
/invalid setting consolidationRunner/,
|
|
253
|
+
)
|
|
254
|
+
const reset = await rpc.dispatch({}, 'resetSettings', {})
|
|
255
|
+
assert.equal(reset.consolidationRunner, 'fork')
|
|
256
|
+
})
|
|
257
|
+
|
|
258
|
+
// —— 'fork' 默认路径回归 ————————————————————————————————————————————
|
|
259
|
+
|
|
260
|
+
test('the default runner keeps the seeded per-window fork path unchanged', async () => {
|
|
261
|
+
const ctx = host({})
|
|
262
|
+
const sessionId = ctx.bindSession('wl-fork-default')
|
|
263
|
+
const result = await requestPrivateConsolidation(ctx, sessionId)
|
|
264
|
+
assert.equal(result.ok, true)
|
|
265
|
+
assert.equal(result.settled, true)
|
|
266
|
+
assert.equal(ctx.rec.created.length, 1)
|
|
267
|
+
const spec = ctx.rec.created[0]
|
|
268
|
+
assert.equal(spec.sessionId.startsWith('memu-consolidate-'), true, 'fork path keeps its session-id scheme')
|
|
269
|
+
assert.equal(spec.meta.isSeeded, true)
|
|
270
|
+
assert.equal(spec.meta.origin, 'subagent')
|
|
271
|
+
assert.equal(spec.inheritedEventCount, 7, 'the whole wrapped transcript is seeded')
|
|
272
|
+
assert.ok(spec.seed, 'the fork carries a buildForkSeed payload')
|
|
273
|
+
assert.equal(ctx.rec.disposed.length, 1, 'the fork is disposed per window')
|
|
274
|
+
assert.equal(state.getSessionBinding(spec.sessionId), null, 'disposed fork binding removed')
|
|
275
|
+
assert.equal(state.getSessionBinding(sessionId).lastSleepSeq, 6)
|
|
276
|
+
assert.equal(state.getSessionBinding(sessionId).workerEpoch ?? null, null, 'fork path leaves no epoch behind')
|
|
277
|
+
})
|
|
278
|
+
|
|
279
|
+
// —— 模型路由:host/custom 不探测父会话(避免 resume 把父会话挂成活视图)——————
|
|
280
|
+
|
|
281
|
+
test('host/custom consolidation models do not resume the parent just to read a route', async () => {
|
|
282
|
+
state.updateSettings({
|
|
283
|
+
consolidationRunner: 'worker', consolidationModelMode: 'host', consolidationModel: 'test-provider/test-model',
|
|
284
|
+
consolidationReasoningEffort: 'inherit',
|
|
285
|
+
})
|
|
286
|
+
try {
|
|
287
|
+
const ctx = host({ resume: 'works', parentOptions: false })
|
|
288
|
+
const sessionId = ctx.bindSession('wl-host-route-no-resume')
|
|
289
|
+
const result = await runWorkerWindow(ctx, sessionId)
|
|
290
|
+
assert.equal(result.ok, true, result.error || '')
|
|
291
|
+
assert.equal(ctx.rec.resumed.length, 0, 'an unused inherit route must not resume (and pin) the parent session')
|
|
292
|
+
assert.deepEqual(ctx.rec.created[0]?.agentOptions, { provider: 'test-provider', model: 'test-model' })
|
|
293
|
+
} finally {
|
|
294
|
+
state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
|
|
295
|
+
}
|
|
296
|
+
})
|
|
297
|
+
|
|
298
|
+
// —— S1 冻结回归:活视图停在旧前缀时,窗口必须从持久日志取新回合 ————————————
|
|
299
|
+
test('a frozen live view is recovered from the persisted log before the window is chosen', async () => {
|
|
300
|
+
state.updateSettings({
|
|
301
|
+
consolidationRunner: 'worker', consolidationModelMode: 'host', consolidationModel: 'test-provider/test-model',
|
|
302
|
+
consolidationReasoningEffort: 'inherit',
|
|
303
|
+
})
|
|
304
|
+
try {
|
|
305
|
+
const ctx = host({})
|
|
306
|
+
const sessionId = ctx.bindSession('wl-cold-ahead')
|
|
307
|
+
const liveEvents = wrappedTurn(0) // 活视图冻结在第一回合 seq 0-6
|
|
308
|
+
const coldEvents = [...wrappedTurn(0), ...wrappedTurn(7, { user: '追加回合:这条只存在于持久日志里' })] // seq 0-13
|
|
309
|
+
const header = {
|
|
310
|
+
id: sessionId, cwd: path.join(home, 'proj'), agentPreset: 'coding',
|
|
311
|
+
createdAt: 1, isSeeded: false, delegationDepth: 0,
|
|
312
|
+
}
|
|
313
|
+
const originalGet = ctx.get.bind(ctx)
|
|
314
|
+
ctx.get = (name) => {
|
|
315
|
+
if (name === 'sessionQuery') {
|
|
316
|
+
return {
|
|
317
|
+
observeSession: async () => ({
|
|
318
|
+
source: 'live',
|
|
319
|
+
header,
|
|
320
|
+
inheritedEventCount: 0,
|
|
321
|
+
events: liveEvents,
|
|
322
|
+
cursor: 6,
|
|
323
|
+
retain: () => ({ [Symbol.dispose]: () => {} }),
|
|
324
|
+
[Symbol.dispose]: () => {},
|
|
325
|
+
}),
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (name === 'sessionPersistence') {
|
|
329
|
+
return {
|
|
330
|
+
open: async () => ({}),
|
|
331
|
+
__coldLogs: { [sessionId]: { header, inheritedEventCount: 0, events: coldEvents } },
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return originalGet(name)
|
|
335
|
+
}
|
|
336
|
+
const result = await runWorkerWindow(ctx, sessionId, { force: true })
|
|
337
|
+
assert.equal(result.ok, true, result.error || '')
|
|
338
|
+
assert.equal(result.settled, true)
|
|
339
|
+
assert.equal(result.snapshot?.throughSeq, 13, 'the window uses the persisted tail, not the frozen live cut')
|
|
340
|
+
assert.equal(state.getSessionBinding(sessionId).lastSleepSeq, 13, 'the cursor advances over the appended turn')
|
|
341
|
+
const pack = textOf(ctx.rec.forkFollowups[0])
|
|
342
|
+
assert.match(pack, /"seq":\[0,6\]/)
|
|
343
|
+
assert.match(pack, /"seq":\[7,13\]/, 'the appended turn is in the worker pack')
|
|
344
|
+
} finally {
|
|
345
|
+
state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
|
|
346
|
+
}
|
|
347
|
+
})
|
|
348
|
+
|
|
349
|
+
// —— 初生(§4.1) ——————————————————————————————————————————————————
|
|
350
|
+
|
|
351
|
+
test('worker mode births an unseeded persistent worker with an epoch and keeps it alive', async () => {
|
|
352
|
+
state.updateSettings({ consolidationRunner: 'worker', consolidationReasoningEffort: 'inherit' })
|
|
353
|
+
const ctx = host({})
|
|
354
|
+
const sessionId = ctx.bindSession('wl-birth')
|
|
355
|
+
await seedMemory(sessionId, '已有的一条记忆', '用户对伞的偏好:晴天不带。')
|
|
356
|
+
const result = await runWorkerWindow(ctx, sessionId)
|
|
357
|
+
assert.equal(result.ok, true, result.error || '')
|
|
358
|
+
assert.equal(result.settled, true)
|
|
359
|
+
assert.equal(ctx.rec.created.length, 1)
|
|
360
|
+
const spec = ctx.rec.created[0]
|
|
361
|
+
assert.match(spec.sessionId, /^memu-worker-[0-9a-f]+-1$/, 'the session id is memu-worker-<hash>-<epoch 序号>')
|
|
362
|
+
assert.equal(spec.meta.parentSession, sessionId)
|
|
363
|
+
assert.equal(spec.meta.origin, 'subagent')
|
|
364
|
+
assert.equal(spec.meta.cwd, path.join(home, 'proj'))
|
|
365
|
+
assert.equal(spec.meta.agentPreset, 'coding')
|
|
366
|
+
assert.equal(spec.meta.isSeeded, undefined, 'no-seed birth (§4.1)')
|
|
367
|
+
assert.equal(spec.seed, undefined)
|
|
368
|
+
assert.equal(spec.inheritedEventCount, undefined)
|
|
369
|
+
assert.deepEqual(spec.agentOptions, { provider: 'test-provider', model: 'test-model' })
|
|
370
|
+
// worker 不销毁、子绑定不清(改动点 6)
|
|
371
|
+
assert.equal(ctx.rec.disposed.length, 0)
|
|
372
|
+
const child = state.getSessionBinding(spec.sessionId)
|
|
373
|
+
assert.ok(child, 'the worker binding survives the window')
|
|
374
|
+
assert.equal(child.consolidationFork, true)
|
|
375
|
+
assert.equal(child.origin, 'subagent')
|
|
376
|
+
assert.equal(child.libraryId, state.getSessionBinding(sessionId).libraryId)
|
|
377
|
+
assert.equal(child.mood, null)
|
|
378
|
+
assert.equal(child.workerEpoch?.forkSessionId, spec.sessionId)
|
|
379
|
+
// 父绑定 epoch 记账:本窗已并入增量与产出
|
|
380
|
+
const parent = state.getSessionBinding(sessionId)
|
|
381
|
+
assert.equal(parent.workerEpoch?.forkSessionId, spec.sessionId)
|
|
382
|
+
assert.equal(parent.workerEpoch?.index, 1)
|
|
383
|
+
assert.equal(parent.workerEpoch?.windows, 1)
|
|
384
|
+
assert.ok((parent.workerEpoch?.chars || 0) > 0, 'increment + observed output landed in epoch.chars')
|
|
385
|
+
assert.equal(parent.workerEpoch?.timeouts, 0)
|
|
386
|
+
assert.ok(parent.workerEpoch?.lastIdleAt, 'whenIdle completion stamps lastIdleAt')
|
|
387
|
+
assert.equal(parent.workerEpoch?.scopeGeneration, state.getSessionBinding(sessionId).workerEpoch.scopeGeneration)
|
|
388
|
+
assert.equal(parent.lastSleepSeq, 6)
|
|
389
|
+
// 初生包:身份任务书 + 待处理回合 + 目录 + 契约 + 场景时间
|
|
390
|
+
const pack = textOf(ctx.rec.forkFollowups[0])
|
|
391
|
+
assert.match(pack, /私有整理 worker/, 'the identity brief leads the birth pack')
|
|
392
|
+
assert.ok(pack.includes('--- 待处理回合 ---') && pack.includes('--- 结束 ---'))
|
|
393
|
+
assert.match(pack, /memory-catalog/, 'the catalog header ships with the birth pack')
|
|
394
|
+
assert.match(pack, /"seq":\[0,6\]/, 'the pending increment carries the turn record')
|
|
395
|
+
assert.match(pack, /memu-consolidation-receipt/, 'the receipt contract ships with the birth pack')
|
|
396
|
+
})
|
|
397
|
+
|
|
398
|
+
// —— 续窗复用 + 增量包(§4.2/§15.2 改动点 4) ————————————————————————
|
|
399
|
+
|
|
400
|
+
test('a second window reuses the worker and ships only the increment pack', async () => {
|
|
401
|
+
state.updateSettings({ consolidationRunner: 'worker', consolidationReasoningEffort: 'inherit' })
|
|
402
|
+
const ctx = host({})
|
|
403
|
+
const sessionId = ctx.bindSession('wl-reuse')
|
|
404
|
+
await seedMemory(sessionId, '已有的一条记忆', '用户对伞的偏好:晴天不带。')
|
|
405
|
+
const first = await runWorkerWindow(ctx, sessionId)
|
|
406
|
+
assert.equal(first.ok, true, first.error || '')
|
|
407
|
+
const forkId = ctx.rec.created[0].sessionId
|
|
408
|
+
ctx.pushTurn(wrappedTurn(10, { user: '第二回合:把上次的结论再核对一遍', sceneTime: '第三日夜' }))
|
|
409
|
+
// sceneTime 每窗重读:窗 2 前父绑定场景时间推进(RP 剧情可能推进,§6)
|
|
410
|
+
state.setSessionBinding(sessionId, { sceneTime: '第三日夜' })
|
|
411
|
+
const second = await runWorkerWindow(ctx, sessionId)
|
|
412
|
+
assert.equal(second.ok, true, second.error || '')
|
|
413
|
+
assert.equal(ctx.rec.created.length, 1, 'no new worker for the next window')
|
|
414
|
+
assert.equal(ctx.rec.forkFollowups.length, 2)
|
|
415
|
+
assert.equal(ctx.rec.forkFollowups[1].child, forkId, 'the increment pack goes to the same worker')
|
|
416
|
+
const pack = textOf(ctx.rec.forkFollowups[1])
|
|
417
|
+
assert.ok(pack.includes('--- 待处理回合 ---') && pack.includes('--- 结束 ---'), 'separator markers frame the increment')
|
|
418
|
+
assert.match(pack, /"seq":\[10,16\]/, 'the increment covers only the new turn')
|
|
419
|
+
assert.match(pack, /待处理增量\] 1 回合 · seq 10–16/, 'the digest line describes the increment')
|
|
420
|
+
assert.match(pack, /memory-catalog/, 'the catalog header ships every window')
|
|
421
|
+
assert.match(pack, /memu-consolidation-receipt/, 'the receipt contract ships every window')
|
|
422
|
+
assert.match(pack, /\[场景时间\] 第三日夜/, 'sceneTime is re-read per window')
|
|
423
|
+
assert.ok(!pack.includes('已结算参考'), 'continuation windows never carry the settled tail (§4.2)')
|
|
424
|
+
assert.ok(!pack.includes('私有整理 worker'), 'continuation windows never repeat the identity brief')
|
|
425
|
+
assert.equal(ctx.rec.disposed.length, 0, 'the worker survives the window')
|
|
426
|
+
assert.equal(state.getSessionBinding(forkId) !== null, true)
|
|
427
|
+
const parent = state.getSessionBinding(sessionId)
|
|
428
|
+
assert.equal(parent.workerEpoch?.windows, 2)
|
|
429
|
+
assert.equal(parent.workerEpoch?.index, 1, 'the epoch keeps its index across windows')
|
|
430
|
+
assert.equal(parent.lastSleepSeq, 16)
|
|
431
|
+
})
|
|
432
|
+
|
|
433
|
+
// —— 三级试活(§4.6) ————————————————————————————————————————————————
|
|
434
|
+
|
|
435
|
+
test('resume capability revives the same epoch after a host restart', async () => {
|
|
436
|
+
state.updateSettings({ consolidationRunner: 'worker' })
|
|
437
|
+
const ctx = host({ resume: 'works' })
|
|
438
|
+
const sessionId = ctx.bindSession('wl-resume-works')
|
|
439
|
+
const first = await runWorkerWindow(ctx, sessionId)
|
|
440
|
+
assert.equal(first.ok, true, first.error || '')
|
|
441
|
+
const forkId = ctx.rec.created[0].sessionId
|
|
442
|
+
ctx.restart()
|
|
443
|
+
ctx.pushTurn(wrappedTurn(10, { user: '重启后的第一回合' }))
|
|
444
|
+
const second = await runWorkerWindow(ctx, sessionId)
|
|
445
|
+
assert.equal(second.ok, true, second.error || '')
|
|
446
|
+
assert.equal(ctx.rec.created.length, 1, 'the epoch survives the restart without a new birth')
|
|
447
|
+
assert.deepEqual(ctx.rec.resumed, [forkId])
|
|
448
|
+
assert.equal(ctx.rec.forkFollowups[1].child, forkId, 'the increment goes to the resumed agent')
|
|
449
|
+
assert.equal(state.getSessionBinding(sessionId).workerEpoch?.index, 1, 'epoch accounting is not reset by a restart')
|
|
450
|
+
})
|
|
451
|
+
|
|
452
|
+
test('without resume capability a dead worker cold-starts a new epoch', async () => {
|
|
453
|
+
state.updateSettings({ consolidationRunner: 'worker' })
|
|
454
|
+
const ctx = host({ resume: 'none' })
|
|
455
|
+
const sessionId = ctx.bindSession('wl-resume-none')
|
|
456
|
+
const first = await runWorkerWindow(ctx, sessionId)
|
|
457
|
+
assert.equal(first.ok, true, first.error || '')
|
|
458
|
+
const forkId = ctx.rec.created[0].sessionId
|
|
459
|
+
ctx.restart()
|
|
460
|
+
ctx.pushTurn(wrappedTurn(10, { user: '重启后 resume 不可用的回合' }))
|
|
461
|
+
const second = await runWorkerWindow(ctx, sessionId)
|
|
462
|
+
assert.equal(second.ok, true, second.error || '')
|
|
463
|
+
assert.equal(ctx.rec.created.length, 2, 'a gone worker falls through to birth')
|
|
464
|
+
const newSpec = ctx.rec.created[1]
|
|
465
|
+
assert.equal(newSpec.sessionId.startsWith('memu-worker-'), true)
|
|
466
|
+
assert.ok(newSpec.sessionId.endsWith('-2'), 'the epoch index increments across cold starts')
|
|
467
|
+
assert.notEqual(newSpec.sessionId, forkId)
|
|
468
|
+
assert.equal(state.getSessionBinding(forkId), null, 'the dead worker binding was cleaned up')
|
|
469
|
+
assert.equal(state.getSessionBinding(sessionId).workerEpoch?.forkSessionId, newSpec.sessionId)
|
|
470
|
+
assert.equal(state.getSessionBinding(sessionId).workerEpoch?.windows, 1, 'the new epoch starts its own accounting')
|
|
471
|
+
})
|
|
472
|
+
|
|
473
|
+
test('bench bug regression: a birth collision with a live orphan worker adopts it', async () => {
|
|
474
|
+
// bench 实录(arm B):窗口 2 派发崩溃 → retireWorker('failure') 清 epoch,但 dispose
|
|
475
|
+
// 只关句柄不删会话 → 下一窗初生用同一 forkId → 宿主拒绝 already exists(连挂 10 次)
|
|
476
|
+
// → 增量永远整理不进库。修复:撞车时探测旧会话——**存活就收编**(重建 epoch 记账指向它,
|
|
477
|
+
// 保留其累积上下文),已死才顺延换新 id。
|
|
478
|
+
state.updateSettings({ consolidationRunner: 'worker' })
|
|
479
|
+
const ctx = host({ resume: 'none' })
|
|
480
|
+
const sessionId = ctx.bindSession('wl-collision')
|
|
481
|
+
const first = await runWorkerWindow(ctx, sessionId)
|
|
482
|
+
assert.equal(first.ok, true, first.error || '')
|
|
483
|
+
const firstForkId = ctx.rec.created[0].sessionId
|
|
484
|
+
// 复刻实录:epoch 清零(retireWorker 的副作用),但宿主注册表里的旧 worker 还活着。
|
|
485
|
+
state.setSessionBinding(sessionId, { workerEpoch: null })
|
|
486
|
+
ctx.pushTurn(wrappedTurn(10, { user: '碰撞后的新回合' }))
|
|
487
|
+
const second = await runWorkerWindow(ctx, sessionId)
|
|
488
|
+
assert.equal(second.ok, true, second.error || '')
|
|
489
|
+
assert.equal(second.childId, firstForkId, 'the live orphan is adopted, not re-created')
|
|
490
|
+
assert.equal(ctx.rec.created.length, 1, 'no second create for a live orphan')
|
|
491
|
+
assert.equal(ctx.rec.forkFollowups.filter((f) => f.child === second.childId).length, 2, 'both windows dispatch to the adopted worker; actual followups=' + JSON.stringify(ctx.rec.forkFollowups.map((f) => ({ child: f.child.slice(-14), msg: textOf(f).slice(0, 60) }))))
|
|
492
|
+
const adoptedSecondPack = textOf(ctx.rec.forkFollowups.filter((f) => f.child === second.childId)[1])
|
|
493
|
+
assert.match(adoptedSecondPack, /"seq":\[10,16\]/, 'the second window pack carries the pending increment')
|
|
494
|
+
// 收编后 epoch 记账重建:同一 forkId、窗口计数续计、父绑定指回它
|
|
495
|
+
const epoch = state.getSessionBinding(sessionId).workerEpoch
|
|
496
|
+
assert.equal(epoch?.forkSessionId, firstForkId, 'the epoch points at the adopted worker')
|
|
497
|
+
assert.equal(epoch?.windows, 1, 'the adopted epoch starts its own accounting (conservative: budget restarts, context itself is the safety net)')
|
|
498
|
+
assert.equal(state.getSessionBinding(firstForkId)?.workerEpoch?.forkSessionId, firstForkId, 'the child binding is rebuilt too')
|
|
499
|
+
assert.equal(ctx.rec.disposed.filter((id) => id === firstForkId).length, 0, 'the adopted worker was never disposed')
|
|
500
|
+
})
|
|
501
|
+
|
|
502
|
+
// —— 退役条件 1(scope 变化,§4.5) ———————————————————————————————————
|
|
503
|
+
|
|
504
|
+
test('a scope change retires the worker immediately and births without a handoff', async () => {
|
|
505
|
+
state.updateSettings({ consolidationRunner: 'worker' })
|
|
506
|
+
const ctx = host({})
|
|
507
|
+
const sessionId = ctx.bindSession('wl-scope-change')
|
|
508
|
+
const first = await runWorkerWindow(ctx, sessionId)
|
|
509
|
+
assert.equal(first.ok, true, first.error || '')
|
|
510
|
+
const forkId = ctx.rec.created[0].sessionId
|
|
511
|
+
// 库/域指纹变化(scopeGenerationOf 的口径之一)
|
|
512
|
+
state.setSessionBinding(sessionId, { domainOverride: 'coding' })
|
|
513
|
+
ctx.pushTurn(wrappedTurn(10, { user: '换了领域之后的第一回合' }))
|
|
514
|
+
const second = await runWorkerWindow(ctx, sessionId)
|
|
515
|
+
assert.equal(second.ok, true, second.error || '')
|
|
516
|
+
assert.deepEqual(ctx.rec.disposed, [forkId], 'the polluted worker is retired')
|
|
517
|
+
assert.equal(ctx.rec.created.length, 2)
|
|
518
|
+
const pack = textOf(ctx.rec.forkFollowups[1])
|
|
519
|
+
assert.ok(!pack.includes('已结算参考'), 'scope-change retirement ships no settled tail (no handoff)')
|
|
520
|
+
assert.match(pack, /私有整理 worker/, 'the fresh birth pack still carries the identity brief')
|
|
521
|
+
assert.equal(state.getSessionBinding(sessionId).workerEpoch?.forkSessionId, ctx.rec.created[1].sessionId)
|
|
522
|
+
})
|
|
523
|
+
|
|
524
|
+
// —— 退役条件 2/3/4(只在 acquire 检查,§4.5) ——————————————————————————
|
|
525
|
+
|
|
526
|
+
test('char limit, window limit and idle TTL retire the epoch at acquire time', async () => {
|
|
527
|
+
const { scopeGenerationOf } = await import('../lib/consolidation-ledger.js')
|
|
528
|
+
const ctx = host({ resume: 'none' })
|
|
529
|
+
const sessionId = 'wl-retire-unit'
|
|
530
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
|
|
531
|
+
const generation = scopeGenerationOf(state.getSessionBinding(sessionId))
|
|
532
|
+
const budget = workerPool.epochBudget({ workerEpoch: { modelMaxContext: null } })
|
|
533
|
+
|
|
534
|
+
const birthed = []
|
|
535
|
+
const runAcquire = async (workerEpoch) => {
|
|
536
|
+
state.setSessionBinding(sessionId, { workerEpoch })
|
|
537
|
+
const result = await workerPool.acquireWorker(ctx, { ...state.getSessionBinding(sessionId), sessionId }, {
|
|
538
|
+
incrementChars: 100, settings: state.getSettings(), probe: { ok: true, source: 'unknown', hasWrite: null }, agentOptions: { provider: 'p', model: 'm' },
|
|
539
|
+
})
|
|
540
|
+
return result
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// 条件 2:预算合格制——已累计 + 增量×3 越过 120k 档即换新(有交接)。
|
|
544
|
+
const fit = await runAcquire({ forkSessionId: 'w0', index: 1, chars: 119_900, windows: 1, scopeGeneration: generation, parentSession: sessionId, timeouts: 0, lastIdleAt: new Date().toISOString() })
|
|
545
|
+
assert.equal(fit.ok, true, fit.error || '')
|
|
546
|
+
assert.equal(fit.birth, true, '119.9k + 100×3 crosses the 120k tier: retired and reborn')
|
|
547
|
+
assert.deepEqual(fit.retired.map((r) => r.reason), ['char-limit'])
|
|
548
|
+
assert.equal(fit.retired[0].handoff, true, 'char-limit retirement hands off')
|
|
549
|
+
birthed.push(fit.forkId)
|
|
550
|
+
|
|
551
|
+
// 条件 3:窗口数到档位上限(默认 8)。
|
|
552
|
+
const windows = await runAcquire({ forkSessionId: 'w1', index: 2, chars: 0, windows: budget.maxWindows, scopeGeneration: generation, parentSession: sessionId, timeouts: 0, lastIdleAt: new Date().toISOString() })
|
|
553
|
+
assert.equal(windows.ok, true, windows.error || '')
|
|
554
|
+
assert.equal(windows.birth, true)
|
|
555
|
+
assert.deepEqual(windows.retired.map((r) => r.reason), ['window-limit'])
|
|
556
|
+
assert.equal(windows.retired[0].handoff, true)
|
|
557
|
+
birthed.push(windows.forkId)
|
|
558
|
+
|
|
559
|
+
// 条件 4:距上一窗 whenIdle 超 TTL(30 分钟)。
|
|
560
|
+
const ttl = await runAcquire({ forkSessionId: 'w2', index: 3, chars: 0, windows: 1, scopeGeneration: generation, parentSession: sessionId, timeouts: 0, lastIdleAt: new Date(Date.now() - 31 * 60_000).toISOString() })
|
|
561
|
+
assert.equal(ttl.ok, true, ttl.error || '')
|
|
562
|
+
assert.equal(ttl.birth, true)
|
|
563
|
+
assert.deepEqual(ttl.retired.map((r) => r.reason), ['idle-ttl'])
|
|
564
|
+
assert.equal(ttl.retired[0].handoff, true)
|
|
565
|
+
birthed.push(ttl.forkId)
|
|
566
|
+
|
|
567
|
+
// 条件 1:scope 指纹变化——立即退役,无交接。
|
|
568
|
+
const scope = await runAcquire({ forkSessionId: 'w3', index: 4, chars: 0, windows: 1, scopeGeneration: 'stale-generation', parentSession: sessionId, timeouts: 0, lastIdleAt: new Date().toISOString() })
|
|
569
|
+
assert.equal(scope.ok, true, scope.error || '')
|
|
570
|
+
assert.equal(scope.birth, true)
|
|
571
|
+
assert.deepEqual(scope.retired.map((r) => r.reason), ['scope-change'])
|
|
572
|
+
assert.equal(scope.retired[0].handoff, false, 'scope-change never hands off')
|
|
573
|
+
|
|
574
|
+
// 条件全未触发:同 epoch 复用,不退役。
|
|
575
|
+
const epoch = state.getSessionBinding(sessionId).workerEpoch
|
|
576
|
+
const reuse = await runAcquire(epoch)
|
|
577
|
+
assert.equal(reuse.ok, true, reuse.error || '')
|
|
578
|
+
assert.equal(reuse.birth, false)
|
|
579
|
+
assert.equal(reuse.reused, true)
|
|
580
|
+
assert.deepEqual(reuse.retired, [])
|
|
581
|
+
// 退役动作清掉的永远是「旧」fork 的绑定;四次退役的旧 id 都不该留下绑定。
|
|
582
|
+
for (const oldId of ['w0', 'w1', 'w2', 'w3']) {
|
|
583
|
+
assert.equal(state.getSessionBinding(oldId) ?? null, null, 'retired bindings are cleaned')
|
|
584
|
+
}
|
|
585
|
+
assert.equal(state.getSessionBinding(sessionId).workerEpoch?.forkSessionId, reuse.forkId, 'the parent epoch points at the live worker')
|
|
586
|
+
})
|
|
587
|
+
|
|
588
|
+
// —— 预算分档与产出系数(§4.5 条件 2) ————————————————————————————————
|
|
589
|
+
|
|
590
|
+
test('epoch tiers follow model maxContext and explicit settings override them', () => {
|
|
591
|
+
assert.deepEqual(workerPool.epochBudget({ workerEpoch: { modelMaxContext: 100_000 } }), { charLimit: 120_000, maxWindows: 8 })
|
|
592
|
+
assert.deepEqual(workerPool.epochBudget({ workerEpoch: { modelMaxContext: 131_072 } }), { charLimit: 120_000, maxWindows: 8 })
|
|
593
|
+
assert.deepEqual(workerPool.epochBudget({ workerEpoch: { modelMaxContext: 200_000 } }), { charLimit: 200_000, maxWindows: 16 })
|
|
594
|
+
assert.deepEqual(workerPool.epochBudget({ workerEpoch: { modelMaxContext: 262_144 } }), { charLimit: 200_000, maxWindows: 16 })
|
|
595
|
+
assert.deepEqual(workerPool.epochBudget({ workerEpoch: { modelMaxContext: 1_000_000 } }), { charLimit: 200_000, maxWindows: 16 })
|
|
596
|
+
assert.deepEqual(workerPool.epochBudget({ workerEpoch: {} }), { charLimit: 120_000, maxWindows: 8 }, 'unknown model takes the conservative tier')
|
|
597
|
+
assert.deepEqual(
|
|
598
|
+
workerPool.epochBudget({ workerEpoch: { modelMaxContext: 1_000_000 } }, { workerEpochCharLimit: 50_000, workerEpochMaxWindows: 3 }),
|
|
599
|
+
{ charLimit: 50_000, maxWindows: 3 },
|
|
600
|
+
'explicit settings override the auto tier',
|
|
601
|
+
)
|
|
602
|
+
})
|
|
603
|
+
|
|
604
|
+
test('budgetFit applies the output factor to the candidate increment only', () => {
|
|
605
|
+
const epoch = { chars: 100_000, modelMaxContext: 131_072 }
|
|
606
|
+
assert.equal(workerPool.budgetFit(epoch, 6_000), true, '100k + 6k×3 = 118k fits the 120k tier')
|
|
607
|
+
assert.equal(workerPool.budgetFit(epoch, 7_000), false, '100k + 7k×3 = 121k crosses the 120k tier')
|
|
608
|
+
assert.equal(workerPool.budgetFit({ chars: 100_000, modelMaxContext: 1_000_000 }, 7_000), true, 'the 200k tier has room')
|
|
609
|
+
assert.equal(workerPool.budgetFit({ chars: 0 }, 40_000), true, '0 + 40k×3 = 120k exactly fits')
|
|
610
|
+
assert.equal(workerPool.budgetFit({ chars: 1 }, 40_000), false)
|
|
611
|
+
})
|
|
612
|
+
|
|
613
|
+
// —— epoch 记账(recordEpochProgress) ————————————————————————————————
|
|
614
|
+
|
|
615
|
+
test('recordEpochProgress accumulates chars/windows and tracks the timeout streak', () => {
|
|
616
|
+
const sessionId = 'wl-progress'
|
|
617
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
|
|
618
|
+
const forkId = 'memu-worker-progress-1'
|
|
619
|
+
const epoch = { forkSessionId: forkId, index: 1, birthAt: new Date().toISOString(), chars: 0, windows: 0, timeouts: 0, scopeGeneration: 'g', parentSession: sessionId, modelMaxContext: null, lastIdleAt: null }
|
|
620
|
+
state.setSessionBinding(sessionId, { workerEpoch: epoch })
|
|
621
|
+
state.setSessionBinding(forkId, { consolidationFork: true, workerEpoch: epoch })
|
|
622
|
+
|
|
623
|
+
let next = workerPool.recordEpochProgress({ sessionId }, { incrementChars: 300, workerOutputChars: 120, idleAt: 1_700_000_000_000 })
|
|
624
|
+
assert.equal(next.chars, 420)
|
|
625
|
+
assert.equal(next.windows, 1)
|
|
626
|
+
assert.equal(next.timeouts, 0)
|
|
627
|
+
assert.equal(next.lastIdleAt, new Date(1_700_000_000_000).toISOString())
|
|
628
|
+
|
|
629
|
+
next = workerPool.recordEpochProgress({ sessionId }, { timeout: true, progress: false })
|
|
630
|
+
assert.equal(next.timeouts, 1, 'a timeout increments the streak')
|
|
631
|
+
assert.equal(next.windows, 1, 'flag-only calls do not double-count the window')
|
|
632
|
+
|
|
633
|
+
next = workerPool.recordEpochProgress({ sessionId }, { settled: true, progress: false })
|
|
634
|
+
assert.equal(next.timeouts, 0, 'a settled window clears the streak')
|
|
635
|
+
|
|
636
|
+
// 子绑定副本同步刷新
|
|
637
|
+
assert.equal(state.getSessionBinding(forkId).workerEpoch.chars, 420)
|
|
638
|
+
assert.equal(state.getSessionBinding(sessionId).workerEpoch.chars, 420)
|
|
639
|
+
})
|
|
640
|
+
|
|
641
|
+
// —— 退役动作(retireWorker) ————————————————————————————————————————
|
|
642
|
+
|
|
643
|
+
test('retireWorker waits idle, disposes tools and the agent, and clears both bindings', async () => {
|
|
644
|
+
const ctx = host({})
|
|
645
|
+
const agents = ctx.get('agents')
|
|
646
|
+
const sessionId = 'wl-retire-action'
|
|
647
|
+
const forkId = 'memu-worker-retire-1'
|
|
648
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
|
|
649
|
+
state.setSessionBinding(forkId, {
|
|
650
|
+
consolidationFork: true,
|
|
651
|
+
origin: 'subagent',
|
|
652
|
+
parentSessionId: sessionId,
|
|
653
|
+
libraryId: state.getSessionBinding(sessionId).libraryId,
|
|
654
|
+
workerEpoch: { forkSessionId: forkId, index: 1, chars: 900, windows: 3, parentSession: sessionId },
|
|
655
|
+
})
|
|
656
|
+
state.setSessionBinding(sessionId, { workerEpoch: { forkSessionId: forkId, index: 1, chars: 900, windows: 3, parentSession: sessionId } })
|
|
657
|
+
// 注册表里放一个 handle,验证 dispose 与 bounded whenIdle
|
|
658
|
+
agents.create({ sessionId: forkId, meta: { origin: 'subagent' } })
|
|
659
|
+
const result = await workerPool.retireWorker(ctx, forkId, 'window-limit', { handoff: true, idleWaitMs: 200 })
|
|
660
|
+
assert.equal(result.ok, true)
|
|
661
|
+
assert.equal(result.handoff, true)
|
|
662
|
+
assert.deepEqual(ctx.rec.disposed, [forkId])
|
|
663
|
+
assert.equal(state.getSessionBinding(forkId), null)
|
|
664
|
+
assert.equal(state.getSessionBinding(sessionId).workerEpoch ?? null, null, 'the parent epoch is cleared')
|
|
665
|
+
// 已死的 worker:无 handle 也能完成清理(先清掉进程内注册表)
|
|
666
|
+
ctx.restart()
|
|
667
|
+
const dead = await workerPool.retireWorker(ctx, forkId, 'idle-ttl', { handoff: true, idleWaitMs: 50 })
|
|
668
|
+
assert.equal(dead.ok, true)
|
|
669
|
+
assert.equal(dead.hadHandle, false)
|
|
670
|
+
})
|
|
671
|
+
|
|
672
|
+
// —— 超时语义(§4.4):废回合不废 worker,连续 2 次退役 ———————————————————
|
|
673
|
+
|
|
674
|
+
test('a timeout abandons the turn but keeps the worker; the next pack notes the unsettled window', async () => {
|
|
675
|
+
state.updateSettings({ consolidationRunner: 'worker' })
|
|
676
|
+
const ctx = host({})
|
|
677
|
+
ctx.setDelayTurn(true) // 回合"在跑":whenIdle 挂起,模拟慢回合导致窗口超时
|
|
678
|
+
const sessionId = ctx.bindSession('wl-timeout')
|
|
679
|
+
const first = await runWorkerWindow(ctx, sessionId, { maxWaitMs: 80 })
|
|
680
|
+
assert.equal(first.ok, false)
|
|
681
|
+
assert.equal(first.timedOut, true)
|
|
682
|
+
assert.equal(first.partialWritesPossible, true, 'the range went back to pending with writes possible')
|
|
683
|
+
assert.match(first.error, /the worker is kept/)
|
|
684
|
+
const forkId = ctx.rec.created[0].sessionId
|
|
685
|
+
assert.equal(ctx.rec.disposed.length, 0, 'the worker is NOT disposed on the first timeout')
|
|
686
|
+
assert.ok(state.getSessionBinding(forkId), 'the worker binding survives')
|
|
687
|
+
const parent = state.getSessionBinding(sessionId)
|
|
688
|
+
assert.equal(parent.workerEpoch?.timeouts, 1)
|
|
689
|
+
assert.ok(parent.consolidationPending, 'the unsettled window is flagged for the next pack')
|
|
690
|
+
assert.equal(parent.workerEpoch?.lastIdleAt ?? null, null, 'a timed-out window never stamps lastIdleAt')
|
|
691
|
+
assert.equal(parent.lastSleepSeq, undefined, 'the cursor did not advance')
|
|
692
|
+
|
|
693
|
+
// 两窗之间:上一慢回合落地(真实宿主里它终会跑完)。A1 要求下一窗先等它 idle 再发包。
|
|
694
|
+
ctx.completeTurn()
|
|
695
|
+
// 第二窗:复用同一个 worker,增量包开头带「上窗未结算」核对说明;本窗回合又超时。
|
|
696
|
+
const second = await runWorkerWindow(ctx, sessionId, { maxWaitMs: 80 })
|
|
697
|
+
assert.equal(second.ok, false)
|
|
698
|
+
assert.equal(second.timedOut, true)
|
|
699
|
+
assert.equal(ctx.rec.created.length, 1, 'the first timeout did not retire the worker')
|
|
700
|
+
assert.equal(ctx.rec.forkFollowups.length, 2)
|
|
701
|
+
const pack = textOf(ctx.rec.forkFollowups[1])
|
|
702
|
+
assert.match(pack, /\[上窗未结算/, 'the unsettled note leads the next pack')
|
|
703
|
+
assert.match(pack, /勿重复写/)
|
|
704
|
+
assert.match(pack, /([0-9a-f]{12}…)/, 'the note cites the previous snapshot hash prefix')
|
|
705
|
+
// 连续第 2 次超时 → 升级退役(§4.4)
|
|
706
|
+
assert.deepEqual(ctx.rec.disposed, [forkId], 'two consecutive timeouts retire the worker')
|
|
707
|
+
assert.equal(state.getSessionBinding(forkId), null)
|
|
708
|
+
assert.equal(state.getSessionBinding(sessionId).workerEpoch ?? null, null)
|
|
709
|
+
})
|
|
710
|
+
|
|
711
|
+
// —— A1 回归:超时后必须等上一回合 idle 才发下一窗,杜绝事件污染 ————————————
|
|
712
|
+
|
|
713
|
+
test('A1: after a timeout the next window waits for the old turn to land and reuses cleanly', async () => {
|
|
714
|
+
state.updateSettings({ consolidationRunner: 'worker' })
|
|
715
|
+
const ctx = host({})
|
|
716
|
+
const sessionId = ctx.bindSession('wl-a1-clean')
|
|
717
|
+
ctx.setDelayTurn(true)
|
|
718
|
+
const first = await runWorkerWindow(ctx, sessionId, { maxWaitMs: 80 })
|
|
719
|
+
assert.equal(first.timedOut, true)
|
|
720
|
+
const forkId = ctx.rec.created[0].sessionId
|
|
721
|
+
// 上一回合在两窗之间落地;下一窗关掉延迟,正常结算。
|
|
722
|
+
ctx.completeTurn()
|
|
723
|
+
ctx.setDelayTurn(false)
|
|
724
|
+
const second = await runWorkerWindow(ctx, sessionId)
|
|
725
|
+
assert.equal(second.ok, true, second.error || '')
|
|
726
|
+
assert.equal(second.settled, true)
|
|
727
|
+
assert.equal(ctx.rec.created.length, 1, 'the idle worker is reused, not replaced')
|
|
728
|
+
assert.equal(ctx.rec.forkFollowups[1].child, forkId)
|
|
729
|
+
assert.equal(state.getSessionBinding(sessionId).lastSleepSeq, 6, 'the second window settled without contamination')
|
|
730
|
+
assert.equal(state.getSessionBinding(sessionId).consolidationPending ?? null, null, 'the pending flag cleared on settle')
|
|
731
|
+
})
|
|
732
|
+
|
|
733
|
+
test('A1: a worker still busy past the idle grace is retired and replaced, never fed a new turn', async () => {
|
|
734
|
+
state.updateSettings({ consolidationRunner: 'worker' })
|
|
735
|
+
const ctx = host({})
|
|
736
|
+
const sessionId = ctx.bindSession('wl-a1-stuck')
|
|
737
|
+
const binding = () => ({ ...state.getSessionBinding(sessionId), sessionId })
|
|
738
|
+
const opts = { probe: { hasWrite: true }, agentOptions: { provider: 'p', model: 'm' }, header: { cwd: path.join(home, 'proj'), agentPreset: 'coding' } }
|
|
739
|
+
const first = await workerPool.acquireWorker(ctx, binding(), opts)
|
|
740
|
+
assert.equal(first.ok, true, first.error || '')
|
|
741
|
+
const forkId = first.forkId
|
|
742
|
+
// 挂一个永不落地的回合,模拟卡死。
|
|
743
|
+
ctx.setDelayTurn(true)
|
|
744
|
+
first.handle.agent.followup({ content: 'stuck turn' })
|
|
745
|
+
// 有界 idle 等待超时 → 退役冷启动,绝不把新回合塞进还在忙的 worker。
|
|
746
|
+
const second = await workerPool.acquireWorker(ctx, binding(), { ...opts, idleWaitMs: 50 })
|
|
747
|
+
assert.equal(second.ok, true, second.error || '')
|
|
748
|
+
assert.equal(second.birth, true, 'the stuck worker was retired and a new one born')
|
|
749
|
+
assert.notEqual(second.forkId, forkId)
|
|
750
|
+
assert.ok(ctx.rec.disposed.includes(forkId), 'the stuck worker was disposed')
|
|
751
|
+
assert.ok(second.retired.some((r) => r.forkId === forkId && r.stuck === true), 'retirement is flagged as stuck')
|
|
752
|
+
})
|
|
753
|
+
|
|
754
|
+
// —— 退役条件 5:回合失败即退役 ————————————————————————————————————————
|
|
755
|
+
|
|
756
|
+
test('a failed worker turn retires the epoch without a handoff', async () => {
|
|
757
|
+
state.updateSettings({ consolidationRunner: 'worker' })
|
|
758
|
+
const ctx = host({ turnReason: { kind: 'error', error: { message: 'prompt variable "{{model}}" has no value', code: 'UNKNOWN' } } })
|
|
759
|
+
const sessionId = ctx.bindSession('wl-turn-failed')
|
|
760
|
+
const result = await runWorkerWindow(ctx, sessionId)
|
|
761
|
+
assert.equal(result.ok, false)
|
|
762
|
+
assert.match(result.error, /fork turn ended error/)
|
|
763
|
+
assert.deepEqual(ctx.rec.disposed.length, 1, 'the worker is retired on turn failure')
|
|
764
|
+
assert.equal(state.getSessionBinding(ctx.rec.created[0].sessionId), null)
|
|
765
|
+
assert.equal(state.getSessionBinding(sessionId).workerEpoch ?? null, null)
|
|
766
|
+
assert.equal(state.getSessionBinding(sessionId).lastSleepSeq, undefined, 'the failed range stays pending')
|
|
767
|
+
})
|
|
768
|
+
|
|
769
|
+
// —— 增量读取与缺口重建(§3.3) ————————————————————————————————————————
|
|
770
|
+
|
|
771
|
+
test('loadWorkerIncrement rebuilds gaps from host events and falls back to condense', () => {
|
|
772
|
+
const sessionId = 'wl-increment'
|
|
773
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
|
|
774
|
+
const window = { fromSeq: 0, throughSeq: 6 }
|
|
775
|
+
const events = wrappedTurn(0)
|
|
776
|
+
|
|
777
|
+
// 日志缺失 → rebuildRange 从宿主事件补全
|
|
778
|
+
const rebuilt = workerPool.loadWorkerIncrement({ sessionId, binding: {}, window, events })
|
|
779
|
+
assert.equal(rebuilt.source, 'rebuilt')
|
|
780
|
+
assert.equal(rebuilt.records.length, 1)
|
|
781
|
+
assert.deepEqual(rebuilt.records[0].seq, [0, 6])
|
|
782
|
+
assert.ok(rebuilt.chars > 0)
|
|
783
|
+
assert.match(rebuilt.digest, /1 回合 · seq 0–6 · 缺口重建/)
|
|
784
|
+
|
|
785
|
+
// 日志已衔接 → 直接读增量
|
|
786
|
+
const again = workerPool.loadWorkerIncrement({ sessionId, binding: { lastSleepSeq: 0 }, window: { fromSeq: 0, throughSeq: 6 }, events })
|
|
787
|
+
assert.equal(again.source, 'turn-log')
|
|
788
|
+
assert.deepEqual(again.records[0].seq, [0, 6])
|
|
789
|
+
|
|
790
|
+
// 记录起点越过窗口的整回合不会进增量(下窗游标推进后不重发)
|
|
791
|
+
turnLog.recordTurn(sessionId, { seq: [20, 26], at: 't', scene: null, user: '下一窗的回合', model: '' })
|
|
792
|
+
const clipped = workerPool.loadWorkerIncrement({ sessionId, binding: { lastSleepSeq: 6 }, window: { fromSeq: 10, throughSeq: 16 }, events: wrappedTurn(10) })
|
|
793
|
+
assert.deepEqual(clipped.records.map((row) => row.seq), [[10, 16]])
|
|
794
|
+
|
|
795
|
+
// 转录给不出闭合回合 → 现场 condenseEvents 回退,不写日志
|
|
796
|
+
const openEvents = [
|
|
797
|
+
{ seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '没有闭合回合的裸转录' }] } },
|
|
798
|
+
{ seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '好的' }] } } },
|
|
799
|
+
]
|
|
800
|
+
const fallback = workerPool.loadWorkerIncrement({ sessionId: 'wl-increment-fallback', binding: {}, window: { fromSeq: 0, throughSeq: 1 }, events: openEvents })
|
|
801
|
+
assert.equal(fallback.source, 'fallback')
|
|
802
|
+
assert.ok(fallback.text.includes('裸转录') || fallback.text.length >= 0, 'the fallback carries condensed text')
|
|
803
|
+
assert.equal(turnLog.readIncrement('wl-increment-fallback', -1).records.length, 0, 'the fallback never writes the log')
|
|
804
|
+
})
|
|
805
|
+
|
|
806
|
+
// —— A3/A5/A7 回归:缺口判定 / 回合对齐 / off 开关 —————————————————————————
|
|
807
|
+
|
|
808
|
+
test('A3: heartbeat/injection-only turns do not force a permanent fallback', () => {
|
|
809
|
+
const sessionId = 'wl-a3-heartbeat'
|
|
810
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
|
|
811
|
+
// 正常回合 0-6 + 心跳回合 7-9(纯 plugin 注入,无对话)+ 正常回合 10-16。
|
|
812
|
+
const heartbeat = [
|
|
813
|
+
{ seq: 7, type: 'turn/start', data: { turn: 2 } },
|
|
814
|
+
{ seq: 8, type: 'user/message', data: { source: { kind: 'plugin:heartbeat' }, content: [{ type: 'text', text: 'heartbeat' }] } },
|
|
815
|
+
{ seq: 9, type: 'turn/end', data: { turn: 2, reason: { kind: 'completed' } } },
|
|
816
|
+
]
|
|
817
|
+
const events = [...wrappedTurn(0), ...heartbeat, ...wrappedTurn(10)]
|
|
818
|
+
for (const record of turnLog.buildTurnRecords(events)) turnLog.recordTurn(sessionId, record)
|
|
819
|
+
const inc = workerPool.loadWorkerIncrement({ sessionId, binding: { lastSleepSeq: -1 }, window: { fromSeq: 0, throughSeq: 16 }, events })
|
|
820
|
+
assert.equal(inc.source, 'turn-log', 'the heartbeat gap is not a hole; no fallback')
|
|
821
|
+
assert.deepEqual(inc.records.map((r) => r.seq), [[0, 6], [10, 16]])
|
|
822
|
+
// 再跑一遍仍走 turn-log(缺口不会反复触发重建/回退)。
|
|
823
|
+
const again = workerPool.loadWorkerIncrement({ sessionId, binding: { lastSleepSeq: -1 }, window: { fromSeq: 0, throughSeq: 16 }, events })
|
|
824
|
+
assert.equal(again.source, 'turn-log')
|
|
825
|
+
})
|
|
826
|
+
|
|
827
|
+
test('A5: alignWindowToTurn trims a mid-turn window to the last closed turn', async () => {
|
|
828
|
+
// 闭合回合 0-6、7-13,随后一个开了头但未闭合的回合 14-15。
|
|
829
|
+
const events = [
|
|
830
|
+
...wrappedTurn(0), ...wrappedTurn(7),
|
|
831
|
+
{ seq: 14, type: 'turn/start', data: { turn: 3 } },
|
|
832
|
+
{ seq: 15, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '开回合' }] } },
|
|
833
|
+
]
|
|
834
|
+
const aligned = alignWindowToTurn({ events, fromSeq: 0, throughSeq: 15, remaining: 0 })
|
|
835
|
+
assert.equal(aligned.throughSeq, 13, 'the window backs off to the last turn/end')
|
|
836
|
+
assert.equal(aligned.events.length, 14, 'the open turn is pushed to the next window')
|
|
837
|
+
assert.equal(aligned.remaining, 2)
|
|
838
|
+
// 已对齐的窗口原样返回。
|
|
839
|
+
const already = alignWindowToTurn({ events: wrappedTurn(0), fromSeq: 0, throughSeq: 6, remaining: 0 })
|
|
840
|
+
assert.equal(already.throughSeq, 6)
|
|
841
|
+
})
|
|
842
|
+
|
|
843
|
+
test('A5: turn-aligned windows feed a straddling turn exactly once', () => {
|
|
844
|
+
const sessionId = 'wl-a5-straddle'
|
|
845
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
|
|
846
|
+
const events = [...wrappedTurn(0), ...wrappedTurn(7), ...wrappedTurn(14)]
|
|
847
|
+
for (const record of turnLog.buildTurnRecords(events)) turnLog.recordTurn(sessionId, record)
|
|
848
|
+
// 窗 N 对齐到回合 A 末(6):只喂 A;跨骑回合 T 整条留给下窗。
|
|
849
|
+
const winN = workerPool.loadWorkerIncrement({ sessionId, binding: { lastSleepSeq: -1 }, window: { fromSeq: 0, throughSeq: 6 }, events })
|
|
850
|
+
assert.deepEqual(winN.records.map((r) => r.seq), [[0, 6]])
|
|
851
|
+
// 窗 N+1 游标 6、对齐到 20:喂 T 和 B,T 不会因跨骑被重复整条下发。
|
|
852
|
+
const winN1 = workerPool.loadWorkerIncrement({ sessionId, binding: { lastSleepSeq: 6 }, window: { fromSeq: 7, throughSeq: 20 }, events })
|
|
853
|
+
assert.deepEqual(winN1.records.map((r) => r.seq), [[7, 13], [14, 20]])
|
|
854
|
+
})
|
|
855
|
+
|
|
856
|
+
// 边界 1:单个回合超过 500 事件时,窗口向后补到该回合的 turn/end,不再整条跨窗重发。
|
|
857
|
+
test('A5: selectWorkerWindow extends a 500-event cut to the end of a long turn', () => {
|
|
858
|
+
const events = [...wrappedTurn(0)]
|
|
859
|
+
events.push({ seq: 7, type: 'turn/start', data: { turn: 2 } })
|
|
860
|
+
events.push({ seq: 8, type: 'step/start', data: { turn: 2, step: 1 } })
|
|
861
|
+
events.push({ seq: 9, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '长回合' }] } })
|
|
862
|
+
for (let seq = 10; seq <= 554; seq += 1) {
|
|
863
|
+
events.push({ seq, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: 'x' }] } } })
|
|
864
|
+
}
|
|
865
|
+
events.push({ seq: 555, type: 'step/end', data: { turn: 2, step: 1 } })
|
|
866
|
+
events.push({ seq: 556, type: 'turn/end', data: { turn: 2, reason: { kind: 'completed' } } })
|
|
867
|
+
// 第一窗已结算 0-6;第二窗从 7 开始,500 事件切在长回合中间。
|
|
868
|
+
const fresh = events.filter((event) => event.seq > 6)
|
|
869
|
+
const window = selectWorkerWindow(fresh, 500)
|
|
870
|
+
assert.equal(window.throughSeq, 556, 'the cut extends to the long turn end')
|
|
871
|
+
assert.equal(window.events.length, 550)
|
|
872
|
+
assert.equal(window.remaining, 0)
|
|
873
|
+
const next = selectWorkerWindow(fresh.filter((event) => event.seq > 556), 500)
|
|
874
|
+
assert.equal(next.events.length, 0, 'the long turn is not re-fed by a following window')
|
|
875
|
+
})
|
|
876
|
+
|
|
877
|
+
// 边界 2:turn/end 之后只有 session 级元数据时,对齐不能把游标回退。
|
|
878
|
+
test('A5: trailing session metadata after a closed turn never regresses the cursor', () => {
|
|
879
|
+
const tail = [...wrappedTurn(0), { seq: 7, type: 'session/end-seed', data: {} }]
|
|
880
|
+
const kept = alignWindowToTurn({ events: tail, fromSeq: 0, throughSeq: 7, remaining: 0 })
|
|
881
|
+
assert.equal(kept.throughSeq, 7, 'metadata after the last turn/end stays in the window')
|
|
882
|
+
const open = [
|
|
883
|
+
...wrappedTurn(0),
|
|
884
|
+
{ seq: 7, type: 'turn/start', data: { turn: 2 } },
|
|
885
|
+
{ seq: 8, type: 'step/start', data: { turn: 2, step: 1 } },
|
|
886
|
+
]
|
|
887
|
+
const trimmed = alignWindowToTurn({ events: open, fromSeq: 0, throughSeq: 8, remaining: 0 })
|
|
888
|
+
assert.equal(trimmed.throughSeq, 6, 'a genuinely open next turn is still pushed forward')
|
|
889
|
+
})
|
|
890
|
+
|
|
891
|
+
test('A7: consolidationTurnLog=off condenses without reading or writing the log', () => {
|
|
892
|
+
state.updateSettings({ consolidationTurnLog: 'off' })
|
|
893
|
+
try {
|
|
894
|
+
const sessionId = 'wl-a7-off'
|
|
895
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
|
|
896
|
+
const events = wrappedTurn(0)
|
|
897
|
+
const inc = workerPool.loadWorkerIncrement({ sessionId, binding: {}, window: { fromSeq: 0, throughSeq: 6 }, events })
|
|
898
|
+
assert.equal(inc.source, 'fallback', 'off falls back to on-the-fly condense')
|
|
899
|
+
assert.equal(turnLog.readIncrement(sessionId, -1).records.length, 0, 'off never writes the log')
|
|
900
|
+
} finally {
|
|
901
|
+
state.updateSettings({ consolidationTurnLog: 'on' })
|
|
902
|
+
}
|
|
903
|
+
})
|
|
904
|
+
|
|
905
|
+
test('A2: the epoch abort is wired at birth and stays stable across reuse', async () => {
|
|
906
|
+
state.updateSettings({ consolidationRunner: 'worker' })
|
|
907
|
+
const ctx = host({})
|
|
908
|
+
const sessionId = ctx.bindSession('wl-a2-abort')
|
|
909
|
+
const binding = () => ({ ...state.getSessionBinding(sessionId), sessionId })
|
|
910
|
+
const opts = { probe: { hasWrite: true }, agentOptions: { provider: 'p', model: 'm' }, header: { cwd: path.join(home, 'proj'), agentPreset: 'coding' } }
|
|
911
|
+
const first = await workerPool.acquireWorker(ctx, binding(), opts)
|
|
912
|
+
assert.equal(first.ok, true, first.error || '')
|
|
913
|
+
assert.ok(first.epochAbort && typeof first.epochAbort.abort === 'function', 'birth exposes an epoch abort controller')
|
|
914
|
+
assert.equal(ctx.rec.created[0].signal, first.epochAbort.signal, 'create is wired to the epoch abort, not a window signal')
|
|
915
|
+
const second = await workerPool.acquireWorker(ctx, binding(), opts)
|
|
916
|
+
assert.equal(second.reused, true)
|
|
917
|
+
assert.equal(second.epochAbort, first.epochAbort, 'reuse keeps the same lifetime-bound abort: hard-stop can stop the persistent worker')
|
|
918
|
+
})
|
|
919
|
+
|
|
920
|
+
// —— 增量包组装(§4.2) ————————————————————————————————————————————————
|
|
921
|
+
|
|
922
|
+
test('buildIncrementPack assembles separators, catalog, capped carry, contract and sceneTime', () => {
|
|
923
|
+
const catalog = {
|
|
924
|
+
type: 'user/message',
|
|
925
|
+
data: { content: [{ type: 'text', text: ['[memory-catalog · 已有记忆目录]', '- [m1] 第一条', '- [m2] 第二条'].join('\n') }] },
|
|
926
|
+
}
|
|
927
|
+
const records = [
|
|
928
|
+
{ seq: [0, 6], at: 't', scene: null, user: '一', model: '甲' },
|
|
929
|
+
{ seq: [10, 16], at: 't', scene: '第三日夜', user: '二', model: '乙' },
|
|
930
|
+
]
|
|
931
|
+
const carry = Array.from({ length: 6 }, (_, i) => ({ fromSeq: i, throughSeq: i + 1, tag: '事实', text: '顺延候选' + i, observedAt: null, carried: true }))
|
|
932
|
+
carry.push({ fromSeq: 0, throughSeq: 6, tag: '事实', text: '本窗新候选', observedAt: null })
|
|
933
|
+
const pack = workerPool.buildIncrementPack({
|
|
934
|
+
binding: { sessionId: 's' },
|
|
935
|
+
incrementRecords: records,
|
|
936
|
+
catalog,
|
|
937
|
+
digest: '2 回合 · seq 0–16',
|
|
938
|
+
carry,
|
|
939
|
+
contract: '[完成说明 · 1.3.1] 成功时最后一条消息用一句话说明整理结果即可',
|
|
940
|
+
sceneTime: '第三日夜',
|
|
941
|
+
pendingNote: true,
|
|
942
|
+
pendingHash: 'a'.repeat(64),
|
|
943
|
+
})
|
|
944
|
+
assert.ok(pack.includes('--- 待处理回合 ---') && pack.includes('--- 结束 ---'), 'explicit separators frame the increment')
|
|
945
|
+
assert.match(pack, /\[上窗未结算(aaaaaaaaaaaa…)\]/, 'the pending note cites the hash prefix')
|
|
946
|
+
assert.match(pack, /勿重复写/)
|
|
947
|
+
assert.match(pack, /\[待处理增量\] 2 回合 · seq 0–16/)
|
|
948
|
+
assert.match(pack, /"seq":\[0,6\]/, 'the records ride inside the separators as JSONL')
|
|
949
|
+
assert.match(pack, /memory-catalog/, 'the catalog header ships every window')
|
|
950
|
+
assert.match(pack, /\[必写候选/, 'carry candidates ship with the pack')
|
|
951
|
+
const carriedRows = (pack.match(/^\d+\. \[顺延/gm) || [])
|
|
952
|
+
assert.equal(carriedRows.length, 4, 'at most 4 carried candidates (carry ≤4)')
|
|
953
|
+
assert.match(pack, /本窗新候选/, 'fresh candidates keep their slot')
|
|
954
|
+
assert.match(pack, /完成说明/, 'the receipt contract ships')
|
|
955
|
+
assert.match(pack, /\[场景时间\] 第三日夜/, 'sceneTime ships as one line')
|
|
956
|
+
// 没有上一窗未结算时不带核对说明
|
|
957
|
+
const clean = workerPool.buildIncrementPack({ binding: { sessionId: 's' }, incrementRecords: records, catalog, carry: [], contract: 'c', sceneTime: null })
|
|
958
|
+
assert.ok(!clean.includes('上窗未结算'))
|
|
959
|
+
assert.ok(!clean.includes('[场景时间]'), 'a missing sceneTime emits no line')
|
|
960
|
+
})
|
|
961
|
+
|
|
962
|
+
// —— 交接包(§5.1):尾部标注、摘要去重与封顶 ————————————————————————————
|
|
963
|
+
|
|
964
|
+
test('buildHandoffPack carries the settled tail, a deduped 20-row written summary and the pending increment', () => {
|
|
965
|
+
const sessionId = 'wl-handoff'
|
|
966
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
|
|
967
|
+
// 已结算两条 + 未结算一条:尾部只能带已结算段
|
|
968
|
+
turnLog.recordTurn(sessionId, { seq: [0, 9], at: 't', scene: null, user: '已结算一', model: '甲' })
|
|
969
|
+
turnLog.recordTurn(sessionId, { seq: [10, 19], at: 't', scene: null, user: '已结算二', model: '乙' })
|
|
970
|
+
turnLog.recordTurn(sessionId, { seq: [30, 39], at: 't', scene: null, user: '未结算段', model: '丙' })
|
|
971
|
+
|
|
972
|
+
// 最近优先:mem-24 最新(账本按 at 倒序;覆盖入参顺序即调用方给的 recency 顺序)
|
|
973
|
+
const writtenIds = Array.from({ length: 25 }, (_, i) => `mem-${String(24 - i).padStart(2, '0')}`)
|
|
974
|
+
// 目录头带 m1:written 里的 mem-00 与目录无关,但第一条写在目录里的 id 应被去重
|
|
975
|
+
const catalog = {
|
|
976
|
+
type: 'user/message',
|
|
977
|
+
data: { content: [{ type: 'text', text: ['[memory-catalog · 已有记忆目录]', '- [mem-00] 目录里已有的一条', '- [mem-other] 另一条'].join('\n') }] },
|
|
978
|
+
}
|
|
979
|
+
const pack = workerPool.buildHandoffPack({
|
|
980
|
+
sessionId,
|
|
981
|
+
binding: { sessionId, libraryId: null, lastSleepSeq: 19 },
|
|
982
|
+
snapshot: { fromSeq: 20, throughSeq: 39, eventCount: 10, hash: 'h'.repeat(64) },
|
|
983
|
+
jobId: 'cons-test',
|
|
984
|
+
mustCover: [],
|
|
985
|
+
contract: '[完成说明 · 1.3.1]',
|
|
986
|
+
incrementRecords: [{ seq: [30, 39], at: 't', scene: null, user: '未结算段', model: '丙' }],
|
|
987
|
+
digest: '1 回合 · seq 30–39',
|
|
988
|
+
catalog,
|
|
989
|
+
sceneTime: '第三日夜',
|
|
990
|
+
writtenRows: writtenIds.map((id) => ({ id, title: '标题 ' + id })),
|
|
991
|
+
lastSleepSeq: 19,
|
|
992
|
+
})
|
|
993
|
+
assert.ok(pack.includes('--- 待处理回合 ---'), 'the pending increment rides in the pack')
|
|
994
|
+
assert.match(pack, /"seq":\[30,39\]/)
|
|
995
|
+
assert.ok(pack.includes('--- 已结算参考(勿为其写新记忆,只处理待处理区间)---'), 'the settled tail is labelled')
|
|
996
|
+
assert.ok(pack.includes('--- 已结算参考结束 ---'))
|
|
997
|
+
assert.match(pack, /"seq":\[0,9\]/, 'settled turn one rides the tail')
|
|
998
|
+
assert.match(pack, /"seq":\[10,19\]/, 'settled turn two rides the tail')
|
|
999
|
+
assert.ok(!pack.includes('"seq":[30,39]\n--- 已结算参考'), 'the unsettled record is tail-excluded')
|
|
1000
|
+
const tailBody = pack.split('--- 已结算参考(勿为其写新记忆,只处理待处理区间)---')[1] || ''
|
|
1001
|
+
assert.ok(!tailBody.includes('未结算段') || !tailBody.includes('"seq":[30,39]'), 'the tail never carries the pending range')
|
|
1002
|
+
assert.match(pack, /已写入摘要/, 'the written summary ships with the birth pack')
|
|
1003
|
+
const summarySection = (pack.split('[已写入摘要')[1] || '').split('\n[')[0]
|
|
1004
|
+
const summaryIds = (summarySection.match(/- \[(mem-\d+)\]/g) || []).map((row) => row.replace(/- \[|\]/g, ''))
|
|
1005
|
+
assert.equal(summaryIds.length, 20, 'the summary is capped at 20 rows')
|
|
1006
|
+
assert.equal(summaryIds[0], 'mem-24', 'the most recent operation leads')
|
|
1007
|
+
assert.ok(!summaryIds.includes('mem-00'), 'ids already listed in the catalog are deduped away')
|
|
1008
|
+
assert.match(pack, /另有 4 条均已在库。/, 'the remainder is counted (25 written − 20 shown − 1 catalog-deduped)')
|
|
1009
|
+
assert.match(pack, /\[场景时间\] 第三日夜/)
|
|
1010
|
+
|
|
1011
|
+
// 无交接退役(scope-change/failure):不带尾部与摘要,身份与目录照发
|
|
1012
|
+
const bare = workerPool.buildHandoffPack({
|
|
1013
|
+
sessionId,
|
|
1014
|
+
binding: { sessionId, libraryId: null },
|
|
1015
|
+
snapshot: { fromSeq: 0, throughSeq: 9, eventCount: 10, hash: 'h'.repeat(64) },
|
|
1016
|
+
contract: 'c',
|
|
1017
|
+
incrementRecords: [{ seq: [0, 9], at: 't', scene: null, user: 'x', model: '' }],
|
|
1018
|
+
catalog,
|
|
1019
|
+
includeTail: false,
|
|
1020
|
+
writtenRows: [],
|
|
1021
|
+
})
|
|
1022
|
+
assert.ok(!bare.includes('已结算参考'))
|
|
1023
|
+
assert.ok(!bare.includes('已写入摘要'))
|
|
1024
|
+
assert.match(bare, /memory-catalog/)
|
|
1025
|
+
})
|
|
1026
|
+
|
|
1027
|
+
test('A8: the ledger-backed written summary includes created, updated and held ids', async () => {
|
|
1028
|
+
const { recordOperation } = await import('../lib/consolidation-ledger.js')
|
|
1029
|
+
const sessionId = 'wl-a8-summary'
|
|
1030
|
+
state.ensureSession(sessionId, { cwd: path.join(home, 'proj'), agentPreset: 'coding' })
|
|
1031
|
+
// private.js 结算时把 created+updated+held 全部记进 operation.ids(A8);摘要走账本读取路径。
|
|
1032
|
+
recordOperation({ sessionId, key: 'op-a8', outcome: 'completed', ids: ['m-created', 'm-updated', 'm-held'] })
|
|
1033
|
+
const pack = workerPool.buildHandoffPack({
|
|
1034
|
+
sessionId,
|
|
1035
|
+
binding: { sessionId, libraryId: null, lastSleepSeq: 9 },
|
|
1036
|
+
snapshot: { fromSeq: 0, throughSeq: 9, eventCount: 10, hash: 'h'.repeat(64) },
|
|
1037
|
+
contract: 'c',
|
|
1038
|
+
incrementRecords: [],
|
|
1039
|
+
catalog: null,
|
|
1040
|
+
lastSleepSeq: 9,
|
|
1041
|
+
})
|
|
1042
|
+
assert.match(pack, /已写入摘要/)
|
|
1043
|
+
assert.match(pack, /\[m-created\]/)
|
|
1044
|
+
assert.match(pack, /\[m-updated\]/, 'updated ids are not dropped from the summary')
|
|
1045
|
+
assert.match(pack, /\[m-held\]/, 'held ids are not dropped from the summary')
|
|
1046
|
+
})
|