dsh-memu-memory 1.3.6 → 1.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/AGENTS.md +2 -1
  2. package/CHANGELOG.md +87 -0
  3. package/README.md +7 -7
  4. package/README.zh.md +7 -7
  5. package/docs/client-conventions.md +4 -0
  6. package/docs/contributing.md +2 -2
  7. package/docs/memory-semantics.md +10 -7
  8. package/docs/troubleshooting.md +132 -7
  9. package/lib/binding-diagnostics.js +2 -2
  10. package/lib/client.js +296 -122
  11. package/lib/consolidation-ledger.js +6 -2
  12. package/lib/consolidation-worker.js +7 -0
  13. package/lib/inbound.js +24 -9
  14. package/lib/inject.js +379 -215
  15. package/lib/lexicon.js +5 -0
  16. package/lib/local-embedding-manager.js +4 -0
  17. package/lib/local-vector-service.js +65 -1
  18. package/lib/memory.js +711 -175
  19. package/lib/paths.js +24 -0
  20. package/lib/private.js +284 -127
  21. package/lib/rpc.js +144 -45
  22. package/lib/snippet.js +49 -28
  23. package/lib/state.js +185 -26
  24. package/lib/tools.js +150 -31
  25. package/lib/webui/standalone.css +28 -1
  26. package/lib/webui.js +25 -1
  27. package/lib/worker-pool.js +260 -26
  28. package/package.json +1 -1
  29. package/scripts/check-i18n.mjs +19 -0
  30. package/scripts/recall-bench.mjs +4 -4
  31. package/scripts/simulate-injection.mjs +3 -0
  32. package/tests/activity-wiring.test.mjs +52 -0
  33. package/tests/client-render.test.mjs +207 -0
  34. package/tests/consolidation-feed.test.mjs +26 -0
  35. package/tests/consolidation-fork.test.mjs +618 -33
  36. package/tests/consolidation-snapshot.test.mjs +2 -1
  37. package/tests/cross-library-recall.test.mjs +156 -0
  38. package/tests/cue.test.mjs +15 -2
  39. package/tests/hybrid-recall.test.mjs +488 -0
  40. package/tests/inbound.test.mjs +49 -4
  41. package/tests/inject-conflict.test.mjs +70 -9
  42. package/tests/inject-guide.test.mjs +13 -1
  43. package/tests/inject.test.mjs +10 -0
  44. package/tests/injection-budget.test.mjs +101 -0
  45. package/tests/injection-chain.test.mjs +37 -0
  46. package/tests/injection-rollback.test.mjs +172 -9
  47. package/tests/issue2-chain.test.mjs +169 -0
  48. package/tests/lexicon-inject.test.mjs +33 -5
  49. package/tests/lexicon-ui.test.mjs +99 -2
  50. package/tests/managed-memory.test.mjs +625 -1
  51. package/tests/media.test.mjs +1 -1
  52. package/tests/new-session-gate.test.mjs +280 -25
  53. package/tests/open-loop-date.test.mjs +11 -1
  54. package/tests/recall-intent.test.mjs +52 -3
  55. package/tests/simulate-injection.test.mjs +4 -4
  56. package/tests/snippet.test.mjs +33 -1
  57. package/tests/state.test.mjs +8 -3
  58. package/tests/tool-schema.test.mjs +52 -0
  59. package/tests/tools.test.mjs +394 -0
  60. package/tests/webui.test.mjs +16 -2
  61. package/tests/worker-lifecycle.test.mjs +419 -36
@@ -5,6 +5,8 @@ import os from 'node:os'
5
5
  import path from 'node:path'
6
6
 
7
7
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-worker-lifecycle-'))
8
+ process.env.DSH_HOME = home
9
+ fs.mkdirSync(path.join(home, 'proj'))
8
10
  process.env.DSH_MEMU_HOME = home
9
11
  process.env.DSH_MEMU_MEMORY_HOME = home
10
12
 
@@ -100,40 +102,52 @@ function host({
100
102
  delayTurn = false,
101
103
  headerTools = null,
102
104
  parentOptions = true,
105
+ cwd = path.join(home, 'proj'),
106
+ childCtxFactory = null,
107
+ childEvents = [],
108
+ usage = null,
109
+ wrapupThrows = false,
103
110
  } = {}) {
104
111
  const rec = {
105
112
  liveFollowups: [], created: [], forkFollowups: [], disposed: [], resumed: [],
106
- sessionHandlers: [],
113
+ sessionHandlers: [], childEvents: [],
107
114
  }
115
+ const headers = new Map()
108
116
  const registry = new Map() // 进程内 agent 注册表:agents.get 只查这里
109
117
  // delayTurnMode=true 时 followup 不立即发回合事件,而是把回合挂起(whenIdle 等待),
110
118
  // 直到 ctx.completeTurn() 才落地——真实模拟"超时后上一回合还在跑"的时序(A1)。
111
119
  let delayTurnMode = delayTurn
112
- let childSeq = 0
120
+ let childSeq = 900
121
+ let childTurn = 0
122
+ const emit = (session, event) => {
123
+ event = { ...event, seq: event.seq ?? ++childSeq }
124
+ rec.childEvents.push({ session, event })
125
+ for (const handler of [...rec.sessionHandlers]) handler(session, event)
126
+ }
113
127
  const transcript = [...wrappedTurn(0)]
114
128
 
115
- const makeRecord = (id) => {
116
- const childSession = { id } // 宿主语义:handle.agent.session 与 session/event 的 session 是同一个对象
129
+ const makeRecord = (id, agentOptions = null) => {
130
+ const childSession = { id, header: headers.get(id) || { cwd } } // stable host session identity
117
131
  let pending = null // 在跑回合:{ promise, finish }
118
132
  const emitTurn = () => {
119
- childSeq += 1
133
+ childTurn += 1
120
134
  const child = state.getSessionBinding(id)
121
135
  const fromSeq = Number.isSafeInteger(child?.snapshotFromSeq) ? child.snapshotFromSeq : 0
122
136
  const throughSeq = Number.isSafeInteger(child?.snapshotThroughSeq) ? child.snapshotThroughSeq : 6
123
137
  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
- }
138
+ for (const event of typeof childEvents === 'function' ? childEvents({ child, childSession }) : childEvents) emit(childSession, event)
139
+ if (text) emit(childSession, { type: 'assistant/message', data: { message: { content: [{ type: 'text', text }] }, ...(usage ? { usage } : {}) } })
140
+ emit(childSession, { type: 'turn/end', data: { turn: childTurn, reason: turnReason } })
130
141
  }
131
142
  return {
132
143
  agent: {
144
+ ...(agentOptions ? { options: structuredClone(agentOptions) } : {}),
133
145
  session: childSession,
146
+ ctx: childCtxFactory?.(),
134
147
  followup: (message) => {
148
+ if (wrapupThrows && message?.source?.summary === '整理收尾提示') throw new Error('wrapup queue rejected')
135
149
  rec.forkFollowups.push({ child: id, message })
136
- if (!emitTurnEnd) return
150
+ if (message?.source?.summary === '整理收尾提示' || !emitTurnEnd) return
137
151
  if (delayTurnMode) {
138
152
  let resolve
139
153
  const promise = new Promise((r) => { resolve = r })
@@ -161,7 +175,7 @@ function host({
161
175
  : null
162
176
 
163
177
  const ctx = {
164
- rec,
178
+ rec, emit,
165
179
  restart: () => registry.clear(),
166
180
  on: (name, handler) => {
167
181
  if (name !== 'session/event') return () => {}
@@ -189,7 +203,8 @@ function host({
189
203
  throw new Error('session "' + spec.sessionId + '" already exists')
190
204
  }
191
205
  rec.created.push(spec)
192
- const record = makeRecord(spec.sessionId)
206
+ headers.set(spec.sessionId, { cwd: spec.meta?.cwd || cwd })
207
+ const record = makeRecord(spec.sessionId, spec.agentOptions)
193
208
  registry.set(spec.sessionId, record)
194
209
  return record
195
210
  },
@@ -211,7 +226,9 @@ function host({
211
226
  }
212
227
  if (name === 'sessionQuery') {
213
228
  return {
214
- readSession: async () => ({ events: [...transcript], session: { cwd: path.join(home, 'proj'), agentPreset: 'coding' } }),
229
+ readSession: async (id) => headers.has(id)
230
+ ? { events: rec.childEvents.filter(row => row.session.id === id).map(row => row.event), session: headers.get(id) }
231
+ : { events: [...transcript], session: { cwd, agentPreset: 'coding' } },
215
232
  }
216
233
  }
217
234
  return undefined
@@ -393,6 +410,16 @@ test('worker mode births an unseeded persistent worker with an epoch and keeps i
393
410
  assert.match(pack, /memory-catalog/, 'the catalog header ships with the birth pack')
394
411
  assert.match(pack, /"seq":\[0,6\]/, 'the pending increment carries the turn record')
395
412
  assert.match(pack, /memu-consolidation-receipt/, 'the receipt contract ships with the birth pack')
413
+ const { estTokens } = await import('../lib/budget.js')
414
+ assert.equal(result.measurement.packet.inputChars, pack.length)
415
+ assert.equal(result.measurement.packet.estimatedTokens, estTokens(pack))
416
+ assert.equal(result.measurement.schemaVersion, 2)
417
+ assert.equal(result.measurement.runner, 'worker')
418
+ assert.equal(parent.workerEpoch.measurementVersion, 2)
419
+ assert.equal(parent.workerEpoch.chars, pack.length + result.measurement.observed.outputTextChars)
420
+ assert.equal(parent.workerEpoch.estimatedTokens, estTokens(pack) + result.measurement.observed.estimatedTokens)
421
+ assert.equal(result.measurement.usage.inputTokens, null)
422
+ assert.equal(result.measurement.observed.reasoningChars, null)
396
423
  })
397
424
 
398
425
  // —— 续窗复用 + 增量包(§4.2/§15.2 改动点 4) ————————————————————————
@@ -470,33 +497,23 @@ test('without resume capability a dead worker cold-starts a new epoch', async ()
470
497
  assert.equal(state.getSessionBinding(sessionId).workerEpoch?.windows, 1, 'the new epoch starts its own accounting')
471
498
  })
472
499
 
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。
500
+ test('a birth collision retires an unmeasured live orphan instead of resetting its context to zero', async () => {
478
501
  state.updateSettings({ consolidationRunner: 'worker' })
479
502
  const ctx = host({ resume: 'none' })
480
503
  const sessionId = ctx.bindSession('wl-collision')
481
504
  const first = await runWorkerWindow(ctx, sessionId)
482
505
  assert.equal(first.ok, true, first.error || '')
483
- const firstForkId = ctx.rec.created[0].sessionId
484
- // 复刻实录:epoch 清零(retireWorker 的副作用),但宿主注册表里的旧 worker 还活着。
485
506
  state.setSessionBinding(sessionId, { workerEpoch: null })
486
507
  ctx.pushTurn(wrappedTurn(10, { user: '碰撞后的新回合' }))
487
508
  const second = await runWorkerWindow(ctx, sessionId)
488
509
  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')
510
+ assert.notEqual(second.childId, first.childId)
511
+ assert.equal(ctx.rec.created.length, 2)
512
+ assert.deepEqual(ctx.rec.disposed, [first.childId])
513
+ assert.equal(state.getSessionBinding(first.childId), null)
514
+ assert.equal(ctx.rec.forkFollowups.filter(row => row.child === first.childId).length, 1)
515
+ assert.match(textOf(ctx.rec.forkFollowups[1]), /"seq":\[10,16\]/)
516
+ assert.equal(state.getSessionBinding(sessionId).workerEpoch.measurementVersion, 2)
500
517
  })
501
518
 
502
519
  // —— 退役条件 1(scope 变化,§4.5) ———————————————————————————————————
@@ -508,8 +525,9 @@ test('a scope change retires the worker immediately and births without a handoff
508
525
  const first = await runWorkerWindow(ctx, sessionId)
509
526
  assert.equal(first.ok, true, first.error || '')
510
527
  const forkId = ctx.rec.created[0].sessionId
511
- // 库/域指纹变化(scopeGenerationOf 的口径之一)
512
- state.setSessionBinding(sessionId, { domainOverride: 'coding' })
528
+ // 库/域指纹变化(scopeGenerationOf 的口径之一)。该工作区名不含 RP 标记,
529
+ // issue #2 后未询问会话的兜底领域就是 coding——写 rp 才是真正的领域变化。
530
+ state.setSessionBinding(sessionId, { domainOverride: 'rp' })
513
531
  ctx.pushTurn(wrappedTurn(10, { user: '换了领域之后的第一回合' }))
514
532
  const second = await runWorkerWindow(ctx, sessionId)
515
533
  assert.equal(second.ok, true, second.error || '')
@@ -533,7 +551,7 @@ test('char limit, window limit and idle TTL retire the epoch at acquire time', a
533
551
 
534
552
  const birthed = []
535
553
  const runAcquire = async (workerEpoch) => {
536
- state.setSessionBinding(sessionId, { workerEpoch })
554
+ state.setSessionBinding(sessionId, { workerEpoch: { measurementVersion: 2, ...workerEpoch } })
537
555
  const result = await workerPool.acquireWorker(ctx, { ...state.getSessionBinding(sessionId), sessionId }, {
538
556
  incrementChars: 100, settings: state.getSettings(), probe: { ok: true, source: 'unknown', hasWrite: null }, agentOptions: { provider: 'p', model: 'm' },
539
557
  })
@@ -764,6 +782,10 @@ test('a failed worker turn retires the epoch without a handoff', async () => {
764
782
  assert.equal(state.getSessionBinding(ctx.rec.created[0].sessionId), null)
765
783
  assert.equal(state.getSessionBinding(sessionId).workerEpoch ?? null, null)
766
784
  assert.equal(state.getSessionBinding(sessionId).lastSleepSeq, undefined, 'the failed range stays pending')
785
+ const { sessionState } = await import('../lib/consolidation-ledger.js')
786
+ assert.equal(sessionState(sessionId).checked, null)
787
+ assert.equal(sessionState(sessionId).pending.throughSeq, 6)
788
+ assert.ok(result.measurement.packet.inputChars > 0)
767
789
  })
768
790
 
769
791
  // —— 增量读取与缺口重建(§3.3) ————————————————————————————————————————
@@ -1044,3 +1066,364 @@ test('A8: the ledger-backed written summary includes created, updated and held i
1044
1066
  assert.match(pack, /\[m-updated\]/, 'updated ids are not dropped from the summary')
1045
1067
  assert.match(pack, /\[m-held\]/, 'held ids are not dropped from the summary')
1046
1068
  })
1069
+
1070
+ // W1/W2: isolated fixtures only, no real host/worker services.
1071
+ test('cwd resolution checks directories and catches stat failures', (t) => {
1072
+ assert.equal(workerPool.resolveConsolidationCwd(path.join(home, 'proj'), home), path.join(home, 'proj'))
1073
+ assert.equal(workerPool.resolveConsolidationCwd(import.meta.filename, home), home)
1074
+ t.mock.method(fs, 'statSync', () => { throw new Error('unreadable') })
1075
+ assert.equal(workerPool.resolveConsolidationCwd('inaccessible', home), home)
1076
+ })
1077
+
1078
+ for (const runner of ['fork', 'worker']) {
1079
+ for (const kind of ['missing', 'file']) {
1080
+ test(`${runner} falls back for a ${kind} cwd without changing permissions or the path`, async (t) => {
1081
+ state.updateSettings({ consolidationRunner: runner, consolidationReasoningEffort: 'inherit' })
1082
+ const cwd = kind === 'file' ? import.meta.filename : path.join(home, 'does-not-exist')
1083
+ const ctx = host({ cwd })
1084
+ ctx.permissionPresets = { set: t.mock.fn() }
1085
+ const id = ctx.bindSession(`wl-cwd-${runner}-${kind}`)
1086
+ const result = await runWorkerWindow(ctx, id, { force: true })
1087
+ assert.equal(result.ok, true, result.error || '')
1088
+ assert.equal(result.settled, true)
1089
+ assert.equal(ctx.rec.created[0].meta.cwd, home)
1090
+ assert.equal(ctx.permissionPresets.set.mock.callCount(), 0)
1091
+ assert.equal(kind === 'missing' ? fs.existsSync(cwd) : fs.statSync(cwd).isDirectory(), false)
1092
+ if (runner === 'worker') await workerPool.retireWorker(ctx, result.childId, 'test-finished')
1093
+ })
1094
+ }
1095
+ }
1096
+
1097
+ test('resume with an immutable dead cwd retires and creates with the fallback', async () => {
1098
+ state.updateSettings({ consolidationRunner: 'worker' })
1099
+ const cwd = fs.mkdtempSync(path.join(home, 'resume-cwd-'))
1100
+ const ctx = host({ resume: 'works', cwd })
1101
+ const id = ctx.bindSession('wl-resume-dead-cwd')
1102
+ const first = await runWorkerWindow(ctx, id)
1103
+ assert.equal(first.ok, true, first.error || '')
1104
+ ctx.restart()
1105
+ fs.rmdirSync(cwd)
1106
+ ctx.pushTurn(wrappedTurn(10))
1107
+ const second = await runWorkerWindow(ctx, id)
1108
+ assert.equal(second.ok, true, second.error || '')
1109
+ assert.deepEqual(ctx.rec.resumed, [first.childId])
1110
+ assert.deepEqual(ctx.rec.disposed, [first.childId])
1111
+ assert.notEqual(second.childId, first.childId)
1112
+ assert.equal(ctx.rec.created[1].meta.cwd, home)
1113
+ assert.equal(fs.existsSync(cwd), false)
1114
+ })
1115
+
1116
+ test('resume restores the PTC mount and restriction before dispatch', async () => {
1117
+ state.updateSettings({ consolidationRunner: 'worker' })
1118
+ const registered = []
1119
+ const restricted = []
1120
+ const ctx = host({ resume: 'works', headerTools: ['run_code'], childCtxFactory: () => ({ tools: {
1121
+ register: tool => { registered.push(tool.name); return () => {} },
1122
+ restrict: spec => { restricted.push({ spec, followups: ctx.rec.forkFollowups.length }); return () => {} },
1123
+ } }) })
1124
+ const id = ctx.bindSession('wl-resume-tool-mount')
1125
+ const first = await runWorkerWindow(ctx, id)
1126
+ assert.equal(first.ok, true, first.error || '')
1127
+ const firstCount = registered.length
1128
+ assert.ok(firstCount > 0)
1129
+ ctx.restart()
1130
+ ctx.pushTurn(wrappedTurn(10))
1131
+ const second = await runWorkerWindow(ctx, id)
1132
+ assert.equal(second.ok, true, second.error || '')
1133
+ assert.deepEqual(registered.slice(firstCount), registered.slice(0, firstCount))
1134
+ assert.equal(restricted.length, 2)
1135
+ assert.equal(restricted[1].followups, 1)
1136
+ assert.equal(second.childId, first.childId)
1137
+ })
1138
+
1139
+ test('replayed and late old-window events cannot complete or charge the next window', async () => {
1140
+ state.updateSettings({ consolidationRunner: 'worker' })
1141
+ let old = []
1142
+ const ctx = host({ childEvents: () => old })
1143
+ const id = ctx.bindSession('wl-late-event')
1144
+ const first = await runWorkerWindow(ctx, id)
1145
+ assert.equal(first.ok, true, first.error || '')
1146
+ old = ctx.rec.childEvents.map(row => structuredClone(row.event))
1147
+ old.push({ type: 'turn/end', seq: old[1].seq, data: { reason: { kind: 'error', error: { message: 'late old failure' } } } })
1148
+ ctx.pushTurn(wrappedTurn(10))
1149
+ const second = await runWorkerWindow(ctx, id)
1150
+ assert.equal(second.ok, true, second.error || '')
1151
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, 16)
1152
+ const newText = ctx.rec.childEvents.filter(row => row.event.seq > old[1].seq && row.event.type === 'assistant/message')[0].event.data.message.content[0].text
1153
+ assert.equal(second.measurement.observed.outputTextChars, newText.length)
1154
+ })
1155
+
1156
+ test('measurement counts JSON arguments/PTC top-level results once and aggregates verified cache usage', () => {
1157
+ const args = { text: '中文参数', nested: [1, true] }
1158
+ const results = [{ type: 'text', text: 'PTC结果正文' }]
1159
+ const tracker = workerPool.createConsolidationMeasurement('worker', { sessionId: 'child' })
1160
+ const events = [
1161
+ { seq: 1, type: 'assistant/message', data: { requestId: 'r0', usage: { inputTokens: 2, cacheReadTokens: 0, cacheWriteTokens: 0, outputTokens: 4, reasoningTokens: 0 }, message: { content: [{ type: 'tool-call', id: 'c1', arguments: args }] } } },
1162
+ { seq: 2, type: 'tool/call', data: { callId: 'c1', arguments: args } },
1163
+ { seq: 3, type: 'tool/ptc-dispatch-start', data: { subCallId: 'p1', arguments: ' {"raw": true} ' } },
1164
+ { seq: 4, type: 'tool/ptc-dispatch', data: { subCallId: 'p1', arguments: ' {"raw": true} ', content: results } },
1165
+ { seq: 5, type: 'tool/result', data: { message: { callId: 'p1', content: results } } },
1166
+ { seq: 6, type: 'assistant/message', data: { requestId: 'r1', usage: { inputTokens: 10, cacheReadTokens: 100, cacheWriteTokens: 20, outputTokens: 30, reasoningTokens: 8 }, message: { content: [{ type: 'text', text: '正文' }, { type: 'reasoning', text: '思考' }] } } },
1167
+ { seq: 7, type: 'assistant/message', data: { requestId: 'r1', usage: { inputTokens: 10, cacheReadTokens: 100, cacheWriteTokens: 20, outputTokens: 30, reasoningTokens: 8 }, message: { content: [] } } },
1168
+ { seq: 8, type: 'assistant/message', data: { requestId: 'r2', usage: { inputTokens: 4, cacheReadTokens: 0, cacheWriteTokens: 0, outputTokens: 6 }, message: { content: [] } } },
1169
+ ]
1170
+ for (const event of events) { assert.equal(tracker.observe(event), true); assert.equal(tracker.observe(structuredClone(event)), false) }
1171
+ const m = tracker.measurement
1172
+ assert.equal(m.observed.toolArgumentsChars, JSON.stringify(args).length + ' {"raw": true} '.length)
1173
+ assert.equal(m.observed.toolResultsChars, JSON.stringify(results).length)
1174
+ assert.equal(m.observed.outputTextChars, 2)
1175
+ assert.equal(m.observed.reasoningChars, 2)
1176
+ assert.deepEqual(m.usage, { inputTokens: 16, cacheReadTokens: 100, cacheWriteTokens: 20, outputTokens: 40, reasoningTokens: null, source: 'assistant/message.data.usage', requests: 3 })
1177
+ assert.ok(!JSON.stringify(m).includes('中文参数'), 'no payload copies enter diagnostics')
1178
+ })
1179
+
1180
+ test('unknown usage stays null and a serialization failure is observable, not object-toString', () => {
1181
+ const tracker = workerPool.createConsolidationMeasurement('fork')
1182
+ const cyclic = {}; cyclic.self = cyclic
1183
+ tracker.observe({ seq: 1, type: 'tool/call', data: { arguments: cyclic } })
1184
+ tracker.observe({ seq: 2, type: 'assistant/message', data: { usage: { inputTokens: '10', outputTokens: -1 }, message: { content: [] } } })
1185
+ assert.equal(tracker.measurement.observed.toolArgumentsChars, null)
1186
+ assert.equal(tracker.measurement.observed.estimatedTokens, null)
1187
+ assert.equal(tracker.measurement.serializationErrors, 1)
1188
+ assert.equal(tracker.measurement.usage.inputTokens, null)
1189
+ assert.equal(tracker.measurement.usage.outputTokens, null)
1190
+ })
1191
+
1192
+ test('real dispatch observation includes JSON args, PTC results, replay dedup and epoch cache totals', async () => {
1193
+ state.updateSettings({ consolidationRunner: 'worker' })
1194
+ const args = { fact: '额外参数正文' }
1195
+ const content = [{ type: 'text', text: '额外工具结果' }]
1196
+ const event = { seq: 800, type: 'tool/ptc-dispatch', data: { subCallId: 'ptc1', arguments: args, content } }
1197
+ const ctx = host({ usage: { inputTokens: 10, cacheReadTokens: 100, cacheWriteTokens: 5, outputTokens: 20 }, childEvents: [event, structuredClone(event)] })
1198
+ const id = ctx.bindSession('wl-real-measure')
1199
+ await seedMemory(id, '额外目录标题'.repeat(15), '这条目录必须在实际完整包中计量。')
1200
+ const result = await runWorkerWindow(ctx, id)
1201
+ assert.equal(result.ok, true, result.error || '')
1202
+ const m = result.measurement
1203
+ const text = textOf(ctx.rec.forkFollowups[0])
1204
+ assert.match(text, /额外目录标题/)
1205
+ assert.equal(m.packet.inputChars, text.length)
1206
+ assert.equal(m.observed.toolArgumentsChars, JSON.stringify(args).length)
1207
+ assert.equal(m.observed.toolResultsChars, JSON.stringify(content).length)
1208
+ const epoch = state.getSessionBinding(id).workerEpoch
1209
+ assert.equal(epoch.chars, text.length + m.observed.outputTextChars + JSON.stringify(args).length + JSON.stringify(content).length)
1210
+ assert.equal(epoch.usage.inputTokens, 10)
1211
+ assert.equal(epoch.usage.cacheReadTokens, 100)
1212
+ assert.equal(epoch.usage.cacheWriteTokens, 5)
1213
+ assert.equal(epoch.usage.outputTokens, 20)
1214
+ assert.equal(epoch.usage.reasoningTokens, null)
1215
+ })
1216
+
1217
+ test('legacy measurement epochs retire at the next acquire without migrating bodies', async () => {
1218
+ state.updateSettings({ consolidationRunner: 'worker' })
1219
+ const ctx = host({ resume: 'works' })
1220
+ const id = ctx.bindSession('wl-upgrade')
1221
+ const first = await runWorkerWindow(ctx, id)
1222
+ assert.equal(first.ok, true, first.error || '')
1223
+ const epoch = { ...state.getSessionBinding(id).workerEpoch }; delete epoch.measurementVersion
1224
+ state.setSessionBinding(id, { workerEpoch: epoch })
1225
+ const acquired = await workerPool.acquireWorker(ctx, { ...state.getSessionBinding(id), sessionId: id }, { probe: { hasWrite: true }, agentOptions: { provider: 'p', model: 'm' }, header: { cwd: home } })
1226
+ assert.equal(acquired.ok, true)
1227
+ assert.deepEqual(acquired.retired.map(row => row.reason), ['measurement-upgrade'])
1228
+ assert.notEqual(acquired.forkId, first.childId)
1229
+ assert.equal(acquired.epoch.measurementVersion, 2)
1230
+ assert.equal(acquired.epoch.chars, 0)
1231
+ })
1232
+
1233
+ test('a final packet exceeding the remaining epoch retires once and is remeasured as a handoff', async () => {
1234
+ state.updateSettings({ consolidationRunner: 'worker' })
1235
+ const ctx = host({})
1236
+ const id = ctx.bindSession('wl-packet-budget')
1237
+ const first = await runWorkerWindow(ctx, id)
1238
+ assert.equal(first.ok, true, first.error || '')
1239
+ state.setSessionBinding(id, { workerEpoch: { ...state.getSessionBinding(id).workerEpoch, chars: 119_900 } })
1240
+ ctx.pushTurn(wrappedTurn(10))
1241
+ const second = await runWorkerWindow(ctx, id)
1242
+ assert.equal(second.ok, true, second.error || '')
1243
+ assert.equal(ctx.rec.created.length, 2)
1244
+ assert.deepEqual(ctx.rec.disposed, [first.childId])
1245
+ assert.notEqual(second.childId, first.childId)
1246
+ assert.equal(ctx.rec.forkFollowups.filter(row => row.child === first.childId).length, 1)
1247
+ const text = textOf(ctx.rec.forkFollowups[1])
1248
+ assert.match(text, /私有整理 worker/)
1249
+ assert.match(text, /已结算参考/)
1250
+ assert.equal(second.measurement.packet.kind, 'handoff')
1251
+ assert.equal(second.measurement.packet.inputChars, text.length)
1252
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, 16)
1253
+ })
1254
+
1255
+ test('an oversized first packet returns pending without a dispatch, cursor advance or rebirth loop', async () => {
1256
+ state.updateSettings({ consolidationRunner: 'worker' })
1257
+ const ctx = host({})
1258
+ const id = ctx.bindSession('wl-first-too-large')
1259
+ state.setSessionBinding(id, { sceneTime: '中'.repeat(50_000) })
1260
+ const result = await runWorkerWindow(ctx, id, { force: true })
1261
+ assert.equal(result.ok, false)
1262
+ assert.equal(result.reasonCode, 'packet-too-large')
1263
+ assert.equal(result.settled, false)
1264
+ assert.equal(ctx.rec.created.length, 1)
1265
+ assert.equal(ctx.rec.forkFollowups.length, 0)
1266
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, undefined)
1267
+ assert.equal(result.measurement.dispatched.followups, 0)
1268
+ assert.equal(result.measurement.packet.dispatched, false)
1269
+ const { sessionState } = await import('../lib/consolidation-ledger.js')
1270
+ assert.deepEqual({ fromSeq: sessionState(id).pending.fromSeq, throughSeq: sessionState(id).pending.throughSeq }, { fromSeq: 0, throughSeq: 6 })
1271
+ assert.equal(sessionState(id).checked, null)
1272
+ assert.equal(sessionState(id).inflight, null)
1273
+ })
1274
+
1275
+ test('an idle persistent worker is recreated when the requested output budget changes', async () => {
1276
+ state.updateSettings({ consolidationRunner: 'worker' })
1277
+ const ctx = host({})
1278
+ const id = ctx.bindSession('wl-output-options-change')
1279
+ const binding = { ...state.getSessionBinding(id), sessionId: id }
1280
+ const first = await workerPool.acquireWorker(ctx, binding, { agentOptions: { provider: 'test-provider', model: 'test-model', maxTokens: 4096 }, probe: { hasWrite: true }, header: { cwd: path.join(home, 'proj'), agentPreset: 'coding' } })
1281
+ assert.equal(first.ok, true, first.error || '')
1282
+ const second = await workerPool.acquireWorker(ctx, binding, { agentOptions: { provider: 'test-provider', model: 'test-model', maxTokens: 32768 }, probe: { hasWrite: true }, header: { cwd: path.join(home, 'proj'), agentPreset: 'coding' } })
1283
+ assert.equal(second.ok, true, second.error || '')
1284
+ assert.equal(second.birth, true)
1285
+ assert.notEqual(second.forkId, first.forkId)
1286
+ assert.equal(second.retired[0]?.reason, 'model-options-change')
1287
+ assert.equal(second.handoff, true)
1288
+ assert.ok(ctx.rec.disposed.includes(first.forkId))
1289
+ assert.equal(ctx.rec.created.at(-1).agentOptions.maxTokens, 32768)
1290
+ await workerPool.retireWorker(ctx, second.forkId, 'test-cleanup', { handoff: false })
1291
+ })
1292
+
1293
+ test('wrapup followups are included in actual input and retained epoch totals', async () => {
1294
+ state.updateSettings({ consolidationRunner: 'worker' })
1295
+ const ctx = host({ childEvents: Array.from({ length: 12 }, (_, i) => ({ type: 'tool/call', data: { callId: 'wrap-' + i, arguments: '{}' } })) })
1296
+ const id = ctx.bindSession('wl-wrapup-measure')
1297
+ const result = await runWorkerWindow(ctx, id)
1298
+ assert.equal(result.ok, true, result.error || '')
1299
+ assert.equal(ctx.rec.forkFollowups.length, 2)
1300
+ const { estTokens } = await import('../lib/budget.js')
1301
+ const texts = ctx.rec.forkFollowups.map(textOf)
1302
+ const m = result.measurement
1303
+ assert.equal(m.dispatched.inputChars, texts.reduce((sum, text) => sum + text.length, 0))
1304
+ assert.equal(m.dispatched.estimatedTokens, texts.reduce((sum, text) => sum + estTokens(text), 0))
1305
+ assert.equal(m.dispatched.wrapupChars, texts[1].length)
1306
+ assert.equal(state.getSessionBinding(id).workerEpoch.chars, m.dispatched.inputChars + m.observed.outputTextChars + m.observed.toolArgumentsChars)
1307
+ })
1308
+
1309
+ test('a synchronously rejected wrapup is not charged as dispatched input', async () => {
1310
+ state.updateSettings({ consolidationRunner: 'worker' })
1311
+ const ctx = host({ wrapupThrows: true, childEvents: Array.from({ length: 12 }, (_, i) => ({ type: 'tool/call', data: { callId: 'rejected-wrap-' + i, arguments: '{}' } })) })
1312
+ const id = ctx.bindSession('wl-rejected-wrapup')
1313
+ const result = await runWorkerWindow(ctx, id)
1314
+ assert.equal(result.ok, true, result.error || '')
1315
+ assert.equal(ctx.rec.forkFollowups.length, 1)
1316
+ const text = textOf(ctx.rec.forkFollowups[0])
1317
+ const { estTokens } = await import('../lib/budget.js')
1318
+ const m = result.measurement
1319
+ assert.equal(m.dispatched.followups, 1)
1320
+ assert.equal(m.dispatched.wrapupChars, 0)
1321
+ assert.equal(m.dispatched.inputChars, text.length)
1322
+ assert.equal(m.dispatched.estimatedTokens, estTokens(text))
1323
+ assert.equal(state.getSessionBinding(id).workerEpoch.chars, text.length + m.observed.outputTextChars + m.observed.toolArgumentsChars)
1324
+ })
1325
+
1326
+ test('a timed-out turn landing with its listener detached is fenced by the public child cursor', async () => {
1327
+ state.updateSettings({ consolidationRunner: 'worker' })
1328
+ let replay = []
1329
+ const ctx = host({ childEvents: () => replay })
1330
+ const id = ctx.bindSession('wl-detached-late-replay')
1331
+ ctx.setDelayTurn(true)
1332
+ const first = await runWorkerWindow(ctx, id, { maxWaitMs: 40 })
1333
+ assert.equal(first.timedOut, true)
1334
+ ctx.completeTurn()
1335
+ replay = ctx.rec.childEvents.map(row => structuredClone(row.event))
1336
+ ctx.setDelayTurn(false)
1337
+ const second = await runWorkerWindow(ctx, id)
1338
+ assert.equal(second.ok, true, second.error || '')
1339
+ assert.equal(second.childId, first.childId)
1340
+ const lastText = ctx.rec.childEvents.filter(row => row.event.type === 'assistant/message').at(-1).event.data.message.content[0].text
1341
+ assert.equal(second.measurement.observed.outputTextChars, lastText.length, 'old receipts are neither charged nor used by the next job')
1342
+ const oldText = replay.find(event => event.type === 'assistant/message').data.message.content[0].text
1343
+ const epoch = state.getSessionBinding(id).workerEpoch
1344
+ assert.equal(epoch.lateOutputChars, oldText.length, 'late output is charged to its old epoch, not silently treated as zero')
1345
+ assert.equal(epoch.chars, first.measurement.dispatched.inputChars + oldText.length + second.measurement.dispatched.inputChars + lastText.length)
1346
+ assert.equal(epoch.windows, 2, 'catching up late output does not create an extra window')
1347
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, 6)
1348
+ })
1349
+
1350
+ test('packet metering distinguishes languages without changing the existing character budget policy', () => {
1351
+ const latin = workerPool.measurePacket('a'.repeat(20_000))
1352
+ const chinese = workerPool.measurePacket('中'.repeat(20_000))
1353
+ assert.ok(chinese.estimatedTokens > latin.estimatedTokens)
1354
+ assert.equal(workerPool.budgetFit({ chars: 0 }, chinese.inputChars), true)
1355
+ assert.equal(workerPool.packetBudgetFit({ chars: 0 }, latin), true)
1356
+ assert.equal(workerPool.packetBudgetFit({ chars: 0 }, chinese), true)
1357
+ assert.equal(workerPool.packetBudgetFit({ chars: 120_000 }, chinese), false)
1358
+ })
1359
+
1360
+ test('a request without usage prevents later known requests from masquerading as complete totals', () => {
1361
+ const tracker = workerPool.createConsolidationMeasurement('worker', { sessionId: 'usage-missing' })
1362
+ tracker.observe({ seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: 'first' }] } } })
1363
+ tracker.observe({ seq: 2, type: 'assistant/message', data: { usage: { inputTokens: 10, cacheReadTokens: 20, cacheWriteTokens: 0, outputTokens: 5, reasoningTokens: 0 }, message: { content: [{ type: 'text', text: 'second' }] } } })
1364
+ assert.equal(tracker.measurement.usage.requests, 2)
1365
+ assert.equal(tracker.measurement.usage.inputTokens, null)
1366
+ assert.equal(tracker.measurement.usage.cacheReadTokens, null)
1367
+ assert.equal(tracker.measurement.usage.outputTokens, null)
1368
+ })
1369
+
1370
+ test('missing usage fields remain unknown when requests are aggregated', () => {
1371
+ const tracker = workerPool.createConsolidationMeasurement('worker', { sessionId: 'usage-partial' })
1372
+ tracker.observe({ seq: 1, type: 'assistant/message', data: { requestId: 'r1', usage: { inputTokens: 1, cacheReadTokens: 5, outputTokens: 2 } } })
1373
+ tracker.observe({ seq: 2, type: 'assistant/message', data: { requestId: 'r2', usage: { inputTokens: 3, outputTokens: 4 } } })
1374
+ assert.equal(tracker.measurement.usage.inputTokens, 4)
1375
+ assert.equal(tracker.measurement.usage.outputTokens, 6)
1376
+ assert.equal(tracker.measurement.usage.cacheReadTokens, null)
1377
+ assert.equal(tracker.measurement.usage.cacheWriteTokens, null)
1378
+ assert.equal(tracker.measurement.usage.reasoningTokens, null)
1379
+ })
1380
+
1381
+ test('late PTC results catch up epoch size without double-counting arguments from the old prefix', async () => {
1382
+ const ctx = host({})
1383
+ const id = ctx.bindSession('wl-late-ptc-size')
1384
+ const binding = () => ({ ...state.getSessionBinding(id), sessionId: id })
1385
+ const options = { probe: { hasWrite: true }, agentOptions: { provider: 'p', model: 'm' }, header: { cwd: home } }
1386
+ const first = await workerPool.acquireWorker(ctx, binding(), options)
1387
+ const tracker = workerPool.createConsolidationMeasurement('worker', { sessionId: first.forkId })
1388
+ const args = { fact: '工具参数' }
1389
+ const content = [{ type: 'text', text: '迟到的PTC结果' }]
1390
+ const start = { seq: 1, type: 'tool/ptc-dispatch-start', data: { subCallId: 'p1', arguments: args } }
1391
+ ctx.emit(first.handle.agent.session, start)
1392
+ tracker.observe(start)
1393
+ tracker.dispatch('first packet', 'handoff')
1394
+ const before = workerPool.recordEpochProgress(binding(), { measurement: tracker.measurement })
1395
+ ctx.emit(first.handle.agent.session, { seq: 2, type: 'tool/ptc-dispatch', data: { subCallId: 'p1', arguments: args, content } })
1396
+ const second = await workerPool.acquireWorker(ctx, binding(), options)
1397
+ assert.equal(second.ok, true, second.error || '')
1398
+ assert.equal(second.reused, true)
1399
+ assert.equal(second.epoch.chars, before.chars + JSON.stringify(content).length)
1400
+ assert.equal(second.epoch.lateOutputChars, JSON.stringify(content).length)
1401
+ assert.equal(second.epoch.windows, 1)
1402
+ assert.equal(second.eventCursor, 2)
1403
+ })
1404
+
1405
+ test('an unreadable late-output snapshot retires conservatively and keeps the range pending', async () => {
1406
+ state.updateSettings({ consolidationRunner: 'worker' })
1407
+ const ctx = host({})
1408
+ const id = ctx.bindSession('wl-late-snapshot-unavailable')
1409
+ ctx.setDelayTurn(true)
1410
+ const first = await runWorkerWindow(ctx, id, { maxWaitMs: 40 })
1411
+ assert.equal(first.timedOut, true)
1412
+ ctx.completeTurn()
1413
+ ctx.setDelayTurn(false)
1414
+ const get = ctx.get
1415
+ ctx.get = name => name === 'sessionQuery' ? { readSession: async target => {
1416
+ if (target === first.childId) throw new Error('child snapshot unreadable')
1417
+ return get(name).readSession(target)
1418
+ } } : get(name)
1419
+ const second = await runWorkerWindow(ctx, id)
1420
+ assert.equal(second.ok, false)
1421
+ assert.equal(second.reasonCode, 'worker-measurement-unavailable')
1422
+ assert.equal(ctx.rec.created.length, 1)
1423
+ assert.equal(ctx.rec.forkFollowups.length, 1)
1424
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, undefined)
1425
+ assert.equal(state.getSessionBinding(id).workerEpoch, null)
1426
+ const { sessionState } = await import('../lib/consolidation-ledger.js')
1427
+ assert.equal(sessionState(id).pending.throughSeq, 6)
1428
+ assert.equal(sessionState(id).checked, null)
1429
+ })