dsh-memu-memory 1.3.7 → 1.3.9

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 (63) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +70 -0
  3. package/README.md +7 -7
  4. package/README.zh.md +7 -7
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/contributing.md +2 -2
  7. package/docs/host-adaptation.md +1 -1
  8. package/docs/memory-semantics.md +7 -6
  9. package/docs/troubleshooting.md +74 -7
  10. package/lib/auto-link/decide.js +0 -4
  11. package/lib/binding-diagnostics.js +2 -2
  12. package/lib/client.js +150 -81
  13. package/lib/consolidation-ledger.js +6 -2
  14. package/lib/curator.js +42 -10
  15. package/lib/cycle.js +28 -3
  16. package/lib/inbound.js +24 -9
  17. package/lib/inject.js +379 -215
  18. package/lib/local-vector-service.js +1 -10
  19. package/lib/memory.js +704 -181
  20. package/lib/paths.js +24 -0
  21. package/lib/private.js +294 -134
  22. package/lib/rpc.js +53 -6
  23. package/lib/snippet.js +49 -28
  24. package/lib/state.js +185 -26
  25. package/lib/tools.js +137 -28
  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 +587 -26
  36. package/tests/cross-library-recall.test.mjs +156 -0
  37. package/tests/cue.test.mjs +15 -2
  38. package/tests/curator-contract.test.mjs +191 -0
  39. package/tests/curator-probe.test.mjs +5 -5
  40. package/tests/curator.test.mjs +3 -1
  41. package/tests/hybrid-recall.test.mjs +488 -0
  42. package/tests/inbound.test.mjs +49 -4
  43. package/tests/inject-conflict.test.mjs +70 -9
  44. package/tests/inject-guide.test.mjs +13 -1
  45. package/tests/inject.test.mjs +10 -0
  46. package/tests/injection-budget.test.mjs +101 -0
  47. package/tests/injection-chain.test.mjs +37 -0
  48. package/tests/injection-rollback.test.mjs +172 -9
  49. package/tests/issue2-chain.test.mjs +169 -0
  50. package/tests/lexicon-inject.test.mjs +33 -5
  51. package/tests/managed-memory.test.mjs +625 -1
  52. package/tests/media.test.mjs +1 -1
  53. package/tests/new-session-gate.test.mjs +280 -25
  54. package/tests/open-loop-date.test.mjs +11 -1
  55. package/tests/recall-intent.test.mjs +52 -3
  56. package/tests/regression-sweep.test.mjs +281 -0
  57. package/tests/simulate-injection.test.mjs +4 -4
  58. package/tests/snippet.test.mjs +33 -1
  59. package/tests/state.test.mjs +8 -3
  60. package/tests/tool-schema.test.mjs +52 -0
  61. package/tests/tools.test.mjs +394 -0
  62. package/tests/webui.test.mjs +16 -2
  63. package/tests/worker-lifecycle.test.mjs +419 -36
@@ -3,14 +3,21 @@ import assert from 'node:assert/strict'
3
3
  import fs from 'node:fs'
4
4
  import os from 'node:os'
5
5
  import path from 'node:path'
6
+ import { spawn } from 'node:child_process'
6
7
 
7
8
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-fork-'))
9
+ process.env.DSH_HOME = home
8
10
  process.env.DSH_MEMU_HOME = home
11
+ process.env.DSH_MEMU_MEMORY_HOME = home
9
12
 
10
13
  const state = await import('../lib/state.js')
11
14
  const activity = await import('../lib/activity-log.js')
15
+ const ledger = await import('../lib/consolidation-ledger.js')
12
16
  const forkModel = await import('../lib/fork-model.js')
13
- const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY, CONSOLIDATION_WINDOW_EVENTS, isEffortRefused, effortRefusalOf, compactSeedEvents, selectConsolidationWindow, selectTailTurnWindow, mustCoverCandidates, mergeMustCover, candidateCovered } = await import('../lib/private.js')
17
+ const { dataDir, setWarnSink } = await import('../lib/paths.js')
18
+ const { retireWorker } = await import('../lib/worker-pool.js')
19
+ const { CORE_WRITE_TOOLS, WORKER_TOOL_ALLOW } = await import('../lib/consolidation-worker.js')
20
+ const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY, CONSOLIDATION_WINDOW_EVENTS, isEffortRefused, markEffortRefused, effortRefusalOf, compactSeedEvents, selectConsolidationWindow, selectTailTurnWindow, mustCoverCandidates, mergeMustCover, candidateCovered } = await import('../lib/private.js')
14
21
  // 这些用例验证“路由继承”,不是推理强度;默认 medium 由 config 测试单独覆盖。
15
22
  state.updateSettings({ consolidationReasoningEffort: 'inherit' })
16
23
 
@@ -57,9 +64,10 @@ function assertHostCreateAccepts(spec = {}) {
57
64
  }
58
65
  }
59
66
 
60
- function host({ live = false, whenIdle = null, parentOptions = { provider: 'test-provider', model: 'test-model' }, requestConfig = null, extraEvents = [], transcriptSize = 0, turnReason = { kind: 'completed' }, emitTurnEnd = true, headerTools = null, childCtxFactory = null, llm = null } = {}) {
67
+ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test-provider', model: 'test-model' }, requestConfig = null, extraEvents = [], transcriptSize = 0, turnReason = { kind: 'completed' }, emitTurnEnd = true, headerTools = null, childCtxFactory = null, llm = null, cwd = path.join(home, 'proj') } = {}) {
61
68
  const rec = { liveFollowups: [], created: [], forkFollowups: [], disposed: [], sessionHandlers: [], workerToolRegistrations: [], workerToolDisposals: [] }
62
- const childContexts = new Map()
69
+ // agents.get 返回裸 agent;dispose 注销活句柄,但会话 id 仍在磁盘上占用。
70
+ const childAgents = new Map()
63
71
  const tick = String.fromCharCode(96)
64
72
  const receiptFence = (range, identity) => [tick + tick + tick + 'memu-consolidation-receipt', JSON.stringify({ version: 1, ...identity, status: 'completed', outcome: 'no_value', checkedRange: range, createdIds: [], updatedIds: [], heldIds: [], reasonCode: null, retryable: false }), tick + tick + tick].join('\n')
65
73
  // 真实长会话的规模:补齐不产生证据的事件,只影响 fork 成本判定。
@@ -79,8 +87,7 @@ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test
79
87
  if (name === 'agents') {
80
88
  return {
81
89
  get: (id) => {
82
- // attachWorkerTools 用 childContexts 模拟"宿主在 create 后暴露的 agent ctx"。
83
- if (childContexts.has(id)) return { ctx: childContexts.get(id) }
90
+ if (childAgents.has(id)) return childAgents.get(id)
84
91
  return (live
85
92
  ? {
86
93
  followup: (message) => rec.liveFollowups.push({ id, message }),
@@ -94,16 +101,23 @@ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test
94
101
  },
95
102
  create: async (spec) => {
96
103
  assertHostCreateAccepts(spec)
104
+ if (childAgents.has(spec.sessionId)) throw new Error('session already exists: ' + spec.sessionId)
97
105
  rec.created.push(spec)
98
- if (childCtxFactory) childContexts.set(spec.sessionId, childCtxFactory())
99
106
  const childSession = { id: spec.sessionId }
100
- return {
107
+ const dispose = async () => {
108
+ rec.disposed.push(spec.sessionId)
109
+ childAgents.set(spec.sessionId, null)
110
+ }
111
+ const handle = {
101
112
  agent: {
102
113
  session: childSession,
114
+ ctx: childCtxFactory?.(),
115
+ dispose,
103
116
  followup: (message) => {
104
117
  rec.forkFollowups.push({ child: spec.sessionId, message })
105
118
  if (emitTurnEnd) {
106
- if (turnReason?.kind === 'completed') {
119
+ const reason = typeof turnReason === 'function' ? turnReason(spec) : turnReason
120
+ if (reason?.kind === 'completed') {
107
121
  // The worker receipt must match the window the fork was seeded
108
122
  // with, not the whole parent transcript.
109
123
  const child = state.getSessionBinding(spec.sessionId)
@@ -116,14 +130,16 @@ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test
116
130
  }
117
131
  }
118
132
  for (const handler of rec.sessionHandlers) {
119
- handler(childSession, { type: 'turn/end', seq: 100, data: { turn: 1, reason: turnReason } })
133
+ handler(childSession, { type: 'turn/end', seq: 100, data: { turn: 1, reason } })
120
134
  }
121
135
  }
122
136
  },
123
137
  whenIdle: whenIdle || (async () => {}),
124
138
  },
125
- dispose: async () => { rec.disposed.push(spec.sessionId) },
139
+ dispose,
126
140
  }
141
+ childAgents.set(spec.sessionId, handle.agent)
142
+ return handle
127
143
  },
128
144
  }
129
145
  }
@@ -140,7 +156,7 @@ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test
140
156
  ...extraEvents,
141
157
  ...filler,
142
158
  ],
143
- session: { cwd: path.join(home, 'proj'), agentPreset: 'coding' },
159
+ session: { cwd, agentPreset: 'coding' },
144
160
  }),
145
161
  }
146
162
  }
@@ -196,7 +212,75 @@ test('a live session is consolidated in a fork, not by queueing on itself', asyn
196
212
  assert.equal(result.scanned, 3, 'report how much of the transcript was scanned')
197
213
  assert.equal(result.fresh, 3, 'report how many events were new since the last consolidation')
198
214
  assert.equal(result.wrote, 0, 'the fake fork writes nothing, but the metric must still be measured')
215
+ const text = ctx.rec.forkFollowups[0].message.content[0].text
216
+ const { estTokens } = await import('../lib/budget.js')
217
+ assert.equal(result.measurement.runner, 'fork')
218
+ assert.equal(result.measurement.packet.inputChars, text.length)
219
+ assert.equal(result.measurement.packet.estimatedTokens, estTokens(text))
220
+ assert.equal(result.measurement.usage.inputTokens, null)
221
+ })
222
+
223
+ for (const restriction of ['succeeds', 'missing', 'throws twice']) {
224
+ test(`a fork keeps host permissions and dispatches when tools.restrict ${restriction}`, async (t) => {
225
+ const id = 'fork-permissions-' + restriction.replaceAll(' ', '-')
226
+ state.ensureSession(id, { cwd: home, agentPreset: 'coding' })
227
+ const setPermission = t.mock.fn()
228
+ const disposeRestriction = t.mock.fn()
229
+ const followupsAtRestriction = []
230
+ const restrict = t.mock.fn(() => {
231
+ followupsAtRestriction.push(ctx.rec.forkFollowups.length)
232
+ if (restriction === 'throws twice') throw new Error('host refused tool restriction')
233
+ return disposeRestriction
234
+ })
235
+ const ctx = host({
236
+ live: true,
237
+ headerTools: [...CORE_WRITE_TOOLS, 'read', 'shell'],
238
+ childCtxFactory: () => ({ tools: restriction === 'missing' ? {} : { restrict } }),
239
+ })
240
+ ctx.permissionPresets = { set: setPermission }
241
+
242
+ const result = await requestPrivateConsolidation(ctx, id)
243
+ assert.equal(setPermission.mock.callCount(), 0, 'the plugin must not change the host permission preset')
244
+ assert.equal(result.ok, true, String(result.error || ''))
245
+ assert.equal(result.settled, true, 'missing or failing restrict keeps the existing capability fallback')
246
+ assert.equal(ctx.rec.created.length, 1)
247
+ assert.equal(ctx.rec.forkFollowups.length, 1, 'the fork still receives the consolidation task')
248
+ assert.equal(ctx.rec.liveFollowups.length, 0, 'the parent never receives the task')
249
+ assert.equal(ctx.rec.disposed.length, 1, 'the scratch fork is still disposed')
250
+ const expectedAllows = restriction === 'missing' ? []
251
+ : restriction === 'throws twice' ? [WORKER_TOOL_ALLOW, CORE_WRITE_TOOLS] : [WORKER_TOOL_ALLOW]
252
+ assert.deepEqual(restrict.mock.calls.map((call) => call.arguments), expectedAllows.map((allow) => [{ allow }]),
253
+ 'restriction still tries the full allowlist and falls back to the write core on failure')
254
+ assert.deepEqual(followupsAtRestriction, expectedAllows.map(() => 0), 'all restriction attempts precede dispatch')
255
+ assert.equal(disposeRestriction.mock.callCount(), restriction === 'succeeds' ? 1 : 0)
256
+ })
257
+ }
258
+
259
+ test('a fork preserves an existing parent cwd', async () => {
260
+ const cwd = fs.mkdtempSync(path.join(home, 'existing-cwd-'))
261
+ state.ensureSession('fork-cwd-existing', { cwd, agentPreset: 'coding' })
262
+ const ctx = host({ live: true, cwd })
263
+ const result = await requestPrivateConsolidation(ctx, 'fork-cwd-existing')
264
+ assert.equal(result.ok, true, String(result.error || ''))
265
+ assert.equal(ctx.rec.created.length, 1)
266
+ assert.notEqual(cwd, dataDir(), 'the existing cwd differs from the fallback')
267
+ assert.equal(ctx.rec.created[0].meta.cwd, cwd)
268
+ assert.equal(ctx.rec.forkFollowups.length, 1)
269
+ })
270
+
271
+ test('a fork falls back to the real dataDir when the parent cwd no longer exists', async () => {
272
+ const cwd = path.join(home, 'missing-cwd')
273
+ assert.equal(fs.existsSync(cwd), false)
274
+ state.ensureSession('fork-cwd-missing', { cwd, agentPreset: 'coding' })
275
+ const ctx = host({ live: true, cwd })
276
+ const result = await requestPrivateConsolidation(ctx, 'fork-cwd-missing')
277
+ assert.equal(result.ok, true, String(result.error || ''))
278
+ assert.equal(ctx.rec.created.length, 1)
279
+ assert.equal(ctx.rec.created[0].meta.cwd, dataDir())
280
+ assert.equal(fs.statSync(ctx.rec.created[0].meta.cwd).isDirectory(), true, 'the fallback is a real directory')
281
+ assert.equal(ctx.rec.forkFollowups.length, 1)
199
282
  })
283
+
200
284
  test('a live session inherits the route of its latest turn, not stale creation options', async () => {
201
285
  state.ensureSession('fork-route', { cwd: path.join(home, 'proj-route'), agentPreset: 'coding' })
202
286
  const ctx = host({
@@ -253,6 +337,12 @@ test('a failed fork turn is reported as failure and does not advance the sleep c
253
337
  assert.equal(state.getSessionBinding('fork-turn-error').lastSleepSeq, undefined, 'a failed turn must be retried, not marked asleep')
254
338
  assert.equal(ctx.rec.disposed.length, 1, 'the failed fork is still disposed')
255
339
  assert.equal(ctx.rec.sessionHandlers.length, 0, 'the failed fork listener is removed')
340
+ const { sessionState } = await import('../lib/consolidation-ledger.js')
341
+ const ledger = sessionState('fork-turn-error')
342
+ assert.equal(ledger.checked, null)
343
+ assert.equal(ledger.pending.fromSeq, 0)
344
+ assert.equal(ledger.pending.throughSeq, 2)
345
+ assert.ok(result.measurement.packet.inputChars > 0, 'failed dispatches still carry cost measurement')
256
346
  })
257
347
 
258
348
  test('a fork that never reports turn/end is a failure, not a success', async () => {
@@ -476,7 +566,7 @@ test('a candidate is covered only when a written entry carries the fact', () =>
476
566
 
477
567
  test('the same failed snapshot stops automatic re-forking after the failure cap', async () => {
478
568
  state.ensureSession('fork-failcap', { cwd: path.join(home, 'proj-failcap'), agentPreset: 'coding' })
479
- const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: 'provider refused' } } })
569
+ const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: 'provider refused max-tokens argument' } } })
480
570
  const first = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
481
571
  const second = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
482
572
  assert.equal(first.ok, false)
@@ -493,6 +583,161 @@ test('the same failed snapshot stops automatic re-forking after the failure cap'
493
583
  assert.equal(ctx.rec.created.length, 3, 'a manual retry is allowed past the cap')
494
584
  })
495
585
 
586
+ for (const runner of ['fork', 'worker']) {
587
+ test(`${runner} preserves max-tokens pending and retries the same snapshot only after output configuration changes`, async () => {
588
+ state.updateSettings({ consolidationRunner: runner, consolidationModelMode: 'inherit', consolidationReasoningEffort: 'inherit' })
589
+ const id = 'output-limit-' + runner
590
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
591
+ const parentOptions = { provider: id, model: 'test-model', maxTokens: 4096, reasoningEffort: 'medium' }
592
+ markEffortRefused([id, 'test-model', 'medium'].join('|'))
593
+ const ctx = host({ live: true, parentOptions, turnReason: spec => spec.agentOptions.maxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
594
+ try {
595
+ for (let i = 0; i < 2; i++) {
596
+ const failed = await requestPrivateConsolidation(ctx, id, { force: true })
597
+ assert.equal(failed.ok, false)
598
+ assert.equal(failed.settled, false)
599
+ assert.equal(failed.reasonCode, 'model-output-limit')
600
+ assert.equal(failed.retryable, true)
601
+ assert.equal(failed.configuredMaxTokens, 4096)
602
+ assert.match(failed.error, /输出预算不足/)
603
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, undefined)
604
+ assert.ok(ledger.sessionState(id).pending)
605
+ assert.equal(parentOptions.maxTokens, 4096, 'the plugin never raises the parent limit')
606
+ assert.equal(parentOptions.reasoningEffort, 'medium')
607
+ assert.equal(ctx.rec.created.at(-1).agentOptions.reasoningEffort, undefined)
608
+ }
609
+ const suppressed = await requestPrivateConsolidation(ctx, id)
610
+ assert.equal(suppressed.skipped, 'snapshot-failed')
611
+ assert.equal(suppressed.settled, false)
612
+ assert.equal(ctx.rec.created.length, 2)
613
+ parentOptions.maxTokens = 32768
614
+ const recovered = await requestPrivateConsolidation(ctx, id)
615
+ assert.equal(recovered.ok, true, recovered.error || '')
616
+ assert.equal(recovered.settled, true)
617
+ assert.equal(ctx.rec.created.length, 3)
618
+ assert.equal(ctx.rec.created.at(-1).agentOptions.maxTokens, 32768)
619
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, 2)
620
+ assert.equal(ledger.sessionState(id).pending, null)
621
+ } finally {
622
+ const worker = state.getSessionBinding(id)?.workerEpoch?.forkSessionId
623
+ if (worker) await retireWorker(ctx, worker, 'test-cleanup', { handoff: false })
624
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'inherit' })
625
+ }
626
+ })
627
+ }
628
+
629
+ test('host-route output default changes unlock a truncated snapshot without inheriting a parent route or overriding its cap', async () => {
630
+ const id = 'output-default-host'
631
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
632
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'host', consolidationModel: 'test-provider/test-model', consolidationReasoningEffort: 'inherit' })
633
+ let defaultMaxTokens = 4096
634
+ const ctx = host({ live: false, llm: { resolveModelInfo: async () => ({ defaultMaxTokens }) }, turnReason: () => defaultMaxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
635
+ try {
636
+ for (let i = 0; i < 2; i++) {
637
+ const result = await requestPrivateConsolidation(ctx, id, { force: true })
638
+ assert.equal(result.reasonCode, 'model-output-limit')
639
+ assert.equal(result.configuredMaxTokens, 4096)
640
+ }
641
+ const frozen = await requestPrivateConsolidation(ctx, id)
642
+ assert.equal(frozen.skipped, 'snapshot-failed')
643
+ defaultMaxTokens = 32768
644
+ const resumed = await requestPrivateConsolidation(ctx, id)
645
+ assert.equal(resumed.ok, true, resumed.error || '')
646
+ assert.equal(resumed.settled, true)
647
+ assert.equal(ctx.rec.created.length, 3)
648
+ assert.ok(ctx.rec.created.every(spec => !Object.hasOwn(spec.agentOptions, 'maxTokens')))
649
+ } finally {
650
+ state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
651
+ }
652
+ })
653
+
654
+ test('a budget change during a truncated turn is not charged as a failed attempt of the new configuration', async () => {
655
+ const id = 'output-limit-mid-turn-change'
656
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
657
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'inherit', consolidationReasoningEffort: 'inherit' })
658
+ const parentOptions = { provider: id, model: 'test-model', maxTokens: 4096 }
659
+ let oldAttempts = 0
660
+ let newAttempts = 0
661
+ const ctx = host({ live: true, parentOptions, turnReason: spec => {
662
+ if (spec.agentOptions.maxTokens === 4096) {
663
+ if (++oldAttempts === 2) parentOptions.maxTokens = 8192
664
+ return { kind: 'max-tokens' }
665
+ }
666
+ return ++newAttempts === 1 ? { kind: 'max-tokens' } : { kind: 'completed' }
667
+ } })
668
+ for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
669
+ assert.equal((await requestPrivateConsolidation(ctx, id)).reasonCode, 'model-output-limit')
670
+ const recovered = await requestPrivateConsolidation(ctx, id)
671
+ assert.equal(recovered.ok, true, recovered.error || '')
672
+ assert.equal(recovered.settled, true)
673
+ assert.equal(newAttempts, 2)
674
+ assert.equal(ctx.rec.created.length, 4)
675
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, 2)
676
+ })
677
+
678
+ test('a provider default reasoning change reopens an output-limited host route without an explicit effort override', async () => {
679
+ const id = 'output-limit-default-reasoning'
680
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
681
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'host', consolidationModel: id + '/test-model', consolidationReasoningEffort: 'inherit' })
682
+ let defaultEffort = 'high'
683
+ const ctx = host({ live: false, llm: { resolveModelInfo: async () => ({ defaultMaxTokens: 4096, reasoning: { defaultEffort } }) }, turnReason: () => defaultEffort === 'high' ? { kind: 'max-tokens' } : { kind: 'completed' } })
684
+ try {
685
+ for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
686
+ assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
687
+ defaultEffort = 'low'
688
+ const result = await requestPrivateConsolidation(ctx, id)
689
+ assert.equal(result.ok, true, result.error || '')
690
+ assert.equal(result.settled, true)
691
+ assert.equal(ctx.rec.created.length, 3)
692
+ assert.ok(ctx.rec.created.every(spec => !Object.hasOwn(spec.agentOptions, 'reasoningEffort')))
693
+ } finally {
694
+ state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
695
+ }
696
+ })
697
+
698
+ test('unavailable model metadata does not masquerade as an output configuration change', async () => {
699
+ const id = 'output-limit-unavailable-defaults'
700
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
701
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'host', consolidationModel: id + '/test-model', consolidationReasoningEffort: 'inherit' })
702
+ let unavailable = false
703
+ let defaultMaxTokens = 4096
704
+ const ctx = host({ live: false, llm: { resolveModelInfo: async () => {
705
+ if (unavailable) throw new Error('model metadata unavailable')
706
+ return { defaultMaxTokens }
707
+ } }, turnReason: () => defaultMaxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
708
+ try {
709
+ for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
710
+ unavailable = true
711
+ assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
712
+ unavailable = false
713
+ assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
714
+ assert.equal(ctx.rec.created.length, 2)
715
+ defaultMaxTokens = 32768
716
+ assert.equal((await requestPrivateConsolidation(ctx, id)).settled, true)
717
+ assert.equal(ctx.rec.created.length, 3)
718
+ } finally {
719
+ state.updateSettings({ consolidationModelMode: 'inherit', consolidationModel: '' })
720
+ }
721
+ })
722
+
723
+ test('an explicit live output limit supersedes a cached header budget only on the same route', async () => {
724
+ const id = 'output-limit-cached-header'
725
+ state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
726
+ state.updateSettings({ consolidationRunner: 'fork', consolidationModelMode: 'inherit', consolidationReasoningEffort: 'inherit' })
727
+ const parentOptions = { provider: id, model: 'test-model', maxTokens: 4096 }
728
+ const requestConfig = Object.freeze({ provider: id, model: 'test-model', maxTokens: 4096 })
729
+ const ctx = host({ live: true, parentOptions, requestConfig, turnReason: spec => spec.agentOptions.maxTokens <= 4096 ? { kind: 'max-tokens' } : { kind: 'completed' } })
730
+ for (let i = 0; i < 2; i++) assert.equal((await requestPrivateConsolidation(ctx, id, { force: true })).reasonCode, 'model-output-limit')
731
+ assert.equal((await requestPrivateConsolidation(ctx, id)).skipped, 'snapshot-failed')
732
+ parentOptions.maxTokens = 32768
733
+ const result = await requestPrivateConsolidation(ctx, id)
734
+ assert.equal(result.ok, true, result.error || '')
735
+ assert.equal(result.settled, true)
736
+ assert.equal(ctx.rec.created.at(-1).agentOptions.maxTokens, 32768)
737
+ assert.equal(requestConfig.maxTokens, 4096)
738
+ assert.equal(ctx.rec.created.length, 3)
739
+ })
740
+
496
741
  // ---------------------------------------------------------------- PTC 兼容
497
742
  // 现场(2026-10-31,yuike-ptc 会话):PTC 模式下 request/header 的工具表只有 run_code,
498
743
  // probe 曾据此判 unavailable(worker-tools-ptc-only),PTC 会话永远不被整理。宿主的
@@ -925,21 +1170,337 @@ test('a replace is dropped when filtering an inner checkpoint reveals a shadowed
925
1170
 
926
1171
  // 2026-11-15 扫雷守卫:整理思考强度被模型拒绝 → 学习组合 → 清失败连击 → 下次 fork 不带档。
927
1172
  // 现场:wb/glm-5.3-flash 不支持 medium,fork 回合起点即失败,同快照 2 次后被冻结数天。
928
- test('an unsupported reasoning effort is learned, the snapshot gate is reset, and the next fork drops the effort', async () => {
1173
+ function rejectMedium(spec) {
1174
+ const { provider, model, reasoningEffort } = spec.agentOptions
1175
+ return reasoningEffort === 'medium'
1176
+ ? { kind: 'error', error: { message: `provider "${provider}" model "${model}" does not support reasoning effort "medium"` } }
1177
+ : { kind: 'completed' }
1178
+ }
1179
+
1180
+ function cleanupEffortHost(t, ctx, sessionId) {
1181
+ t.after(async () => {
1182
+ const forkId = state.getSessionBinding(sessionId)?.workerEpoch?.forkSessionId
1183
+ if (forkId) await retireWorker(ctx, forkId, 'test-finished', { handoff: false })
1184
+ state.updateSettings({ consolidationRunner: 'fork', consolidationReasoningEffort: 'inherit' })
1185
+ restoreSettings()
1186
+ })
1187
+ }
1188
+
1189
+ for (const runner of ['fork', 'worker']) {
1190
+ for (const mode of ['inherit', 'custom']) {
1191
+ for (const effort of ['inherit', 'medium']) {
1192
+ test(`${runner} learns inherited medium with ${mode} route / ${effort} setting and really succeeds on retry`, async (t) => {
1193
+ const id = `effort-${runner}-${mode}-${effort}`
1194
+ const parentOptions = Object.freeze({ provider: id, model: 'test-model', reasoningEffort: 'medium', maxTokens: 32768 })
1195
+ const key = `${id}|test-model|medium`
1196
+ const ctx = host({ live: true, parentOptions, turnReason: rejectMedium })
1197
+ ctx.permissionPresets = { set: t.mock.fn() }
1198
+ cleanupEffortHost(t, ctx, id)
1199
+ state.updateSettings({ ...(mode === 'custom' ? CUSTOM : {}), consolidationRunner: runner, consolidationReasoningEffort: effort })
1200
+ state.ensureSession(id, { cwd: home, agentPreset: 'coding' })
1201
+ assert.equal(effortRefusalOf(rejectMedium({ agentOptions: parentOptions }).error.message).key, key)
1202
+ assert.equal(isEffortRefused(key), false)
1203
+
1204
+ const first = await requestPrivateConsolidation(ctx, id, { force: true })
1205
+ assert.equal(first.ok, false)
1206
+ assert.equal(first.reasonCode, 'fork-turn-failed')
1207
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, undefined)
1208
+ assert.equal(isEffortRefused(key), true)
1209
+ assert.deepEqual(ctx.rec.created[0].agentOptions, parentOptions)
1210
+ assert.ok(ctx.rec.disposed.includes(first.childId), 'the failed child was retired')
1211
+ assert.equal(state.getSessionBinding(first.childId), null, 'the failed child binding was removed')
1212
+ if (runner === 'worker') assert.equal(state.getSessionBinding(id).workerEpoch ?? null, null)
1213
+ if (mode === 'custom') assert.equal(startedEntryFor(ctx, id).detail.modelMode, 'inherit-fallback')
1214
+
1215
+ const second = await requestPrivateConsolidation(ctx, id)
1216
+ assert.equal(second.skipped, undefined, 'the automatic retry is not frozen')
1217
+ assert.equal(second.ok, true, second.error || '')
1218
+ assert.equal(second.settled, true, 'the parameter-dependent host completed and its receipt settled')
1219
+ assert.equal(state.getSessionBinding(id).lastSleepSeq, 2)
1220
+ assert.equal(ctx.rec.created.length, 2, 'retry really creates a fresh child')
1221
+ assert.notEqual(second.childId, first.childId)
1222
+ const secondOptions = ctx.rec.created[1].agentOptions
1223
+ assert.equal(Object.hasOwn(secondOptions, 'reasoningEffort'), false)
1224
+ assert.deepEqual(secondOptions, { provider: id, model: 'test-model', maxTokens: 32768 })
1225
+ assert.equal(ctx.get('agents').get(id).options, parentOptions, 'the parent object is not replaced')
1226
+ assert.equal(parentOptions.reasoningEffort, 'medium', 'the parent effort is untouched')
1227
+ assert.equal(ctx.permissionPresets.set.mock.callCount(), 0, 'no automatic permission elevation')
1228
+ })
1229
+ }
1230
+ }
1231
+
1232
+ test(`${runner} applies an allowed explicit effort after custom fallback and checks only the effective route`, async (t) => {
1233
+ const id = `effort-override-${runner}`
1234
+ const parentOptions = Object.freeze({ provider: id, model: 'model', reasoningEffort: 'medium', maxTokens: 4096 })
1235
+ const ctx = host({ live: true, parentOptions, turnReason: rejectMedium })
1236
+ cleanupEffortHost(t, ctx, id)
1237
+ state.updateSettings({ ...CUSTOM, consolidationRunner: runner, consolidationReasoningEffort: 'high' })
1238
+ state.ensureSession(id, { cwd: home, agentPreset: 'coding' })
1239
+ markEffortRefused(`${id}|model|medium`)
1240
+ markEffortRefused('dsh-memu-custom|gateway-model|high')
1241
+ const result = await requestPrivateConsolidation(ctx, id, { force: true })
1242
+ assert.equal(result.ok, true, result.error || '')
1243
+ assert.equal(result.settled, true)
1244
+ assert.equal(startedEntryFor(ctx, id).detail.modelMode, 'inherit-fallback')
1245
+ assert.deepEqual(ctx.rec.created[0].agentOptions, { ...parentOptions, reasoningEffort: 'high' })
1246
+ assert.equal(parentOptions.reasoningEffort, 'medium')
1247
+ })
1248
+ }
1249
+
1250
+ test('a fresh worker shares the refusal learned by a fork', async (t) => {
1251
+ const parentOptions = Object.freeze({ provider: 'shared-effort', model: 'model', reasoningEffort: 'medium', maxTokens: 8192 })
1252
+ const ctx = host({ live: true, parentOptions, turnReason: rejectMedium })
1253
+ cleanupEffortHost(t, ctx, 'effort-shared-worker')
1254
+ state.updateSettings({ consolidationRunner: 'fork', consolidationReasoningEffort: 'inherit' })
1255
+ state.ensureSession('effort-shared-fork', { cwd: home, agentPreset: 'coding' })
1256
+ const failed = await requestPrivateConsolidation(ctx, 'effort-shared-fork', { force: true })
1257
+ assert.equal(failed.reasonCode, 'fork-turn-failed')
1258
+ state.updateSettings({ consolidationRunner: 'worker' })
1259
+ state.ensureSession('effort-shared-worker', { cwd: home, agentPreset: 'coding' })
1260
+ const result = await requestPrivateConsolidation(ctx, 'effort-shared-worker', { force: true })
1261
+ assert.equal(result.ok, true, result.error || '')
1262
+ assert.equal(result.settled, true)
1263
+ assert.match(result.childId, /^memu-worker-/)
1264
+ assert.deepEqual(ctx.rec.created[1].agentOptions, { provider: 'shared-effort', model: 'model', maxTokens: 8192 })
1265
+ assert.equal(parentOptions.reasoningEffort, 'medium')
1266
+ })
1267
+
1268
+ // 2026-11-18:学习表持久化。反代服务商签名各异(raccoon/sn-deepseek-v4-1-flash-1017
1269
+ // 拒 medium 实测),表只在内存时每次重启后的第一次整理都要再吃一次 fork-turn-failed。
1270
+ test('a learned effort refusal survives a restart — it is persisted to the data dir', async (t) => {
929
1271
  state.updateSettings({ consolidationReasoningEffort: 'medium' })
930
- state.ensureSession('fork-effort-refusal', { cwd: path.join(home, 'proj-effort'), agentPreset: 'coding' })
931
- const failureMessage = 'provider "test-provider" model "test-model" does not support reasoning effort "medium"'
932
- assert.equal(effortRefusalOf(failureMessage).key, 'test-provider|test-model|medium')
933
- assert.equal(isEffortRefused('test-provider|test-model|medium'), false, 'not learned before the first failure')
934
- const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: failureMessage } } })
935
- const first = await requestPrivateConsolidation(ctx, 'fork-effort-refusal', { force: true })
1272
+ state.ensureSession('fork-effort-persist', { cwd: path.join(home, 'proj-effort-persist'), agentPreset: 'coding' })
1273
+ const ctx = host({ live: true, parentOptions: { provider: 'persist-provider', model: 'persist-model' }, turnReason: rejectMedium })
1274
+ cleanupEffortHost(t, ctx, 'fork-effort-persist')
1275
+ const first = await requestPrivateConsolidation(ctx, 'fork-effort-persist', { force: true })
936
1276
  assert.equal(first.ok, false)
937
1277
  assert.equal(first.reasonCode, 'fork-turn-failed')
938
- assert.equal(isEffortRefused('test-provider|test-model|medium'), true, 'the refusal is learned from the failure')
939
- const second = await requestPrivateConsolidation(ctx, 'fork-effort-refusal')
940
- assert.equal(second.skipped, undefined, 'the retry gate was reset — the automatic path forks again')
941
- const secondSpec = ctx.rec.created[1]
942
- assert.ok(secondSpec, 'the second attempt forks again')
943
- assert.equal(secondSpec.agentOptions?.reasoningEffort, undefined, 'the learned refusal drops the effort from the fork options')
944
- state.updateSettings({ consolidationReasoningEffort: 'inherit' })
1278
+
1279
+ const persisted = JSON.parse(fs.readFileSync(path.join(dataDir(), 'effort-refusals.json'), 'utf8'))
1280
+ assert.ok(persisted.keys.includes('persist-provider|persist-model|medium'), 'the refusal was written to the data dir')
1281
+ const child = effortChild(t, home, `assert.equal(api.isEffortRefused('persist-provider|persist-model|medium'), true)`)
1282
+ await child.ready
1283
+ child.release()
1284
+ await child.done
1285
+ })
1286
+
1287
+ // 子进程只加载测试 loader + private.js,home/cwd 全部指向临时目录。
1288
+ // IPC 屏障保证并发用例里的两个进程先各自读完旧表,再同时开始 mark。
1289
+ function effortChild(t, dir, before, after = '') {
1290
+ const code = `
1291
+ import assert from 'node:assert/strict'
1292
+ const api = await import(${JSON.stringify(new URL('../lib/private.js', import.meta.url).href)})
1293
+ ${before}
1294
+ const released = new Promise(resolve => process.once('message', resolve))
1295
+ process.send('loaded')
1296
+ await released
1297
+ ${after}
1298
+ process.disconnect()
1299
+ `
1300
+ const child = spawn(process.execPath, ['--import', new URL('./loader-register.mjs', import.meta.url).href, '--input-type=module', '-e', code], {
1301
+ cwd: dir, windowsHide: true, timeout: 20_000,
1302
+ env: { ...process.env, DSH_HOME: dir, DSH_MEMU_HOME: dir, DSH_MEMU_MEMORY_HOME: dir },
1303
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
1304
+ })
1305
+ let errors = ''
1306
+ child.stdout.on('data', data => { errors += data })
1307
+ child.stderr.on('data', data => { errors += data })
1308
+ const ready = new Promise((resolve, reject) => {
1309
+ child.on('message', message => { if (message === 'loaded') resolve() })
1310
+ child.on('error', reject)
1311
+ child.on('close', () => reject(new Error('child exited before barrier: ' + errors)))
1312
+ })
1313
+ const done = new Promise((resolve, reject) => {
1314
+ child.on('error', reject)
1315
+ child.on('close', code => code === 0 ? resolve() : reject(new Error('effort child failed: ' + errors)))
1316
+ })
1317
+ // 在等待另一个进程抵达屏障时也接住早退;原 promise 仍供断言 await。
1318
+ ready.catch(() => {})
1319
+ done.catch(() => {})
1320
+ t.after(() => { if (child.exitCode === null) child.kill() })
1321
+ return { ready, done, release: () => child.send('mark') }
1322
+ }
1323
+
1324
+ function refusalStore(t) {
1325
+ state.flushState()
1326
+ const dir = fs.mkdtempSync(path.join(home, 'effort-store-'))
1327
+ const previous = [process.env.DSH_MEMU_HOME, process.env.DSH_MEMU_MEMORY_HOME]
1328
+ process.env.DSH_MEMU_HOME = process.env.DSH_MEMU_MEMORY_HOME = dir
1329
+ const warnings = []
1330
+ setWarnSink(message => warnings.push(message))
1331
+ t.after(() => {
1332
+ ;[process.env.DSH_MEMU_HOME, process.env.DSH_MEMU_MEMORY_HOME] = previous
1333
+ setWarnSink(null)
1334
+ })
1335
+ return { dir, file: path.join(dir, 'effort-refusals.json'), warnings }
1336
+ }
1337
+
1338
+ function seedRefusals(file, keys) {
1339
+ const raw = JSON.stringify({ version: 1, keys })
1340
+ fs.writeFileSync(file, raw)
1341
+ return raw
1342
+ }
1343
+
1344
+ function refusalKeys(file) {
1345
+ return JSON.parse(fs.readFileSync(file, 'utf8')).keys.sort()
1346
+ }
1347
+
1348
+ test('refusals load lazily once and clean queries/duplicate marks perform no file IO', async (t) => {
1349
+ const { file } = refusalStore(t)
1350
+ seedRefusals(file, ['initial|model|medium'])
1351
+ const read = t.mock.method(fs, 'readFileSync')
1352
+ const write = t.mock.method(fs, 'writeFileSync')
1353
+ const fresh = await import('../lib/private.js?effort-lazy')
1354
+ const tableReads = () => read.mock.calls.filter(call => call.arguments[0] === file).length
1355
+ assert.equal(tableReads(), 0, 'import does not capture or read a home')
1356
+ assert.equal(fresh.isEffortRefused('initial|model|medium'), true)
1357
+ assert.equal(tableReads(), 1)
1358
+ for (let i = 0; i < 20; i++) {
1359
+ assert.equal(fresh.isEffortRefused('initial|model|medium'), true)
1360
+ assert.equal(fresh.isEffortRefused('unknown|model|medium'), false)
1361
+ fresh.markEffortRefused('initial|model|medium')
1362
+ }
1363
+ assert.equal(tableReads(), 1, 'a clean cache never rescans the table')
1364
+ assert.equal(write.mock.callCount(), 0, 'queries and duplicate clean marks never rewrite the table')
1365
+ })
1366
+
1367
+ test('a failed initial read never replaces old keys and retries after IO recovers', (t) => {
1368
+ const { file, warnings } = refusalStore(t)
1369
+ const original = seedRefusals(file, ['old|model|medium'])
1370
+ const read = fs.readFileSync
1371
+ let failing = true
1372
+ t.mock.method(fs, 'readFileSync', function (target, ...args) {
1373
+ if (target === file && failing) throw Object.assign(new Error('read failed api_key=secret123456789'), { code: 'EIO' })
1374
+ return read.call(this, target, ...args)
1375
+ })
1376
+ assert.equal(isEffortRefused('old|model|medium'), false, 'an unreadable key is not yet known')
1377
+ markEffortRefused('new|model|medium')
1378
+ assert.equal(isEffortRefused('new|model|medium'), true, 'new knowledge survives the failed read')
1379
+ assert.equal(read(file, 'utf8'), original, 'read failure cannot be saved back as an empty table')
1380
+ assert.ok(warnings.length > 0)
1381
+ assert.ok(warnings.every(message => !message.includes('secret123456789')), 'warnings use the existing redaction sink')
1382
+ failing = false
1383
+ assert.equal(isEffortRefused('old|model|medium'), true, 'the query retries the pending merge')
1384
+ assert.deepEqual(refusalKeys(file), ['new|model|medium', 'old|model|medium'])
1385
+ })
1386
+
1387
+ for (const retry of ['same-key mark', 'query']) {
1388
+ test(`an atomic write failure keeps pending keys and recovers on ${retry}`, (t) => {
1389
+ const { dir, file, warnings } = refusalStore(t)
1390
+ const original = seedRefusals(file, ['old|model|medium'])
1391
+ assert.equal(isEffortRefused('old|model|medium'), true)
1392
+ const rename = fs.renameSync
1393
+ let failing = true
1394
+ t.mock.method(fs, 'renameSync', function (from, to) {
1395
+ if (to === file && failing) throw Object.assign(new Error('injected rename failure'), { code: 'EIO' })
1396
+ return rename.call(this, from, to)
1397
+ })
1398
+ markEffortRefused('new|model|medium')
1399
+ assert.equal(isEffortRefused('new|model|medium'), true)
1400
+ assert.equal(fs.readFileSync(file, 'utf8'), original, 'failed atomic replace preserves the previous bytes')
1401
+ assert.deepEqual(fs.readdirSync(dir), ['effort-refusals.json'], 'temporary files and locks are cleaned')
1402
+ assert.ok(warnings.some(message => message.includes('injected rename failure')))
1403
+ failing = false
1404
+ if (retry === 'same-key mark') markEffortRefused('new|model|medium')
1405
+ else assert.equal(isEffortRefused('old|model|medium'), true, 'even an unrelated lookup flushes pending knowledge')
1406
+ assert.deepEqual(refusalKeys(file), ['new|model|medium', 'old|model|medium'])
1407
+ const reads = t.mock.method(fs, 'readFileSync')
1408
+ const writes = t.mock.method(fs, 'writeFileSync')
1409
+ isEffortRefused('new|model|medium')
1410
+ markEffortRefused('new|model|medium')
1411
+ assert.equal(reads.mock.callCount(), 0, 'successful recovery clears the pending state')
1412
+ assert.equal(writes.mock.callCount(), 0)
1413
+ })
1414
+ }
1415
+
1416
+ for (const [label, raw] of [
1417
+ ['broken JSON', '{"version":1,"keys":['],
1418
+ ['invalid keys', JSON.stringify({ version: 1, keys: [123] })],
1419
+ ['unknown schema', JSON.stringify({ version: 2, keys: [] })],
1420
+ ]) {
1421
+ test(`${label} is never overwritten, and pending knowledge merges after repair`, (t) => {
1422
+ const { file, warnings } = refusalStore(t)
1423
+ fs.writeFileSync(file, raw)
1424
+ assert.equal(isEffortRefused('pending|model|medium'), false)
1425
+ markEffortRefused('pending|model|medium')
1426
+ assert.equal(isEffortRefused('pending|model|medium'), true)
1427
+ assert.equal(fs.readFileSync(file, 'utf8'), raw)
1428
+ assert.ok(warnings.length > 0)
1429
+ seedRefusals(file, ['restored|model|high'])
1430
+ assert.equal(isEffortRefused('restored|model|high'), true)
1431
+ assert.deepEqual(refusalKeys(file), ['pending|model|medium', 'restored|model|high'])
1432
+ })
1433
+ }
1434
+
1435
+ test('refusal caches and writes follow the current home without leaking keys', (t) => {
1436
+ const { file: firstFile } = refusalStore(t)
1437
+ assert.equal(isEffortRefused('first|model|medium'), false, 'ENOENT starts an empty table')
1438
+ markEffortRefused('first|model|medium')
1439
+ const secondDir = fs.mkdtempSync(path.join(home, 'effort-other-'))
1440
+ const secondFile = path.join(secondDir, 'effort-refusals.json')
1441
+ seedRefusals(secondFile, ['second|model|high'])
1442
+ process.env.DSH_MEMU_HOME = process.env.DSH_MEMU_MEMORY_HOME = secondDir
1443
+ assert.equal(isEffortRefused('first|model|medium'), false)
1444
+ assert.equal(isEffortRefused('second|model|high'), true)
1445
+ markEffortRefused('second|model|medium')
1446
+ process.env.DSH_MEMU_HOME = process.env.DSH_MEMU_MEMORY_HOME = path.dirname(firstFile)
1447
+ assert.equal(isEffortRefused('first|model|medium'), true)
1448
+ assert.equal(isEffortRefused('second|model|medium'), false)
1449
+ assert.deepEqual(refusalKeys(firstFile), ['first|model|medium'])
1450
+ assert.deepEqual(refusalKeys(secondFile), ['second|model|high', 'second|model|medium'])
1451
+ })
1452
+
1453
+ test('two processes merge stale refusal snapshots under the file lock', async (t) => {
1454
+ const { dir, file } = refusalStore(t)
1455
+ seedRefusals(file, ['old|model|medium'])
1456
+ const children = ['left', 'right'].map(name => effortChild(t, dir,
1457
+ `assert.equal(api.isEffortRefused('old|model|medium'), true)`,
1458
+ `api.markEffortRefused('${name}|model|medium'); assert.equal(api.isEffortRefused('${name}|model|medium'), true)`,
1459
+ ))
1460
+ await Promise.all(children.map(child => child.ready))
1461
+ for (const child of children) child.release()
1462
+ await Promise.all(children.map(child => child.done))
1463
+ assert.deepEqual(refusalKeys(file), ['left|model|medium', 'old|model|medium', 'right|model|medium'])
1464
+ })
1465
+
1466
+ test('missing buildForkSeed only disables fork; worker really completes without loading the seed API', async (t) => {
1467
+ const dir = fs.mkdtempSync(path.join(home, 'missing-seed-'))
1468
+ const before = `
1469
+ const { registerHooks } = await import('node:module')
1470
+ let seedImports = 0
1471
+ const hooks = registerHooks({ resolve(specifier, context, next) {
1472
+ if (specifier === '@deepseek-ai/dsh-session') {
1473
+ seedImports++
1474
+ return { url: 'data:text/javascript,export const unavailable = true', shortCircuit: true }
1475
+ }
1476
+ return next(specifier, context)
1477
+ } })
1478
+ const state = await import(${JSON.stringify(new URL('../lib/state.js', import.meta.url).href)})
1479
+ const home = ${JSON.stringify(dir)}
1480
+ const META_KEYS = ${JSON.stringify(META_KEYS)}
1481
+ const assertHostCreateAccepts = ${assertHostCreateAccepts.toString()}
1482
+ const host = ${host.toString()}
1483
+ const ctx = host({ live: true, cwd: home })
1484
+ state.ensureSession('missing-seed-fork', { cwd: home, agentPreset: 'coding' })
1485
+ state.updateSettings({ consolidationRunner: 'fork', consolidationReasoningEffort: 'inherit' })
1486
+ const fork = await api.requestPrivateConsolidation(ctx, 'missing-seed-fork', { force: true })
1487
+ assert.equal(fork.reasonCode, 'no-fork-seed')
1488
+ assert.equal(fork.settled, false)
1489
+ assert.equal(ctx.rec.created.length, 0)
1490
+ const afterFork = seedImports
1491
+ state.ensureSession('missing-seed-worker', { cwd: home, agentPreset: 'coding' })
1492
+ state.updateSettings({ consolidationRunner: 'worker' })
1493
+ const worker = await api.requestPrivateConsolidation(ctx, 'missing-seed-worker', { force: true })
1494
+ assert.equal(worker.ok, true, worker.error || '')
1495
+ assert.equal(worker.settled, true)
1496
+ assert.equal(ctx.rec.created.length, 1)
1497
+ assert.equal(ctx.rec.created[0].seed, undefined)
1498
+ assert.equal(state.getSessionBinding('missing-seed-worker').lastSleepSeq, 2)
1499
+ assert.equal(seedImports, afterFork, 'worker never imports the missing seed API')
1500
+ hooks.deregister()
1501
+ `
1502
+ const child = effortChild(t, dir, before)
1503
+ await child.ready
1504
+ child.release()
1505
+ await child.done
945
1506
  })