dsh-dev-plan-presets 0.0.0-stage → 0.4.0

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.
@@ -0,0 +1,1912 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { readFileSync } from 'node:fs'
4
+ import { dirname, join } from 'node:path'
5
+ import { fileURLToPath, pathToFileURL } from 'node:url'
6
+ import {
7
+ callRoute,
8
+ createFakeAgent,
9
+ createFakeConfigEditor,
10
+ createFakeContext,
11
+ createFakeRegistry,
12
+ createFakeWebServer,
13
+ loadModules,
14
+ } from '../scripts/test-harness.mjs'
15
+
16
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
17
+ const { settings: S, preset: P, index, guard } = await loadModules(ROOT)
18
+
19
+ const base = () => ({ ...S.DEFAULT_SETTINGS })
20
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
21
+
22
+ async function loadClientTestApi() {
23
+ const previousWindow = globalThis.window
24
+ const previousFlag = globalThis.__DSH_DEV_PLAN_PRESETS_TEST__
25
+ const captured = { module: null }
26
+ globalThis.window = {
27
+ __ModuleLoader__: {
28
+ load(module) {
29
+ captured.module = module
30
+ },
31
+ },
32
+ }
33
+ globalThis.__DSH_DEV_PLAN_PRESETS_TEST__ = true
34
+ try {
35
+ const url =
36
+ pathToFileURL(join(ROOT, 'client.js')).href +
37
+ '?client-test=' +
38
+ Date.now() +
39
+ Math.random().toString(36).slice(2)
40
+ await import(url)
41
+ assert.ok(captured.module, 'client.js 没有调用 __ModuleLoader__.load')
42
+ const fakeReact = {
43
+ createElement: (...args) => ({ args }),
44
+ useState: (initial) => [initial, () => {}],
45
+ useEffect: () => {},
46
+ useRef: (initial) => ({ current: initial }),
47
+ useCallback: (fn) => fn,
48
+ useMemo: (fn) => fn(),
49
+ cloneElement: (element) => element,
50
+ Fragment: 'Fragment',
51
+ }
52
+ const api = captured.module.factory(() => fakeReact)
53
+ assert.ok(api.__test, 'client 没有暴露测试用纯选择函数')
54
+ return api.__test
55
+ } finally {
56
+ globalThis.window = previousWindow
57
+ globalThis.__DSH_DEV_PLAN_PRESETS_TEST__ = previousFlag
58
+ }
59
+ }
60
+
61
+ test('默认设置:standard + ask-edit + pin,零 deep-ptc 依赖', () => {
62
+ const value = S.normalizeSettings(undefined)
63
+ assert.equal(value.developMode, 'standard')
64
+ assert.equal(value.modelGuardMode, 'pin')
65
+ assert.equal(value.killOnViolation, true)
66
+ assert.equal(value.honorExplicit, false)
67
+ assert.equal(value.audit, true)
68
+ assert.equal(value.guardAllSubagents, false)
69
+ assert.equal(value.mainToolMode, 'ask-edit')
70
+ assert.equal(value.mainStepWarnThreshold, 6)
71
+ assert.equal(value.childProvider, 'dsh-opencode-go')
72
+ assert.equal(value.childModel, 'deepseek-v4.1-flash')
73
+ assert.equal(value.childReasoningEffort, '')
74
+ assert.deepEqual(S.routeOf(value), { provider: 'dsh-opencode-go', model: 'deepseek-v4.1-flash' })
75
+ })
76
+
77
+ test('Config 严格校验:默认值通过,非法枚举/空路由被拒绝', () => {
78
+ const ok = S.Config['~standard'].validate({})
79
+ assert.deepEqual(ok.value, base())
80
+ // 任意非空 preset id 都合法;只有空值被拒绝。
81
+ const customMode = S.Config['~standard'].validate({ developMode: 'my-preset' })
82
+ assert.equal(customMode.value.developMode, 'my-preset')
83
+ const emptyMode = S.Config['~standard'].validate({ developMode: ' ' })
84
+ assert.ok(emptyMode.issues.some((issue) => issue.path[0] === 'developMode'))
85
+ const badGuardAll = S.Config['~standard'].validate({ guardAllSubagents: 'yes' })
86
+ assert.ok(badGuardAll.issues.some((issue) => issue.path[0] === 'guardAllSubagents'))
87
+ const goodGuardAll = S.Config['~standard'].validate({ guardAllSubagents: true })
88
+ assert.equal(goodGuardAll.value.guardAllSubagents, true)
89
+ const badGuard = S.Config['~standard'].validate({ modelGuardMode: 'kill' })
90
+ assert.ok(badGuard.issues.some((issue) => issue.path[0] === 'modelGuardMode'))
91
+ const badRoute = S.Config['~standard'].validate({ childProvider: ' ' })
92
+ assert.ok(badRoute.issues.some((issue) => issue.path[0] === 'childProvider'))
93
+ const badEffort = S.Config['~standard'].validate({ childReasoningEffort: 1 })
94
+ assert.ok(badEffort.issues.some((issue) => issue.path[0] === 'childReasoningEffort'))
95
+ })
96
+
97
+ test('standard 定义(mainToolMode=none):四个委派工具、develop=standard、主窗无施工工具', () => {
98
+ const definition = P.buildPresetDefinition({
99
+ settings: { ...base(), mainToolMode: 'none' },
100
+ mode: P.resolveDevelopMode({ requestedMode: 'standard' }),
101
+ })
102
+ assert.equal(definition.id, 'dev-plan')
103
+ assert.equal(definition.name, '开发规划与交付')
104
+ assert.equal(P.PRESET_NAME, '开发规划与交付')
105
+ assert.equal(definition.order, 10)
106
+
107
+ const rows = []
108
+ const walk = (plugins) => {
109
+ for (const row of plugins ?? []) {
110
+ rows.push(row)
111
+ if (Array.isArray(row?.config)) walk(row.config)
112
+ }
113
+ }
114
+ walk(definition.plugins)
115
+ for (const forbidden of P.FORBIDDEN_MAIN_PLUGINS) {
116
+ assert.ok(!rows.some((row) => row?.name === forbidden), `主窗不应挂 ${forbidden}`)
117
+ }
118
+ const subagents = rows.filter((row) => row?.name === '@deepseek-ai/dsh-tool-subagent')
119
+ assert.equal(subagents.length, 4)
120
+ assert.deepEqual(
121
+ subagents.map((row) => row.config.toolName).sort(),
122
+ ['develop', 'recon', 'review', 'scribe'],
123
+ )
124
+ for (const row of subagents) {
125
+ const cfg = row.config
126
+ assert.equal(cfg.provider, 'spawn')
127
+ assert.equal(cfg.maxDepth, 1)
128
+ assert.equal(cfg.modelSelection, false)
129
+ assert.equal(cfg.modelDiscovery, false)
130
+ assert.equal(cfg.allowedAgentPresets, undefined)
131
+ assert.deepEqual(cfg.agentOptions, { provider: 'dsh-opencode-go', model: 'deepseek-v4.1-flash' })
132
+ assert.equal(cfg.agentPreset, 'standard')
133
+ }
134
+ assert.equal(subagents.find((row) => row.config.toolName === 'develop').config.agentPreset, 'standard')
135
+ })
136
+
137
+ test('deep-ptc 定义:只有 develop 切到 deep-ptc,其余仍是 standard', () => {
138
+ const mode = P.resolveDevelopMode({
139
+ requestedMode: 'deep-ptc',
140
+ presets: [{ id: 'deep-ptc', name: '深度 PTC' }],
141
+ catalogChecked: true,
142
+ })
143
+ const definition = P.buildPresetDefinition({ settings: base(), mode })
144
+ const rows = []
145
+ const walk = (plugins) => {
146
+ for (const row of plugins ?? []) {
147
+ rows.push(row)
148
+ if (Array.isArray(row?.config)) walk(row.config)
149
+ }
150
+ }
151
+ walk(definition.plugins)
152
+ const byName = Object.fromEntries(
153
+ rows
154
+ .filter((row) => row?.name === '@deepseek-ai/dsh-tool-subagent')
155
+ .map((row) => [row.config.toolName, row.config.agentPreset]),
156
+ )
157
+ assert.deepEqual(byName, {
158
+ recon: 'standard',
159
+ review: 'standard',
160
+ scribe: 'standard',
161
+ develop: 'deep-ptc',
162
+ })
163
+ assert.match(definition.description, /deep-ptc/)
164
+ })
165
+
166
+ test('回退显式可见:standard + 原因,写进 description 与 persona', () => {
167
+ const mode = P.resolveDevelopMode({ requestedMode: 'deep-ptc', presets: [], catalogChecked: true })
168
+ assert.equal(mode.effective, 'standard')
169
+ assert.equal(mode.fallback, true)
170
+ assert.match(mode.reason, /没有可用的施工方式|未安装|未启用|已被移除/)
171
+ const definition = P.buildPresetDefinition({ settings: base(), mode })
172
+ assert.match(definition.description, /已回退 standard/)
173
+ const persona = definition.plugins.find((row) => row.id === 'persona').config.prefix
174
+ assert.match(persona, /已回退 standard/)
175
+ assert.match(persona, /回退显式可见/)
176
+ })
177
+
178
+ test('deep-ptc 已注册但激活失败也回退', () => {
179
+ const mode = P.resolveDevelopMode({
180
+ requestedMode: 'deep-ptc',
181
+ presets: [{ id: 'deep-ptc', broken: 'row 3 failed to import' }],
182
+ catalogChecked: true,
183
+ })
184
+ assert.equal(mode.effective, 'standard')
185
+ assert.equal(mode.fallback, true)
186
+ assert.match(mode.reason, /加载失败/)
187
+ })
188
+
189
+ test('apply 动态注册 preset,并在 dispose 时交还 disposer', async () => {
190
+ const registry = createFakeRegistry()
191
+ const ctx = createFakeContext({ registry })
192
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
193
+ await ctx.flush()
194
+ assert.deepEqual(
195
+ registry.definitions.map((d) => d.id),
196
+ ['dev-plan'],
197
+ )
198
+ await ctx.dispose()
199
+ assert.deepEqual(registry.released, ['dev-plan'])
200
+ })
201
+
202
+ test('state 路由:默认 standard、preset 描述可用', async () => {
203
+ const registry = createFakeRegistry()
204
+ const webServer = createFakeWebServer()
205
+ const ctx = createFakeContext({ registry, webServer })
206
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
207
+ await ctx.flush()
208
+ const handler = webServer.handlers.get('/plugins/dev-plan-presets/state')
209
+ assert.equal(typeof handler, 'function')
210
+ const response = await callRoute(handler, 'GET')
211
+ assert.equal(response.code, 200)
212
+ assert.equal(response.body.version, '0.4.0')
213
+ assert.ok(Number.isInteger(response.body.stateVersion) && response.body.stateVersion >= 1)
214
+ assert.ok(typeof response.headers.etag === 'string' && response.headers.etag.length > 0)
215
+ assert.equal(response.body.effectiveMode, 'standard')
216
+ assert.equal(response.body.fallback.active, false)
217
+ assert.equal(response.body.preset.id, 'dev-plan')
218
+ assert.equal(response.body.config.guardAllSubagents, false)
219
+ assert.equal(response.body.config.mainToolMode, 'ask-edit')
220
+ assert.equal(response.body.config.mainStepWarnThreshold, 6)
221
+ assert.equal(response.body.presets.selfId, 'dev-plan')
222
+ assert.deepEqual(response.body.presets.disabledIds, ['dev-plan', 'dev-plan-scout', 'dev-plan-scribe'])
223
+ assert.deepEqual(response.body.internalPresets, { scout: false, scribe: false })
224
+ assert.match(response.body.preset.description, /standard/)
225
+ await ctx.dispose()
226
+ })
227
+
228
+ test('state 路由:请求 deep-ptc 但宿主没有时显式回退', async () => {
229
+ const registry = createFakeRegistry()
230
+ const webServer = createFakeWebServer()
231
+ const ctx = createFakeContext({ registry, webServer })
232
+ index.apply(ctx.ctx, { ...base(), developMode: 'deep-ptc' }, { verificationDelayMs: 0 })
233
+ await ctx.flush()
234
+ const handler = webServer.handlers.get('/plugins/dev-plan-presets/state')
235
+ const response = await callRoute(handler, 'GET')
236
+ assert.equal(response.body.effectiveMode, 'standard')
237
+ assert.equal(response.body.fallback.active, true)
238
+ assert.match(response.body.fallback.reason, /没有可用的施工方式|未安装|未启用|已被移除/)
239
+ assert.equal(response.body.presets.checked, true)
240
+ assert.deepEqual(response.body.presets.rows, [])
241
+ assert.match(response.body.preset.description, /已回退 standard/)
242
+ assert.ok(ctx.loggerCalls.warn.some((line) => line.includes('已回退 standard')))
243
+ const mainDef = registry.definitions.find((d) => d.id === 'dev-plan')
244
+ assert.equal(mainDef.plugins.at(-1).config.agentPreset, 'standard')
245
+ await ctx.dispose()
246
+ })
247
+
248
+ test('registry 中实际存在 deep-ptc 时,develop 使用 deep-ptc', async () => {
249
+ const registry = createFakeRegistry({ rows: [{ id: 'deep-ptc' }] })
250
+ const ctx = createFakeContext({
251
+ registry,
252
+ entries: [{ id: 'deep-ptc-settings', options: { name: 'dsh-deep-ptc-mode' }, fiber: { state: 1 } }],
253
+ })
254
+ index.apply(ctx.ctx, { ...base(), developMode: 'deep-ptc' }, { verificationDelayMs: 0 })
255
+ await ctx.flush()
256
+ const definition = registry.definitions.find((d) => d.id === 'dev-plan')
257
+ const develop = definition.plugins.find((row) => row.id === 'tool-subagent-develop')
258
+ assert.equal(develop.config.agentPreset, 'deep-ptc')
259
+ assert.equal(definition.plugins.find((row) => row.id === 'tool-subagent-recon').config.agentPreset, 'standard')
260
+ assert.equal(definition.plugins.find((row) => row.id === 'tool-subagent-scribe').config.agentPreset, 'standard')
261
+ await ctx.dispose()
262
+ })
263
+
264
+ test('目录中没有目标 preset 时回退,不把 loader entry 当可用证据', async () => {
265
+ const registry = createFakeRegistry({ rows: [] })
266
+ const webServer = createFakeWebServer()
267
+ const ctx = createFakeContext({
268
+ registry,
269
+ webServer,
270
+ // LOADING:深度 PTC 已安装并开始加载,但 preset 还没注册,不能据 entry 推断可用。
271
+ entries: [{ id: 'deep-ptc-settings', options: { name: 'dsh-deep-ptc-mode' }, fiber: { state: 1 } }],
272
+ })
273
+ index.apply(ctx.ctx, { ...base(), developMode: 'deep-ptc' }, { verificationDelayMs: 0 })
274
+ await ctx.flush()
275
+ const definition = registry.definitions.find((d) => d.id === 'dev-plan')
276
+ assert.equal(definition.plugins.find((row) => row.id === 'tool-subagent-develop').config.agentPreset, 'standard')
277
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
278
+ assert.equal(state.body.effectiveMode, 'standard')
279
+ assert.equal(state.body.fallback.active, true)
280
+ assert.match(state.body.fallback.reason, /没有可用的施工方式|未安装|未启用|已被移除/)
281
+ assert.match(state.body.preset.description, /已回退 standard/)
282
+ await ctx.dispose()
283
+ })
284
+
285
+ test('延迟复检可以在 registry 出现 deep-ptc 后把 develop 从 standard 提升到 deep-ptc', async () => {
286
+ const registry = createFakeRegistry({ rows: [] })
287
+ let listCalls = 0
288
+ // 第一次探测时 registry 还没有 deep-ptc;延迟复检时已注册。
289
+ registry.list = async () => {
290
+ listCalls += 1
291
+ return listCalls === 1 ? [] : [{ id: 'deep-ptc' }]
292
+ }
293
+ const webServer = createFakeWebServer()
294
+ const ctx = createFakeContext({
295
+ registry,
296
+ webServer,
297
+ entries: [{ id: 'deep-ptc-settings', options: { name: 'dsh-deep-ptc-mode' }, fiber: { state: 1 } }],
298
+ })
299
+ index.apply(ctx.ctx, { ...base(), developMode: 'deep-ptc' }, { verificationDelayMs: 300 })
300
+ await ctx.flush()
301
+ const initialMains = registry.definitions.filter((d) => d.id === 'dev-plan')
302
+ assert.equal(initialMains.length, 1)
303
+ assert.equal(
304
+ initialMains[0].plugins.find((row) => row.id === 'tool-subagent-develop').config.agentPreset,
305
+ 'standard',
306
+ )
307
+
308
+ // 深度 PTC 完成动态注册后,下一次延迟复检应释放旧定义并注册 deep-ptc 版本。
309
+ await sleep(600)
310
+ await ctx.flush()
311
+ const updatedMains = registry.definitions.filter((d) => d.id === 'dev-plan')
312
+ assert.ok(updatedMains.length >= 2)
313
+ const latest = updatedMains.at(-1)
314
+ assert.equal(latest.plugins.find((row) => row.id === 'tool-subagent-develop').config.agentPreset, 'deep-ptc')
315
+ assert.equal(latest.plugins.find((row) => row.id === 'tool-subagent-recon').config.agentPreset, 'standard')
316
+ assert.ok(registry.released.includes('dev-plan'))
317
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
318
+ assert.equal(state.body.effectiveMode, 'deep-ptc')
319
+ assert.equal(state.body.fallback.active, false)
320
+ await ctx.dispose()
321
+ })
322
+
323
+ test('同 effective/fallback 但回退原因变化时,重新发布 preset 描述', async () => {
324
+ const registry = createFakeRegistry({ rows: [] })
325
+ let listCalls = 0
326
+ registry.list = async () => {
327
+ listCalls += 1
328
+ return [{ id: 'deep-ptc', broken: listCalls === 1 ? 'first failure' : 'second failure' }]
329
+ }
330
+ const webServer = createFakeWebServer()
331
+ const ctx = createFakeContext({ registry, webServer })
332
+ index.apply(ctx.ctx, { ...base(), developMode: 'deep-ptc' }, { verificationDelayMs: 300 })
333
+ await ctx.flush()
334
+ const firstMains = registry.definitions.filter((d) => d.id === 'dev-plan')
335
+ assert.equal(firstMains.length, 1)
336
+ assert.match(firstMains[0].description, /first failure/)
337
+
338
+ await sleep(600)
339
+ await ctx.flush()
340
+ const updatedMains = registry.definitions.filter((d) => d.id === 'dev-plan')
341
+ assert.ok(updatedMains.length >= 2)
342
+ const latest = updatedMains.at(-1)
343
+ assert.match(latest.description, /second failure/)
344
+ assert.doesNotMatch(latest.description, /first failure/)
345
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
346
+ assert.equal(state.body.effectiveMode, 'standard')
347
+ assert.equal(state.body.fallback.active, true)
348
+ assert.match(state.body.fallback.reason, /second failure/)
349
+ assert.match(state.body.preset.description, /second failure/)
350
+ await ctx.dispose()
351
+ })
352
+
353
+ test('config 路由:用 configEditor 写回,非法值 400 且不写', async () => {
354
+ const registry = createFakeRegistry()
355
+ const webServer = createFakeWebServer()
356
+ const configEditor = createFakeConfigEditor()
357
+ const ctx = createFakeContext({ registry, webServer, configEditor })
358
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
359
+ await ctx.flush()
360
+ const handler = webServer.handlers.get('/plugins/dev-plan-presets/config')
361
+
362
+ const invalid = await callRoute(handler, 'POST', { modelGuardMode: 'kill' })
363
+ assert.equal(invalid.code, 400)
364
+ assert.equal(configEditor.edits.length, 0)
365
+
366
+ const ok = await callRoute(handler, 'POST', {
367
+ developMode: 'deep-ptc',
368
+ childProvider: 'p',
369
+ childModel: 'm',
370
+ childReasoningEffort: 'high',
371
+ modelGuardMode: 'audit',
372
+ killOnViolation: false,
373
+ honorExplicit: true,
374
+ audit: false,
375
+ guardAllSubagents: true,
376
+ mainToolMode: 'ask-edit',
377
+ mainStepWarnThreshold: 10,
378
+ })
379
+ assert.equal(ok.code, 200)
380
+ assert.equal(configEditor.edits.length, 1)
381
+ assert.deepEqual(configEditor.edits[0].next, {
382
+ developMode: 'deep-ptc',
383
+ childProvider: 'p',
384
+ childModel: 'm',
385
+ childReasoningEffort: 'high',
386
+ modelGuardMode: 'audit',
387
+ killOnViolation: false,
388
+ honorExplicit: true,
389
+ audit: false,
390
+ guardAllSubagents: true,
391
+ mainToolMode: 'ask-edit',
392
+ mainStepWarnThreshold: 10,
393
+ })
394
+ assert.equal(ok.body.ok, true)
395
+ await ctx.dispose()
396
+ })
397
+
398
+ test('模型守门 pin:子代理被 select,主会话完全不动', async () => {
399
+ const registry = createFakeRegistry()
400
+ const child = createFakeAgent({ id: 'child-1', parentSession: 'main', origin: 'subagent', current: undefined })
401
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'expensive', model: 'big' } })
402
+ const agents = { get: (id) => (id === 'main' ? parent.agent : child.agent) }
403
+ const ctx = createFakeContext({ registry, agents })
404
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
405
+ await ctx.flush()
406
+ const listener = ctx.listeners.get('agent/created')[0]
407
+ assert.equal(typeof listener, 'function')
408
+
409
+ listener({ agent: child.agent })
410
+ assert.deepEqual(child.selects, [{ provider: 'dsh-opencode-go', model: 'deepseek-v4.1-flash' }])
411
+ assert.equal(child.stepHandlers.length, 1)
412
+
413
+ listener({ agent: parent.agent })
414
+ assert.deepEqual(parent.selects, [])
415
+ assert.equal(parent.stepHandlers.length, 0)
416
+ await ctx.dispose()
417
+ })
418
+
419
+ test('模型守门 pin:pre-step 越界在请求前 reject + cancel + 通知父会话', async () => {
420
+ const registry = createFakeRegistry()
421
+ const child = createFakeAgent({ id: 'child-2', parentSession: 'main', origin: 'subagent', current: undefined })
422
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'expensive', model: 'big' } })
423
+ const agents = { get: (id) => (id === 'main' ? parent.agent : child.agent) }
424
+ const webServer = createFakeWebServer()
425
+ const ctx = createFakeContext({ registry, agents, webServer })
426
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
427
+ await ctx.flush()
428
+ const listener = ctx.listeners.get('agent/created')[0]
429
+ listener({ agent: child.agent })
430
+
431
+ const next = async () => ({ kind: 'enter', messages: [] })
432
+ const decision = await child.stepHandlers[0](
433
+ { modelSelection: { provider: 'other', model: 'expensive' } },
434
+ next,
435
+ )
436
+ assert.deepEqual(decision, { kind: 'reject' })
437
+ assert.equal(child.cancelled.length, 1)
438
+ assert.equal(parent.injected.length, 1)
439
+ assert.match(parent.injected[0].content[0].text, /已中止/)
440
+
441
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
442
+ assert.equal(state.body.violations.length, 1)
443
+ assert.match(state.body.violations[0].text, /越界/)
444
+ await ctx.dispose()
445
+ })
446
+
447
+ test('模型守门 audit:只记录,不 select、不打断', async () => {
448
+ const registry = createFakeRegistry()
449
+ const child = createFakeAgent({ id: 'child-3', parentSession: 'main', origin: 'subagent', current: { provider: 'x', model: 'y' } })
450
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'p', model: 'm' } })
451
+ const agents = { get: (id) => (id === 'main' ? parent.agent : child.agent) }
452
+ const webServer = createFakeWebServer()
453
+ const ctx = createFakeContext({ registry, agents, webServer })
454
+ index.apply(ctx.ctx, { ...base(), modelGuardMode: 'audit' }, { verificationDelayMs: 0 })
455
+ await ctx.flush()
456
+ const listener = ctx.listeners.get('agent/created')[0]
457
+ listener({ agent: child.agent })
458
+ assert.deepEqual(child.selects, [])
459
+ assert.equal(child.stepHandlers.length, 1)
460
+ const decision = await child.stepHandlers[0](
461
+ { modelSelection: { provider: 'x', model: 'y' } },
462
+ async () => ({ kind: 'enter', messages: [] }),
463
+ )
464
+ assert.equal(decision.kind, 'enter')
465
+ assert.equal(child.cancelled.length, 0)
466
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
467
+ assert.equal(state.body.violations.length, 1)
468
+ await ctx.dispose()
469
+ })
470
+
471
+ test('模型守门 off(且 mainToolMode=none):不注册监听、不 select、不检查', async () => {
472
+ const registry = createFakeRegistry()
473
+ const child = createFakeAgent({ id: 'child-4', parentSession: 'main', origin: 'subagent' })
474
+ const ctx = createFakeContext({ registry })
475
+ index.apply(
476
+ ctx.ctx,
477
+ { ...base(), modelGuardMode: 'off', mainToolMode: 'none' },
478
+ { verificationDelayMs: 0 },
479
+ )
480
+ await ctx.flush()
481
+ assert.equal(ctx.listeners.get('agent/created'), undefined)
482
+ assert.deepEqual(child.selects, [])
483
+ assert.equal(child.stepHandlers.length, 0)
484
+ await ctx.dispose()
485
+ })
486
+
487
+ test('config 路由:拒绝 text/plain、cross-site、错误 Origin,且 configEditor 零写入', async () => {
488
+ const registry = createFakeRegistry()
489
+ const webServer = createFakeWebServer()
490
+ const configEditor = createFakeConfigEditor()
491
+ const ctx = createFakeContext({ registry, webServer, configEditor })
492
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
493
+ await ctx.flush()
494
+ const handler = webServer.handlers.get('/plugins/dev-plan-presets/config')
495
+
496
+ const textPlain = await callRoute(handler, 'POST', { modelGuardMode: 'audit' }, { 'content-type': 'text/plain' })
497
+ assert.equal(textPlain.code, 415)
498
+ assert.equal(textPlain.body.code, 'unsupported-media-type')
499
+
500
+ const crossSite = await callRoute(
501
+ handler,
502
+ 'POST',
503
+ { modelGuardMode: 'audit' },
504
+ { 'content-type': 'application/json', 'sec-fetch-site': 'cross-site' },
505
+ )
506
+ assert.equal(crossSite.code, 403)
507
+ assert.equal(crossSite.body.code, 'forbidden-origin')
508
+
509
+ const badOrigin = await callRoute(
510
+ handler,
511
+ 'POST',
512
+ { modelGuardMode: 'audit' },
513
+ { 'content-type': 'application/json', origin: 'https://evil.example', host: '127.0.0.1:1162' },
514
+ )
515
+ assert.equal(badOrigin.code, 403)
516
+ assert.equal(badOrigin.body.code, 'forbidden-origin')
517
+
518
+ // DNS rebinding 形状:Origin 与 Host 同为攻击者域名,但不在实际监听 origin 上。
519
+ const rebinding = await callRoute(
520
+ handler,
521
+ 'POST',
522
+ { modelGuardMode: 'audit' },
523
+ { 'content-type': 'application/json', origin: 'http://evil.example:1162', host: 'evil.example:1162' },
524
+ )
525
+ assert.equal(rebinding.code, 403)
526
+ assert.equal(rebinding.body.reason, 'origin-not-authoritative')
527
+
528
+ const wrongPort = await callRoute(
529
+ handler,
530
+ 'POST',
531
+ { modelGuardMode: 'audit' },
532
+ { 'content-type': 'application/json', origin: 'http://127.0.0.1:9999', host: '127.0.0.1:9999' },
533
+ )
534
+ assert.equal(wrongPort.code, 403)
535
+ assert.equal(wrongPort.body.reason, 'origin-not-authoritative')
536
+
537
+ const nonListening = await callRoute(
538
+ handler,
539
+ 'POST',
540
+ { modelGuardMode: 'audit' },
541
+ { 'content-type': 'application/json', origin: 'http://10.1.2.3:1162', host: '10.1.2.3:1162' },
542
+ )
543
+ assert.equal(nonListening.code, 403)
544
+ assert.equal(nonListening.body.reason, 'origin-not-authoritative')
545
+
546
+ assert.equal(configEditor.edits.length, 0, '被拒绝的请求不得调用 configEditor')
547
+ await ctx.dispose()
548
+ })
549
+
550
+ test('config 路由:允许同源、localhost/[::1] 同端口别名与无 Origin', async () => {
551
+ const registry = createFakeRegistry()
552
+ const webServer = createFakeWebServer()
553
+ const configEditor = createFakeConfigEditor()
554
+ const ctx = createFakeContext({ registry, webServer, configEditor })
555
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
556
+ await ctx.flush()
557
+ const handler = webServer.handlers.get('/plugins/dev-plan-presets/config')
558
+
559
+ const sameOrigin = await callRoute(
560
+ handler,
561
+ 'POST',
562
+ { modelGuardMode: 'audit' },
563
+ {
564
+ 'content-type': 'application/json; charset=utf-8',
565
+ origin: 'http://127.0.0.1:1162',
566
+ host: '127.0.0.1:1162',
567
+ 'sec-fetch-site': 'same-origin',
568
+ },
569
+ )
570
+ assert.equal(sameOrigin.code, 200)
571
+ assert.equal(configEditor.edits.length, 1)
572
+
573
+ const localhostAlias = await callRoute(
574
+ handler,
575
+ 'POST',
576
+ { modelGuardMode: 'audit' },
577
+ {
578
+ 'content-type': 'application/json',
579
+ origin: 'http://localhost:1162',
580
+ host: 'localhost:1162',
581
+ 'sec-fetch-site': 'same-origin',
582
+ },
583
+ )
584
+ assert.equal(localhostAlias.code, 200)
585
+ assert.equal(configEditor.edits.length, 2)
586
+
587
+ const ipv6Alias = await callRoute(
588
+ handler,
589
+ 'POST',
590
+ { modelGuardMode: 'audit' },
591
+ {
592
+ 'content-type': 'application/json',
593
+ origin: 'http://[::1]:1162',
594
+ host: '[::1]:1162',
595
+ 'sec-fetch-site': 'same-origin',
596
+ },
597
+ )
598
+ assert.equal(ipv6Alias.code, 200)
599
+ assert.equal(configEditor.edits.length, 3)
600
+
601
+ const noOrigin = await callRoute(handler, 'POST', { modelGuardMode: 'audit' }, { 'content-type': 'application/json' })
602
+ assert.equal(noOrigin.code, 200)
603
+ assert.equal(configEditor.edits.length, 4)
604
+ await ctx.dispose()
605
+ })
606
+
607
+ test('插件卸载时 guard 总 disposer 真正移除 child 的 pre-step handler', async () => {
608
+ const registry = createFakeRegistry()
609
+ const child = createFakeAgent({ id: 'child-dispose', parentSession: 'main', origin: 'subagent', current: undefined })
610
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'p', model: 'm' } })
611
+ const ctx = createFakeContext({
612
+ registry,
613
+ agents: { get: (id) => (id === 'main' ? parent.agent : child.agent) },
614
+ })
615
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
616
+ await ctx.flush()
617
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
618
+ assert.equal(child.stepHandlers.length, 1)
619
+ await ctx.dispose()
620
+ assert.equal(child.stepHandlers.length, 0, '插件卸载后旧 guard 必须被移除')
621
+ })
622
+
623
+ test('agent/disposed 清理 guard,随后插件卸载保持幂等', async () => {
624
+ const registry = createFakeRegistry()
625
+ const child = createFakeAgent({ id: 'child-agent-disposed', parentSession: 'main', origin: 'subagent', current: undefined })
626
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'p', model: 'm' } })
627
+ const ctx = createFakeContext({
628
+ registry,
629
+ agents: { get: (id) => (id === 'main' ? parent.agent : child.agent) },
630
+ })
631
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
632
+ await ctx.flush()
633
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
634
+ assert.equal(child.stepHandlers.length, 1)
635
+ const disposed = ctx.listeners.get('agent/disposed')?.[0]
636
+ assert.equal(typeof disposed, 'function')
637
+ disposed({ agent: child.agent })
638
+ assert.equal(child.stepHandlers.length, 0)
639
+ await ctx.dispose()
640
+ assert.equal(child.stepHandlers.length, 0)
641
+ })
642
+
643
+ test('modelGuardMode=off(且 mainToolMode=none)不注册 agent/disposed', async () => {
644
+ const ctx = createFakeContext({ registry: createFakeRegistry() })
645
+ index.apply(
646
+ ctx.ctx,
647
+ { ...base(), modelGuardMode: 'off', mainToolMode: 'none' },
648
+ { verificationDelayMs: 0 },
649
+ )
650
+ await ctx.flush()
651
+ assert.equal(ctx.listeners.get('agent/created'), undefined)
652
+ assert.equal(ctx.listeners.get('agent/disposed'), undefined)
653
+ await ctx.dispose()
654
+ })
655
+
656
+ test('模型守门 honorExplicit:显式路由不钉也不挂守卫', async () => {
657
+ const registry = createFakeRegistry()
658
+ const child = createFakeAgent({
659
+ id: 'child-5',
660
+ parentSession: 'main', origin: 'subagent',
661
+ current: { provider: 'explicit', model: 'route' },
662
+ })
663
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'p', model: 'm' } })
664
+ const agents = { get: (id) => (id === 'main' ? parent.agent : child.agent) }
665
+ const ctx = createFakeContext({ registry, agents })
666
+ index.apply(ctx.ctx, { ...base(), honorExplicit: true }, { verificationDelayMs: 0 })
667
+ await ctx.flush()
668
+ const listener = ctx.listeners.get('agent/created')[0]
669
+ listener({ agent: child.agent })
670
+ assert.deepEqual(child.selects, [])
671
+ // 尊重显式路由时不应再挂一个会立刻打断它的守卫。
672
+ assert.equal(child.stepHandlers.length, 0)
673
+ await ctx.dispose()
674
+ })
675
+
676
+ test('模型守门 pin + select 缺失 + kill=false:不 cancel,但保留守卫并记录后续越界', async () => {
677
+ const registry = createFakeRegistry()
678
+ const child = createFakeAgent({
679
+ id: 'child-no-select',
680
+ parentSession: 'main', origin: 'subagent',
681
+ current: undefined,
682
+ select: null,
683
+ })
684
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'p', model: 'm' } })
685
+ const webServer = createFakeWebServer()
686
+ const ctx = createFakeContext({
687
+ registry,
688
+ webServer,
689
+ agents: { get: (id) => (id === 'main' ? parent.agent : child.agent) },
690
+ })
691
+ index.apply(ctx.ctx, { ...base(), killOnViolation: false }, { verificationDelayMs: 0 })
692
+ await ctx.flush()
693
+ const listener = ctx.listeners.get('agent/created')[0]
694
+ listener({ agent: child.agent })
695
+ assert.equal(child.cancelled.length, 0)
696
+ assert.equal(child.stepHandlers.length, 1, 'select 不可用时仍要装 pre-step 守卫')
697
+
698
+ const decision = await child.stepHandlers[0](
699
+ { modelSelection: { provider: 'other', model: 'expensive' } },
700
+ async () => ({ kind: 'enter', messages: [] }),
701
+ )
702
+ assert.equal(decision.kind, 'enter')
703
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
704
+ assert.ok(state.body.violations.some((entry) => /越界/.test(entry.text)))
705
+ assert.ok(state.body.violations.some((entry) => /model\.select/.test(entry.text)))
706
+
707
+ // 主会话仍然完全不受影响。
708
+ listener({ agent: parent.agent })
709
+ assert.equal(parent.selects.length, 0)
710
+ assert.equal(parent.stepHandlers.length, 0)
711
+ await ctx.dispose()
712
+ })
713
+
714
+ test('模型守门 pin + select 抛错 + kill=false:不 cancel,但保留守卫并记录后续越界', async () => {
715
+ const registry = createFakeRegistry()
716
+ const child = createFakeAgent({
717
+ id: 'child-select-throws',
718
+ parentSession: 'main', origin: 'subagent',
719
+ current: undefined,
720
+ select: () => {
721
+ throw new Error('boom')
722
+ },
723
+ })
724
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'p', model: 'm' } })
725
+ const webServer = createFakeWebServer()
726
+ const ctx = createFakeContext({
727
+ registry,
728
+ webServer,
729
+ agents: { get: (id) => (id === 'main' ? parent.agent : child.agent) },
730
+ })
731
+ index.apply(ctx.ctx, { ...base(), killOnViolation: false }, { verificationDelayMs: 0 })
732
+ await ctx.flush()
733
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
734
+ assert.equal(child.cancelled.length, 0)
735
+ assert.equal(child.stepHandlers.length, 1, 'select 抛错时仍要装 pre-step 守卫')
736
+
737
+ const decision = await child.stepHandlers[0](
738
+ { modelSelection: { provider: 'other', model: 'expensive' } },
739
+ async () => ({ kind: 'enter', messages: [] }),
740
+ )
741
+ assert.equal(decision.kind, 'enter')
742
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
743
+ assert.ok(state.body.violations.some((entry) => /钉住子代理路由失败/.test(entry.text)))
744
+ assert.ok(state.body.violations.some((entry) => /越界/.test(entry.text)))
745
+ await ctx.dispose()
746
+ })
747
+
748
+ test('模型守门 pin + select 抛错 + kill=true:仍 cancel 并通知父会话', async () => {
749
+ const registry = createFakeRegistry()
750
+ const child = createFakeAgent({
751
+ id: 'child-select-throws-kill',
752
+ parentSession: 'main', origin: 'subagent',
753
+ current: undefined,
754
+ select: () => {
755
+ throw new Error('boom')
756
+ },
757
+ })
758
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'p', model: 'm' } })
759
+ const ctx = createFakeContext({
760
+ registry,
761
+ agents: { get: (id) => (id === 'main' ? parent.agent : child.agent) },
762
+ })
763
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
764
+ await ctx.flush()
765
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
766
+ assert.equal(child.cancelled.length, 1)
767
+ assert.equal(parent.injected.length, 1)
768
+ assert.equal(child.stepHandlers.length, 1, 'cancel 前已装守卫,但子代理已被中止')
769
+ await ctx.dispose()
770
+ })
771
+
772
+ test('childReasoningEffort 非空时进入 agentOptions 与守门目标', async () => {
773
+ const settings = { ...base(), childReasoningEffort: 'high' }
774
+ const definition = P.buildPresetDefinition({
775
+ settings,
776
+ mode: P.resolveDevelopMode({ requestedMode: 'standard' }),
777
+ })
778
+ const develop = definition.plugins.find((row) => row.id === 'tool-subagent-develop')
779
+ assert.deepEqual(develop.config.agentOptions, {
780
+ provider: 'dsh-opencode-go',
781
+ model: 'deepseek-v4.1-flash',
782
+ reasoningEffort: 'high',
783
+ })
784
+
785
+ const registry = createFakeRegistry()
786
+ const child = createFakeAgent({ id: 'child-6', parentSession: 'main', origin: 'subagent', current: undefined })
787
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'p', model: 'm' } })
788
+ const agents = { get: (id) => (id === 'main' ? parent.agent : child.agent) }
789
+ const ctx = createFakeContext({ registry, agents })
790
+ index.apply(ctx.ctx, settings, { verificationDelayMs: 0 })
791
+ await ctx.flush()
792
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
793
+ assert.deepEqual(child.selects, [
794
+ { provider: 'dsh-opencode-go', model: 'deepseek-v4.1-flash', reasoningEffort: 'high' },
795
+ ])
796
+ const next = async () => ({ kind: 'enter', messages: [] })
797
+ const wrongEffort = await child.stepHandlers[0](
798
+ { modelSelection: { provider: 'dsh-opencode-go', model: 'deepseek-v4.1-flash' } },
799
+ next,
800
+ )
801
+ assert.deepEqual(wrongEffort, { kind: 'reject' })
802
+ await ctx.dispose()
803
+ })
804
+
805
+ test('audit=false 不写审计日志,但越界仍进入 UI 记录', async () => {
806
+ const registry = createFakeRegistry()
807
+ const child = createFakeAgent({ id: 'child-7', parentSession: 'main', origin: 'subagent' })
808
+ const parent = createFakeAgent({ id: 'main', agentPreset: 'dev-plan', current: { provider: 'p', model: 'm' } })
809
+ const agents = { get: (id) => (id === 'main' ? parent.agent : child.agent) }
810
+ const webServer = createFakeWebServer()
811
+ const ctx = createFakeContext({ registry, agents, webServer })
812
+ index.apply(ctx.ctx, { ...base(), audit: false }, { verificationDelayMs: 0 })
813
+ await ctx.flush()
814
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
815
+ await child.stepHandlers[0](
816
+ { modelSelection: { provider: 'x', model: 'y' } },
817
+ async () => ({ kind: 'enter', messages: [] }),
818
+ )
819
+ assert.ok(!ctx.loggerCalls.info.some((line) => line.includes('audit')))
820
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
821
+ assert.equal(state.body.violations.length, 1)
822
+ await ctx.dispose()
823
+ })
824
+
825
+ test('probePresets 返回真实目录:id/name/description/broken,并区分超时', async () => {
826
+ const registry = createFakeRegistry({
827
+ rows: [
828
+ { id: 'standard', name: 'Standard' },
829
+ { id: 'deep-ptc', name: '深度 PTC', description: 'PTC', broken: 'load failed' },
830
+ { nonsense: true },
831
+ ],
832
+ })
833
+ const ctx = createFakeContext({
834
+ registry,
835
+ entries: [{ id: 'ptc-row', options: { name: 'dsh-deep-ptc-mode' }, fiber: { state: 1 } }],
836
+ })
837
+ const probe = await index.probePresets(ctx.ctx, registry)
838
+ assert.equal(probe.checked, true)
839
+ assert.equal(probe.timedOut, false)
840
+ assert.deepEqual(probe.rows.map((row) => row.id), ['standard', 'deep-ptc'])
841
+ assert.equal(probe.rows[1].name, '深度 PTC')
842
+ assert.equal(probe.rows[1].description, 'PTC')
843
+ assert.equal(probe.rows[1].broken, 'load failed')
844
+
845
+ const hanging = createFakeRegistry()
846
+ hanging.list = () => new Promise(() => {})
847
+ const timeoutCtx = createFakeContext({ registry: hanging })
848
+ const timedOut = await index.probePresets(timeoutCtx.ctx, hanging)
849
+ assert.equal(timedOut.checked, false)
850
+ assert.equal(timedOut.timedOut, true)
851
+ assert.deepEqual(timedOut.rows, [])
852
+ })
853
+
854
+ test('P0-1 风险分级:快速/标准/高风险 + 四维判定 + 快速路径不取消必做项', () => {
855
+ const definition = P.buildPresetDefinition({
856
+ settings: base(),
857
+ mode: P.resolveDevelopMode({ requestedMode: 'standard' }),
858
+ internalPresets: { scout: true, scribe: true },
859
+ })
860
+ const persona = definition.plugins.find((row) => row.id === 'persona').config.prefix
861
+ for (const marker of ['快速路径', '标准路径', '高风险路径', '歧义', '影响面', '可逆性', '可验证性']) {
862
+ assert.ok(persona.includes(marker), `缺 P0-1 标记:${marker}`)
863
+ }
864
+ assert.match(persona, /不可取消用户开工批准、developer 自验与主窗审查/)
865
+ assert.match(persona, /不为了流程派 recon\/review\/scribe/)
866
+ assert.match(persona, /必须升级路径/)
867
+ assert.match(persona, /绝不因验证困难降级/)
868
+ assert.doesNotMatch(persona, /降低路径等级并补验收/)
869
+ })
870
+
871
+ test('P0-2 一次性开工契约:字段齐全且普通实现不反复批准', () => {
872
+ const definition = P.buildPresetDefinition({
873
+ settings: base(),
874
+ mode: P.resolveDevelopMode({ requestedMode: 'standard' }),
875
+ internalPresets: { scout: true, scribe: true },
876
+ })
877
+ const persona = definition.plugins.find((row) => row.id === 'persona').config.prefix
878
+ for (const marker of [
879
+ '开工契约',
880
+ '目标',
881
+ '非目标',
882
+ '允许与禁止改动路径',
883
+ '接口与兼容约束',
884
+ '验收标准',
885
+ '检查命令',
886
+ '风险',
887
+ ]) {
888
+ assert.ok(persona.includes(marker), `缺 P0-2 标记:${marker}`)
889
+ }
890
+ assert.match(persona, /普通实现不反复请示/)
891
+ assert.match(persona, /仅范围扩大、风险变化或宿主权限要求/)
892
+ })
893
+
894
+ test('P0-3 验收前置:最小切片→语法/静态契约→针对性测试→必要运行/GUI,且静态不冒充真实验证', () => {
895
+ const definition = P.buildPresetDefinition({
896
+ settings: base(),
897
+ mode: P.resolveDevelopMode({ requestedMode: 'standard' }),
898
+ internalPresets: { scout: true, scribe: true },
899
+ })
900
+ const persona = definition.plugins.find((row) => row.id === 'persona').config.prefix
901
+ const ordered = ['最小切片', '语法/静态契约', '针对性测试', '必要运行/GUI']
902
+ let cursor = -1
903
+ for (const marker of ordered) {
904
+ const index = persona.indexOf(marker)
905
+ assert.ok(index > cursor, `P0-3 顺序错误或缺标记:${marker}`)
906
+ cursor = index
907
+ }
908
+ assert.match(persona, /静态检查\/单测不等于真实运行验收/)
909
+ assert.match(persona, /verified\|partial\|failed\|未验证/)
910
+ })
911
+
912
+ test('P0-4 非阻塞协作:不轮询/不忙等/不重复施工/不重复读文件,developer 打断边界明确', () => {
913
+ const definition = P.buildPresetDefinition({
914
+ settings: base(),
915
+ mode: P.resolveDevelopMode({ requestedMode: 'standard' }),
916
+ internalPresets: { scout: true, scribe: true },
917
+ })
918
+ const persona = definition.plugins.find((row) => row.id === 'persona').config.prefix
919
+ for (const marker of ['非阻塞协作', '不轮询', '不 `sleep`', '不重复施工', '读写 developer 正在改的文件']) {
920
+ assert.ok(persona.includes(marker), `缺 P0-4 标记:${marker}`)
921
+ }
922
+ assert.match(persona, /developer 仅在阻塞、范围冲突或关键契约决策时打断/)
923
+ })
924
+
925
+ test('P0-5 证据化审查与严重度返工:实际 diff、阻塞/非阻塞、最终责任不外包', () => {
926
+ const definition = P.buildPresetDefinition({
927
+ settings: base(),
928
+ mode: P.resolveDevelopMode({ requestedMode: 'standard' }),
929
+ internalPresets: { scout: true, scribe: true },
930
+ })
931
+ const persona = definition.plugins.find((row) => row.id === 'persona').config.prefix
932
+ for (const marker of ['证据化审查', '阻塞', '重要', '建议', 'review 不替代主窗最终审查']) {
933
+ assert.ok(persona.includes(marker), `缺 P0-5 标记:${marker}`)
934
+ }
935
+ assert.match(persona, /send_message.*developer/)
936
+ assert.match(persona, /不无限打磨/)
937
+ assert.match(persona, /recon.*仅在缺失事实/)
938
+ assert.match(persona, /review.*仅高风险/)
939
+ assert.match(persona, /scribe.*仅文档属验收范围/)
940
+ for (const marker of ['分层变更证据', '只有文件清单或口头摘要不算审过 diff', '补证据']) {
941
+ assert.ok(persona.includes(marker), `缺实际变更证据标记:${marker}`)
942
+ }
943
+ assert.match(persona, /git diff/)
944
+ assert.match(persona, /200 行/)
945
+ assert.doesNotMatch(persona, /只有改动摘要也算证据|只给文件清单(?:也)?可以/)
946
+ })
947
+
948
+ test('client 回退横幅涵盖不可用原因(中英文)', () => {
949
+ const source = readFileSync(join(ROOT, 'client.js'), 'utf8')
950
+ for (const marker of ['已回退 standard', '未安装', '未启用', '已被移除', '加载失败']) {
951
+ assert.ok(source.includes(marker), `client 回退横幅缺标记:${marker}`)
952
+ }
953
+ for (const marker of ['Fell back to standard', 'not installed', 'failed to load']) {
954
+ assert.ok(source.includes(marker), `client 英文回退横幅缺标记:${marker}`)
955
+ }
956
+ // 目录超时同样要有可理解状态,而不是伪装成正常。
957
+ for (const marker of ['施工方式列表读取超时', 'setup list timed out']) {
958
+ assert.ok(source.includes(marker), `client 缺少目录超时状态:${marker}`)
959
+ }
960
+ })
961
+
962
+ test('派工事实:实际 develop/send_message 工具调用才是派工,文本不算', () => {
963
+ const definition = P.buildPresetDefinition({
964
+ settings: base(),
965
+ mode: P.resolveDevelopMode({ requestedMode: 'standard' }),
966
+ internalPresets: { scout: true, scribe: true },
967
+ })
968
+ const personaRow = definition.plugins.find((row) => row.id === 'persona')
969
+ const persona = `${personaRow.config.prefix}${personaRow.config.suffix}`
970
+ for (const marker of [
971
+ '文本不是派工',
972
+ '实际调用 develop',
973
+ '已派出 developer',
974
+ '未派工:原因',
975
+ 'prompt',
976
+ 'send_message',
977
+ ]) {
978
+ assert.ok(persona.includes(marker), `缺派工事实标记:${marker}`)
979
+ }
980
+ assert.doesNotMatch(persona, /文本也能算派工|没有调用也可以说已派出|文本任务书即视为已派工/)
981
+ })
982
+
983
+ test('插件显示名带模式,预设名保持开发规划与交付', () => {
984
+ const zh = JSON.parse(readFileSync(join(ROOT, 'locale/zh.json'), 'utf8'))
985
+ const en = JSON.parse(readFileSync(join(ROOT, 'locale/en.json'), 'utf8'))
986
+ assert.equal(zh.meta.title, '开发规划与交付模式')
987
+ assert.equal(en.meta.title, 'Development planning & delivery Mode')
988
+ assert.ok(zh.meta.title.endsWith('模式'))
989
+ assert.ok(en.meta.title.endsWith('Mode'))
990
+ assert.equal(P.PRESET_NAME, '开发规划与交付')
991
+
992
+ const client = readFileSync(join(ROOT, 'client.js'), 'utf8')
993
+ assert.ok(client.includes('开发规划与交付 · 施工设置'))
994
+ assert.ok(!client.includes('开发规划与交付模式 · 施工设置'), '设置页标题应继续使用 preset 名')
995
+
996
+ const readme = readFileSync(join(ROOT, 'README.md'), 'utf8')
997
+ assert.ok(readme.includes('开发规划与交付模式'))
998
+ assert.ok(readme.includes('preset 名称仍是「开发规划与交付」'))
999
+ assert.ok(readme.includes('显示名已定'))
1000
+ assert.ok(!readme.includes('显示名未定'))
1001
+ assert.ok(!readme.includes('界面名称仍是「开发规划」'))
1002
+ })
1003
+
1004
+ test('guard 只认子代理 header:fork 主对话(parentSession + depth 0)不算', () => {
1005
+ assert.equal(guard.isSubagentHeader(undefined), false)
1006
+ assert.equal(guard.isSubagentHeader({}), false)
1007
+ assert.equal(guard.isSubagentHeader({ origin: 'user' }), false)
1008
+ // 宿主真实 fork 主对话形状:有 parentSession、isSeeded、delegationDepth:0、无 origin。
1009
+ assert.equal(guard.isSubagentHeader({ parentSession: 'main' }), false)
1010
+ assert.equal(guard.isSubagentHeader({ parentSession: 'main', isSeeded: true, delegationDepth: 0 }), false)
1011
+ assert.equal(guard.isSubagentHeader({ origin: 'subagent' }), true)
1012
+ assert.equal(guard.isSubagentHeader({ parentSession: 'main', delegationDepth: 1 }), true)
1013
+ assert.equal(guard.isSubagentHeader({ delegationDepth: 0, origin: 'subagent' }), true)
1014
+ assert.equal(guard.isSubagentHeader({ delegationDepth: '1' }), false)
1015
+ })
1016
+
1017
+ test('fork 形主对话在 guardAllSubagents true/false 下都不 select、不挂 pre-step', async () => {
1018
+ for (const global of [false, true]) {
1019
+ const registry = createFakeRegistry()
1020
+ const fork = createFakeAgent({
1021
+ id: 'fork-main',
1022
+ parentSession: 'main',
1023
+ isSeeded: true,
1024
+ delegationDepth: 0,
1025
+ current: undefined,
1026
+ })
1027
+ const parent = createFakeAgent({
1028
+ id: 'main',
1029
+ agentPreset: 'dev-plan',
1030
+ current: { provider: 'p', model: 'm' },
1031
+ })
1032
+ const ctx = createFakeContext({
1033
+ registry,
1034
+ agents: { get: (id) => (id === 'main' ? parent.agent : fork.agent) },
1035
+ })
1036
+ index.apply(ctx.ctx, { ...base(), guardAllSubagents: global }, { verificationDelayMs: 0 })
1037
+ await ctx.flush()
1038
+ const listener = ctx.listeners.get('agent/created')[0]
1039
+ listener({ agent: fork.agent })
1040
+ assert.deepEqual(fork.selects, [], 'fork 主对话不得被 select(global=' + global + ')')
1041
+ assert.equal(fork.stepHandlers.length, 0, 'fork 主对话不得挂 pre-step(global=' + global + ')')
1042
+ listener({ agent: parent.agent })
1043
+ assert.equal(parent.stepHandlers.length, 0, '主会话永不守门')
1044
+ await ctx.dispose()
1045
+ }
1046
+ })
1047
+
1048
+ test('delegationDepth>0 的真正子代理仍按 dev-plan 范围守门', async () => {
1049
+ const registry = createFakeRegistry()
1050
+ const child = createFakeAgent({
1051
+ id: 'child-depth',
1052
+ parentSession: 'main',
1053
+ delegationDepth: 1,
1054
+ current: undefined,
1055
+ })
1056
+ const parent = createFakeAgent({
1057
+ id: 'main',
1058
+ agentPreset: 'dev-plan',
1059
+ current: { provider: 'p', model: 'm' },
1060
+ })
1061
+ const ctx = createFakeContext({
1062
+ registry,
1063
+ agents: { get: (id) => (id === 'main' ? parent.agent : child.agent) },
1064
+ })
1065
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
1066
+ await ctx.flush()
1067
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
1068
+ assert.equal(child.selects.length, 1)
1069
+ assert.equal(child.stepHandlers.length, 1)
1070
+ await ctx.dispose()
1071
+ })
1072
+
1073
+ test('任意有效 develop preset:不再限于 standard/deep-ptc', () => {
1074
+ const mode = P.resolveDevelopMode({
1075
+ requestedMode: 'team-builder',
1076
+ presets: [{ id: 'team-builder', name: '团队施工' }],
1077
+ catalogChecked: true,
1078
+ })
1079
+ assert.equal(mode.effective, 'team-builder')
1080
+ assert.equal(mode.fallback, false)
1081
+ const definition = P.buildPresetDefinition({
1082
+ settings: base(),
1083
+ mode,
1084
+ internalPresets: { scout: true, scribe: true },
1085
+ })
1086
+ const develop = definition.plugins.find((row) => row.id === 'tool-subagent-develop')
1087
+ assert.equal(develop.config.agentPreset, 'team-builder')
1088
+ assert.match(definition.description, /团队施工/)
1089
+ const persona = definition.plugins.find((row) => row.id === 'persona').config.prefix
1090
+ assert.match(persona, /当前施工子代理:团队施工(team-builder)/)
1091
+ })
1092
+
1093
+ test('自引用与缺失/超时:保留配置原值,运行期回退 standard', async () => {
1094
+ for (const selfId of ['dev-plan', 'dev-plan-scout', 'dev-plan-scribe']) {
1095
+ const selfMode = P.resolveDevelopMode({
1096
+ requestedMode: selfId,
1097
+ presets: [{ id: selfId, name: selfId }],
1098
+ catalogChecked: true,
1099
+ })
1100
+ assert.equal(selfMode.fallback, true)
1101
+ assert.match(selfMode.reason, /递归派工|内部预设/)
1102
+ }
1103
+
1104
+ const missing = P.resolveDevelopMode({
1105
+ requestedMode: 'removed-preset',
1106
+ presets: [],
1107
+ catalogChecked: true,
1108
+ })
1109
+ assert.equal(missing.requested, 'removed-preset')
1110
+ assert.equal(missing.effective, 'standard')
1111
+ assert.equal(missing.fallback, true)
1112
+
1113
+ const registry = createFakeRegistry({ rows: [] })
1114
+ const webServer = createFakeWebServer()
1115
+ const ctx = createFakeContext({ registry, webServer })
1116
+ index.apply(ctx.ctx, { ...base(), developMode: 'removed-preset' }, { verificationDelayMs: 0 })
1117
+ await ctx.flush()
1118
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
1119
+ // 配置原值不被静默改写;只有运行期 effective 回退。
1120
+ assert.equal(state.body.config.developMode, 'removed-preset')
1121
+ assert.equal(state.body.requestedMode, 'removed-preset')
1122
+ assert.equal(state.body.effectiveMode, 'standard')
1123
+ assert.equal(state.body.fallback.active, true)
1124
+ const mainDef = registry.definitions.find((d) => d.id === 'dev-plan')
1125
+ assert.equal(
1126
+ mainDef.plugins.find((row) => row.id === 'tool-subagent-develop').config.agentPreset,
1127
+ 'standard',
1128
+ )
1129
+ await ctx.dispose()
1130
+ })
1131
+
1132
+ test('预设目录超时:显式回退并保留 timedOut,供 UI 提示', async () => {
1133
+ const registry = createFakeRegistry()
1134
+ registry.list = () => new Promise(() => {})
1135
+ const webServer = createFakeWebServer()
1136
+ const ctx = createFakeContext({ registry, webServer })
1137
+ index.apply(ctx.ctx, { ...base(), developMode: 'deep-ptc' }, { verificationDelayMs: 0 })
1138
+ await ctx.flush()
1139
+ // probe 会等满 MAX_PROBE_MS,再发布回退结果。
1140
+ await sleep(1400)
1141
+ await ctx.flush()
1142
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
1143
+ assert.equal(state.body.effectiveMode, 'standard')
1144
+ assert.equal(state.body.fallback.active, true)
1145
+ assert.equal(state.body.presets.checked, false)
1146
+ assert.equal(state.body.presets.timedOut, true)
1147
+ assert.match(state.body.fallback.reason, /尚未就绪|读取超时/)
1148
+ await ctx.dispose()
1149
+ })
1150
+
1151
+ test('模型目录:枚举 provider/model,单个 provider 失败只局部降级', async () => {
1152
+ const registry = createFakeRegistry()
1153
+ const webServer = createFakeWebServer()
1154
+ const llm = {
1155
+ listProviders: () => [
1156
+ { id: 'alpha', name: 'Alpha 服务商' },
1157
+ { id: 'broken', name: 'Broken 服务商' },
1158
+ ],
1159
+ listModels: async (id) => {
1160
+ if (id === 'broken') throw new Error('missing credentials')
1161
+ return [
1162
+ { id: 'alpha-1', name: 'Alpha 一号' },
1163
+ { id: 'alpha-2' },
1164
+ ]
1165
+ },
1166
+ }
1167
+ const ctx = createFakeContext({ registry, webServer, llm })
1168
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
1169
+ await ctx.flush()
1170
+ const handler = webServer.handlers.get('/plugins/dev-plan-presets/state')
1171
+ // 第一次 /state 只返回快照并启动后台刷新;第二次读到刷新结果。
1172
+ const first = await callRoute(handler, 'GET')
1173
+ assert.equal(first.body.modelCatalog.checked, false)
1174
+ await sleep(0)
1175
+ await ctx.flush()
1176
+ const state = await callRoute(handler, 'GET')
1177
+ assert.equal(state.body.modelCatalog.checked, true)
1178
+ assert.deepEqual(
1179
+ state.body.modelCatalog.providers.map((item) => [item.provider, item.models.map((m) => m.model)]),
1180
+ [
1181
+ ['alpha', ['alpha-1', 'alpha-2']],
1182
+ ['broken', []],
1183
+ ],
1184
+ )
1185
+ assert.deepEqual(state.body.modelCatalog.failures.map((item) => item.provider), ['broken'])
1186
+ assert.match(state.body.modelCatalog.failures[0].message, /missing credentials/)
1187
+ assert.equal(state.body.modelCatalog.providers[0].models[0].name, 'Alpha 一号')
1188
+ await ctx.dispose()
1189
+ })
1190
+
1191
+ test('模型目录失败与旧路由:目录不可用时不改旧值,也不伪装成目录正常', async () => {
1192
+ const registry = createFakeRegistry()
1193
+ const webServer = createFakeWebServer()
1194
+ const configEditor = createFakeConfigEditor()
1195
+ const llm = {
1196
+ listProviders: () => {
1197
+ throw new Error('catalog exploded')
1198
+ },
1199
+ listModels: async () => [],
1200
+ }
1201
+ const ctx = createFakeContext({ registry, webServer, configEditor, llm })
1202
+ index.apply(
1203
+ ctx.ctx,
1204
+ { ...base(), childProvider: 'legacy-provider', childModel: 'legacy-model' },
1205
+ { verificationDelayMs: 0 },
1206
+ )
1207
+ await ctx.flush()
1208
+ const handler = webServer.handlers.get('/plugins/dev-plan-presets/state')
1209
+ await callRoute(handler, 'GET')
1210
+ await sleep(0)
1211
+ await ctx.flush()
1212
+ const state = await callRoute(handler, 'GET')
1213
+ assert.equal(state.body.modelCatalog.checked, false)
1214
+ assert.match(state.body.modelCatalog.error, /catalog exploded/)
1215
+ assert.equal(state.body.config.childProvider, 'legacy-provider')
1216
+ assert.equal(state.body.config.childModel, 'legacy-model')
1217
+ assert.equal(state.body.route.provider, 'legacy-provider')
1218
+ assert.equal(state.body.route.model, 'legacy-model')
1219
+
1220
+ // 目录失败不会把旧值改成默认值:原样提交视为 unchanged,不触发写回。
1221
+ const unchanged = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/config'), 'POST', {
1222
+ childProvider: 'legacy-provider',
1223
+ childModel: 'legacy-model',
1224
+ childReasoningEffort: '',
1225
+ })
1226
+ assert.equal(unchanged.code, 200)
1227
+ assert.equal(unchanged.body.unchanged, true)
1228
+ assert.equal(configEditor.edits.length, 0)
1229
+
1230
+ // 用户明确改成另一组值时仍可保存,且不会因目录失败被拒绝或改写。
1231
+ const saved = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/config'), 'POST', {
1232
+ childProvider: 'other-provider',
1233
+ childModel: 'other-model',
1234
+ childReasoningEffort: '',
1235
+ })
1236
+ assert.equal(saved.code, 200)
1237
+ assert.equal(configEditor.edits.length, 1)
1238
+ assert.equal(configEditor.edits[0].next.childProvider, 'other-provider')
1239
+ await ctx.dispose()
1240
+ })
1241
+
1242
+ test('守门范围矩阵:默认只守 dev-plan 父会话,global 开关恢复全局,主会话永不守', async () => {
1243
+ const scenarios = [
1244
+ { name: 'dev-plan 父会话', parentPreset: 'dev-plan', global: false, guarded: true },
1245
+ { name: '非 dev-plan 父会话', parentPreset: 'standard', global: false, guarded: false },
1246
+ { name: '父会话 preset 未知', parentPreset: undefined, global: false, guarded: false },
1247
+ { name: '非 dev-plan + global', parentPreset: 'standard', global: true, guarded: true },
1248
+ { name: 'dev-plan + global', parentPreset: 'dev-plan', global: true, guarded: true },
1249
+ ]
1250
+ for (const scenario of scenarios) {
1251
+ const registry = createFakeRegistry()
1252
+ const child = createFakeAgent({ id: 'child', parentSession: 'main', origin: 'subagent', current: undefined })
1253
+ const parent = createFakeAgent({
1254
+ id: 'main',
1255
+ agentPreset: scenario.parentPreset,
1256
+ current: { provider: 'p', model: 'm' },
1257
+ })
1258
+ const ctx = createFakeContext({
1259
+ registry,
1260
+ agents: { get: (id) => (id === 'main' ? parent.agent : child.agent) },
1261
+ })
1262
+ index.apply(ctx.ctx, { ...base(), guardAllSubagents: scenario.global }, { verificationDelayMs: 0 })
1263
+ await ctx.flush()
1264
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
1265
+ assert.equal(
1266
+ child.stepHandlers.length,
1267
+ scenario.guarded ? 1 : 0,
1268
+ `${scenario.name} 的守门范围错误`,
1269
+ )
1270
+ await ctx.dispose()
1271
+ }
1272
+
1273
+ // registry.presetForSession 优先于 header,且主会话即使 global 也不守。
1274
+ const registry = createFakeRegistry({ presetForSession: () => 'dev-plan' })
1275
+ const child = createFakeAgent({
1276
+ id: 'child-priority',
1277
+ parentSession: 'main', origin: 'subagent',
1278
+ current: undefined,
1279
+ })
1280
+ const parent = createFakeAgent({
1281
+ id: 'main',
1282
+ agentPreset: 'standard',
1283
+ current: { provider: 'p', model: 'm' },
1284
+ })
1285
+ const ctx = createFakeContext({
1286
+ registry,
1287
+ agents: { get: (id) => (id === 'main' ? parent.agent : child.agent) },
1288
+ })
1289
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
1290
+ await ctx.flush()
1291
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
1292
+ assert.equal(child.stepHandlers.length, 1, 'presetForSession 应优先于 header')
1293
+ assert.equal(parent.stepHandlers.length, 0, '主会话永不守门')
1294
+ await ctx.dispose()
1295
+ })
1296
+
1297
+ test('施工目录/权限规则写入主代理 persona', () => {
1298
+ const definition = P.buildPresetDefinition({
1299
+ settings: base(),
1300
+ mode: P.resolveDevelopMode({ requestedMode: 'standard' }),
1301
+ internalPresets: { scout: true, scribe: true },
1302
+ })
1303
+ const persona = definition.plugins.find((row) => row.id === 'persona').config.prefix
1304
+ for (const marker of [
1305
+ '施工目录边界',
1306
+ 'cwd',
1307
+ '可写工作区',
1308
+ 'working_directory',
1309
+ 'cd',
1310
+ '父会话事后提权不扩大已有子代理权限',
1311
+ '沙箱',
1312
+ '原错',
1313
+ ]) {
1314
+ assert.ok(persona.includes(marker), `缺权限防护标记:${marker}`)
1315
+ }
1316
+ assert.match(persona, /不在范围或不确定时停止并问用户/)
1317
+ assert.match(persona, /目标子目录尚未创建.*已存在的父目录.*自行创建该子目录/)
1318
+ })
1319
+
1320
+ test('设置页契约:动态预设/模型下拉、原生控件、label 关联与守门范围开关', () => {
1321
+ const source = readFileSync(join(ROOT, 'client.js'), 'utf8')
1322
+ for (const marker of [
1323
+ 'state.presets',
1324
+ 'presetRows',
1325
+ 'state.modelCatalog',
1326
+ 'providers',
1327
+ 'guardAllSubagents',
1328
+ 'htmlFor',
1329
+ 'aria-describedby',
1330
+ 'fieldset',
1331
+ 'legend',
1332
+ "type: 'button'",
1333
+ '同时管理其他插件的子代理',
1334
+ '服务商',
1335
+ '模型',
1336
+ ]) {
1337
+ assert.ok(source.includes(marker), `设置页缺契约标记:${marker}`)
1338
+ }
1339
+ // 不再硬编码 deep-ptc 选项,也不再使用自由文本 provider/model 输入。
1340
+ assert.ok(!source.includes("value: 'deep-ptc'"), '不应硬编码 deep-ptc 选项')
1341
+ assert.ok(!/childProvider:\s*'\s*'/.test(source), '不应把 provider 当自由文本初始化')
1342
+ assert.ok(!source.includes('configEditor'), '普通文案不应出现 configEditor')
1343
+ assert.ok(!source.includes('reasoningEffort(可空)'), '不应把 reasoningEffort 当主标签')
1344
+ assert.ok(!/onChange:\s*save/.test(source), '选择变化不得自动保存')
1345
+ })
1346
+
1347
+ test('state 返回真实预设目录:名称、broken 与自定义预设生效', async () => {
1348
+ const registry = createFakeRegistry({
1349
+ rows: [
1350
+ { id: 'dev-plan', name: '开发规划与交付' },
1351
+ { id: 'team-builder', name: '团队施工', description: '团队预设' },
1352
+ { id: 'broken-preset', name: '损坏预设', broken: 'import failed' },
1353
+ ],
1354
+ })
1355
+ const webServer = createFakeWebServer()
1356
+ const ctx = createFakeContext({ registry, webServer })
1357
+ index.apply(ctx.ctx, { ...base(), developMode: 'team-builder' }, { verificationDelayMs: 0 })
1358
+ await ctx.flush()
1359
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
1360
+ assert.equal(state.body.effectiveMode, 'team-builder')
1361
+ assert.equal(state.body.modeName, '团队施工')
1362
+ assert.deepEqual(state.body.presets.rows.map((row) => row.id), ['dev-plan', 'team-builder', 'broken-preset'])
1363
+ assert.equal(state.body.presets.rows[1].name, '团队施工')
1364
+ assert.equal(state.body.presets.rows[2].broken, 'import failed')
1365
+ assert.equal(
1366
+ registry.definitions.find((d) => d.id === 'dev-plan').plugins.find((row) => row.id === 'tool-subagent-develop').config.agentPreset,
1367
+ 'team-builder',
1368
+ )
1369
+ await ctx.dispose()
1370
+
1371
+ const brokenRegistry = createFakeRegistry({
1372
+ rows: [{ id: 'broken-preset', name: '损坏预设', broken: 'import failed' }],
1373
+ })
1374
+ const brokenWeb = createFakeWebServer()
1375
+ const brokenCtx = createFakeContext({ registry: brokenRegistry, webServer: brokenWeb })
1376
+ index.apply(brokenCtx.ctx, { ...base(), developMode: 'broken-preset' }, { verificationDelayMs: 0 })
1377
+ await brokenCtx.flush()
1378
+ const brokenState = await callRoute(brokenWeb.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
1379
+ assert.equal(brokenState.body.effectiveMode, 'standard')
1380
+ assert.equal(brokenState.body.fallback.active, true)
1381
+ assert.match(brokenState.body.fallback.reason, /加载失败/)
1382
+ assert.equal(brokenState.body.config.developMode, 'broken-preset')
1383
+ await brokenCtx.dispose()
1384
+ })
1385
+
1386
+ test('presetForSession 返回 null 时回退 header.agentPreset 判断守门范围', async () => {
1387
+ const registry = createFakeRegistry({ presetForSession: () => null })
1388
+ const child = createFakeAgent({ id: 'child-fallback', parentSession: 'main', origin: 'subagent', current: undefined })
1389
+ const parent = createFakeAgent({
1390
+ id: 'main',
1391
+ agentPreset: 'dev-plan',
1392
+ current: { provider: 'p', model: 'm' },
1393
+ })
1394
+ const ctx = createFakeContext({
1395
+ registry,
1396
+ agents: { get: (id) => (id === 'main' ? parent.agent : child.agent) },
1397
+ })
1398
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
1399
+ await ctx.flush()
1400
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
1401
+ assert.equal(child.stepHandlers.length, 1, 'header.agentPreset=dev-plan 时应守门')
1402
+ await ctx.dispose()
1403
+ })
1404
+
1405
+ test('模型目录刷新不阻塞 /state:慢 provider 下状态立即返回快照', async () => {
1406
+ const registry = createFakeRegistry()
1407
+ const webServer = createFakeWebServer()
1408
+ const llm = {
1409
+ listProviders: () => [{ id: 'slow', name: 'Slow' }],
1410
+ listModels: () => new Promise(() => {}),
1411
+ }
1412
+ const ctx = createFakeContext({ registry, webServer, llm })
1413
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
1414
+ await ctx.flush()
1415
+ const started = Date.now()
1416
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
1417
+ const elapsed = Date.now() - started
1418
+ assert.ok(elapsed < 500, `/state 不应等待 listModels,实际 ${elapsed}ms`)
1419
+ assert.equal(state.body.modelCatalog.checked, false)
1420
+ assert.equal(state.body.modelCatalog.providers.length, 0)
1421
+ await ctx.dispose()
1422
+ })
1423
+
1424
+ test('设置页静置 60s:模型全量枚举至多 2 次(初始 + 一次刷新)', async () => {
1425
+ let clock = 0
1426
+ let listCalls = 0
1427
+ const registry = createFakeRegistry()
1428
+ const webServer = createFakeWebServer()
1429
+ const llm = {
1430
+ listProviders: () => [{ id: 'p', name: 'P' }],
1431
+ listModels: async () => {
1432
+ listCalls += 1
1433
+ return [{ id: 'm', name: 'M' }]
1434
+ },
1435
+ }
1436
+ const ctx = createFakeContext({ registry, webServer, llm })
1437
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0, now: () => clock })
1438
+ await ctx.flush()
1439
+ const handler = webServer.handlers.get('/plugins/dev-plan-presets/state')
1440
+
1441
+ await callRoute(handler, 'GET')
1442
+ await sleep(0)
1443
+ await ctx.flush()
1444
+ assert.equal(listCalls, 1, '首次 /state 应触发一次初始枚举')
1445
+
1446
+ for (let t = 4000; t <= 56000; t += 4000) {
1447
+ clock = t
1448
+ await callRoute(handler, 'GET')
1449
+ await sleep(0)
1450
+ await ctx.flush()
1451
+ assert.equal(listCalls, 1, `t=${t}ms 时不应重复全量枚举`)
1452
+ }
1453
+
1454
+ clock = 60000
1455
+ await callRoute(handler, 'GET')
1456
+ await sleep(0)
1457
+ await ctx.flush()
1458
+ assert.equal(listCalls, 2, '60s 时应至多刷新一次')
1459
+ await ctx.dispose()
1460
+ })
1461
+
1462
+ test('client 行为:broken/自身/旧值禁用,确实来自真实 client 纯函数', async () => {
1463
+ const api = await loadClientTestApi()
1464
+ const T = (cn) => cn
1465
+ const choices = api.presetChoices(
1466
+ [
1467
+ { id: 'dev-plan', name: '开发规划与交付' },
1468
+ { id: 'broken-preset', name: '损坏方式', broken: 'import failed' },
1469
+ { id: 'team-builder', name: '团队施工' },
1470
+ ],
1471
+ 'broken-preset',
1472
+ 'dev-plan',
1473
+ T,
1474
+ )
1475
+ const byValue = Object.fromEntries(choices.map((choice) => [choice.value, choice]))
1476
+ assert.equal(byValue.standard.disabled, undefined)
1477
+ assert.equal(byValue['dev-plan'].disabled, true, 'dev-plan 自身必须禁用')
1478
+ assert.equal(byValue['broken-preset'].disabled, true, 'broken 项必须禁用')
1479
+ assert.equal(byValue['team-builder'].disabled, undefined)
1480
+ assert.match(byValue['broken-preset'].label, /不可用/)
1481
+ assert.match(byValue['dev-plan'].label, /不能选自己/)
1482
+
1483
+ const legacy = api.presetChoices([{ id: 'team-builder', name: '团队施工' }], 'removed-preset', 'dev-plan', T)
1484
+ assert.equal(legacy.find((choice) => choice.value === 'removed-preset').disabled, true)
1485
+ })
1486
+
1487
+ test('client 行为:provider→model 联动取首个模型,旧 provider/model 禁用', async () => {
1488
+ const api = await loadClientTestApi()
1489
+ const T = (cn) => cn
1490
+ const providers = [
1491
+ { provider: 'alpha', name: 'Alpha', models: [{ model: 'a1', name: 'A1' }, { model: 'a2' }] },
1492
+ { provider: 'beta', name: 'Beta', models: [{ model: 'b1' }] },
1493
+ ]
1494
+ assert.equal(api.firstModelOf(providers, 'beta'), 'b1')
1495
+ assert.equal(api.firstModelOf(providers, 'missing'), '')
1496
+
1497
+ const providerOptions = api.providerChoices(providers, 'legacy', T)
1498
+ assert.equal(providerOptions.find((choice) => choice.value === 'legacy').disabled, true)
1499
+ assert.equal(providerOptions.find((choice) => choice.value === 'alpha').label, 'Alpha(alpha)')
1500
+
1501
+ const modelOptions = api.modelChoices(providers[0].models, 'gone', T)
1502
+ assert.equal(modelOptions.find((choice) => choice.value === 'gone').disabled, true)
1503
+ assert.equal(modelOptions.find((choice) => choice.value === 'a1').label, 'A1(a1)')
1504
+ })
1505
+
1506
+ // ── v0.4.0 新增测试(WP5)──────────────────────────────────────────────────
1507
+
1508
+ test('v0.4.0 preset 长度预算与子代理专用模板嵌入主预设', () => {
1509
+ const def = P.buildPresetDefinition({
1510
+ settings: base(),
1511
+ mode: P.resolveDevelopMode({ requestedMode: 'standard' }),
1512
+ })
1513
+ const persona = def.plugins.find((row) => row.id === 'persona').config
1514
+ const total = persona.prefix.length + persona.suffix.length
1515
+ assert.ok(total <= 6000, `persona 总长应 <= 6000,实际 ${total}`)
1516
+ assert.ok(!persona.prefix.includes('ROLE-TEMPLATE:SCOUT:BEGIN'), '不再使用旧的千字长模板标记')
1517
+ assert.ok(persona.prefix.includes('仅给子代理用,不改变主窗自身规则'))
1518
+ assert.ok(persona.prefix.includes('【仅子代理用 · 侦察/复核约束】'))
1519
+ assert.ok(persona.prefix.includes('【仅子代理用 · 文书落盘约束】'))
1520
+ assert.equal(def.plugins.find((r) => r.id === 'tool-subagent-recon').config.agentPreset, 'standard')
1521
+ assert.equal(def.plugins.find((r) => r.id === 'tool-subagent-review').config.agentPreset, 'standard')
1522
+ assert.equal(def.plugins.find((r) => r.id === 'tool-subagent-scribe').config.agentPreset, 'standard')
1523
+ const pruner = def.plugins
1524
+ .find((r) => r.id === 'compaction')
1525
+ .config.find((r) => r.id === 'tool-result-pruner').config
1526
+ assert.deepEqual(pruner, { thresholdChars: 24576, headChars: 16384, tailChars: 4096 })
1527
+ })
1528
+
1529
+ test('v0.4.0 内部轻量子预设插件面:dev-plan-scout 与 dev-plan-scribe 绝不含 Shell/委派', () => {
1530
+ const forbidden = new Set([
1531
+ '@deepseek-ai/dsh-tool-bash',
1532
+ '@deepseek-ai/dsh-tool-pwsh',
1533
+ '@deepseek-ai/dsh-tool-workflow',
1534
+ '@deepseek-ai/dsh-tool-jobs',
1535
+ '@deepseek-ai/dsh-tool-schedule',
1536
+ '@deepseek-ai/dsh-tool-goal',
1537
+ '@deepseek-ai/dsh-tool-skill',
1538
+ '@deepseek-ai/dsh-tool-todo',
1539
+ '@deepseek-ai/dsh-tool-subagent',
1540
+ '@deepseek-ai/dsh-plan-mode',
1541
+ ])
1542
+ const collect = (plugins, out = []) => {
1543
+ for (const row of plugins ?? []) {
1544
+ out.push(row)
1545
+ if (Array.isArray(row?.config)) collect(row.config, out)
1546
+ }
1547
+ return out
1548
+ }
1549
+
1550
+ const scout = P.buildScoutPresetDefinition()
1551
+ assert.equal(scout.id, 'dev-plan-scout')
1552
+ assert.equal(scout.order, 990)
1553
+ const scoutRows = collect(scout.plugins)
1554
+ for (const row of scoutRows) {
1555
+ assert.ok(!forbidden.has(row.name), `dev-plan-scout 不应含 ${row.name}`)
1556
+ }
1557
+ assert.equal(scoutRows.find((r) => r.name === '@deepseek-ai/dsh-tool-fs')?.config?.applyPatch, false)
1558
+ assert.deepEqual(
1559
+ scoutRows.find((r) => r.name === '@deepseek-ai/dsh-tool-fs-search')?.config,
1560
+ { sampleOverCapGlobResults: false },
1561
+ )
1562
+ assert.deepEqual(
1563
+ scoutRows.find((r) => r.name === '@deepseek-ai/dsh-tool-web')?.config,
1564
+ { fetch: true, searchTimeoutMs: 60000 },
1565
+ )
1566
+
1567
+ const scribe = P.buildScribePresetDefinition()
1568
+ assert.equal(scribe.id, 'dev-plan-scribe')
1569
+ assert.equal(scribe.order, 991)
1570
+ const scribeCompaction = scribe.plugins.find((r) => r.id === 'compaction')
1571
+ assert.equal(scribeCompaction?.group, true)
1572
+ assert.deepEqual(scribeCompaction?.isolate, { compaction: true, toolResultPruner: true })
1573
+ const scribeRows = collect(scribe.plugins)
1574
+ for (const row of scribeRows) {
1575
+ assert.ok(!forbidden.has(row.name), `dev-plan-scribe 不应含 ${row.name}`)
1576
+ }
1577
+ assert.equal(scribeRows.find((r) => r.name === '@deepseek-ai/dsh-tool-fs')?.config?.applyPatch, false)
1578
+ assert.ok(!scribeRows.some((r) => r.name === '@deepseek-ai/dsh-tool-fs-search'))
1579
+ assert.ok(!scribeRows.some((r) => r.name === '@deepseek-ai/dsh-tool-web'))
1580
+ })
1581
+
1582
+ test('v0.4.0 不向宿主公开列表注册 scout/scribe 独立预设,避免污染预设选择器', async () => {
1583
+ const registry = createFakeRegistry()
1584
+ const webServer = createFakeWebServer()
1585
+ const ctx = createFakeContext({ registry, webServer })
1586
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
1587
+ await ctx.flush()
1588
+
1589
+ assert.deepEqual(registry.definitions.map((d) => d.id), ['dev-plan'])
1590
+ const mainDef = registry.definitions[0]
1591
+ assert.equal(mainDef.plugins.find((r) => r.id === 'tool-subagent-recon').config.agentPreset, 'standard')
1592
+ assert.equal(mainDef.plugins.find((r) => r.id === 'tool-subagent-review').config.agentPreset, 'standard')
1593
+ assert.equal(mainDef.plugins.find((r) => r.id === 'tool-subagent-scribe').config.agentPreset, 'standard')
1594
+
1595
+ const state = await callRoute(webServer.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
1596
+ assert.equal(state.body.registration, 'active')
1597
+ assert.deepEqual(state.body.internalPresets, { scout: false, scribe: false })
1598
+ await ctx.dispose()
1599
+ })
1600
+
1601
+ test('v0.4.0 mainToolMode 三档矩阵:插件面、persona 规则与严格校验', () => {
1602
+ const neverAllowed = [
1603
+ '@deepseek-ai/dsh-tool-bash',
1604
+ '@deepseek-ai/dsh-tool-pwsh',
1605
+ '@deepseek-ai/dsh-tool-workflow',
1606
+ '@deepseek-ai/dsh-tool-jobs',
1607
+ '@deepseek-ai/dsh-tool-schedule',
1608
+ '@deepseek-ai/dsh-tool-goal',
1609
+ '@deepseek-ai/dsh-tool-skill',
1610
+ '@deepseek-ai/dsh-tool-todo',
1611
+ '@deepseek-ai/dsh-plan-mode',
1612
+ ]
1613
+ const mode = P.resolveDevelopMode({ requestedMode: 'standard' })
1614
+
1615
+ const noneDef = P.buildPresetDefinition({
1616
+ settings: { ...base(), mainToolMode: 'none' },
1617
+ mode,
1618
+ internalPresets: { scout: true, scribe: true },
1619
+ })
1620
+ assert.ok(!noneDef.plugins.some((r) => r.name === '@deepseek-ai/dsh-tool-fs'))
1621
+ assert.ok(!noneDef.plugins.some((r) => r.name === '@deepseek-ai/dsh-tool-fs-search'))
1622
+ assert.match(noneDef.plugins.find((r) => r.id === 'persona').config.prefix, /主窗工具权限(none)/)
1623
+
1624
+ const roDef = P.buildPresetDefinition({
1625
+ settings: { ...base(), mainToolMode: 'readonly' },
1626
+ mode,
1627
+ internalPresets: { scout: true, scribe: true },
1628
+ })
1629
+ assert.ok(!roDef.plugins.some((r) => r.name === '@deepseek-ai/dsh-tool-fs'))
1630
+ const roSearch = roDef.plugins.find((r) => r.name === '@deepseek-ai/dsh-tool-fs-search')
1631
+ assert.deepEqual(roSearch?.config, { sampleOverCapGlobResults: false })
1632
+ assert.match(roDef.plugins.find((r) => r.id === 'persona').config.prefix, /主窗工具权限(readonly)/)
1633
+
1634
+ const editDef = P.buildPresetDefinition({
1635
+ settings: { ...base(), mainToolMode: 'ask-edit' },
1636
+ mode,
1637
+ internalPresets: { scout: true, scribe: true },
1638
+ })
1639
+ const fsRow = editDef.plugins.find((r) => r.name === '@deepseek-ai/dsh-tool-fs')
1640
+ assert.ok(fsRow && fsRow.config?.applyPatch === false)
1641
+ assert.deepEqual(
1642
+ editDef.plugins.find((r) => r.name === '@deepseek-ai/dsh-tool-fs-search')?.config,
1643
+ { sampleOverCapGlobResults: false },
1644
+ )
1645
+ for (const def of [noneDef, roDef, editDef]) {
1646
+ for (const pkgName of neverAllowed) {
1647
+ assert.ok(!def.plugins.some((r) => r.name === pkgName), `主窗永不应挂 ${pkgName}`)
1648
+ }
1649
+ }
1650
+ assert.match(editDef.plugins.find((r) => r.id === 'persona').config.prefix, /主窗工具权限(ask-edit)/)
1651
+
1652
+ // settings 校验
1653
+ for (const validMode of ['none', 'readonly', 'ask-edit']) {
1654
+ const res = S.validateSettings({ mainToolMode: validMode, mainStepWarnThreshold: 2 })
1655
+ assert.equal(res.issues, undefined)
1656
+ assert.equal(res.value.mainToolMode, validMode)
1657
+ }
1658
+ assert.ok(S.validateSettings({ mainToolMode: 'full-shell' }).issues.some((i) => i.path[0] === 'mainToolMode'))
1659
+ assert.ok(S.validateSettings({ mainStepWarnThreshold: 1 }).issues.some((i) => i.path[0] === 'mainStepWarnThreshold'))
1660
+ assert.ok(S.validateSettings({ mainStepWarnThreshold: 31 }).issues.some((i) => i.path[0] === 'mainStepWarnThreshold'))
1661
+ assert.ok(S.validateSettings({ mainStepWarnThreshold: 4.5 }).issues.some((i) => i.path[0] === 'mainStepWarnThreshold'))
1662
+ })
1663
+
1664
+ test('v0.4.0 index.js 性能优化:免冗余二次复检、ETag 304 与空闲预热 modelCatalog', async () => {
1665
+ // 1) deep-ptc 首次命中后不再在 2s 后冗余触发第二次 registry.list()
1666
+ let listCalls = 0
1667
+ const registry = createFakeRegistry({ rows: [{ id: 'deep-ptc' }] })
1668
+ registry.list = async () => {
1669
+ listCalls += 1
1670
+ return [{ id: 'deep-ptc' }]
1671
+ }
1672
+ const webServer = createFakeWebServer()
1673
+ let modelCalls = 0
1674
+ const llm = {
1675
+ listProviders: () => [{ id: 'p', name: 'P' }],
1676
+ listModels: async () => {
1677
+ modelCalls += 1
1678
+ return [{ id: 'm', name: 'M' }]
1679
+ },
1680
+ }
1681
+ const ctx = createFakeContext({ registry, webServer, llm })
1682
+ index.apply(
1683
+ ctx.ctx,
1684
+ { ...base(), developMode: 'deep-ptc' },
1685
+ { verificationDelayMs: 40, prewarmDelayMs: 10 },
1686
+ )
1687
+ await ctx.flush()
1688
+ await sleep(90)
1689
+ await ctx.flush()
1690
+ assert.equal(listCalls, 1, '首次已找到目标 preset 时不应触发冗余二次 registry.list()')
1691
+ assert.equal(modelCalls, 1, '空闲预热应预先枚举一次模型目录')
1692
+
1693
+ // 2) 首次 /state 直接命中已预热 modelCatalog,且带 ETag 支持 304
1694
+ const handler = webServer.handlers.get('/plugins/dev-plan-presets/state')
1695
+ const first = await callRoute(handler, 'GET')
1696
+ assert.equal(first.code, 200)
1697
+ assert.equal(first.body.modelCatalog.checked, true)
1698
+ const etag = first.headers.etag
1699
+ assert.ok(etag, '响应头应包含 etag')
1700
+
1701
+ const notModified = await callRoute(handler, 'GET', undefined, { 'if-none-match': etag })
1702
+ assert.equal(notModified.code, 304)
1703
+ assert.equal(notModified.body, null)
1704
+ assert.equal(notModified.headers.etag, etag)
1705
+ await ctx.dispose()
1706
+ })
1707
+
1708
+ test('v0.4.0 guard.js 优化:stopped 快速拒绝、effect 释放清理与主会话步数软提醒', async () => {
1709
+ // 1) stopped=true 时直接 reject,不再调 next()
1710
+ const registry = createFakeRegistry()
1711
+ const child = createFakeAgent({ id: 'child-fast', parentSession: 'main', origin: 'subagent', current: undefined })
1712
+ const parent = createFakeAgent({
1713
+ id: 'main',
1714
+ agentPreset: 'dev-plan',
1715
+ current: { provider: 'expensive', model: 'main' },
1716
+ })
1717
+ const ctx = createFakeContext({
1718
+ registry,
1719
+ agents: { get: (id) => (id === 'main' ? parent.agent : child.agent) },
1720
+ })
1721
+ index.apply(ctx.ctx, base(), { verificationDelayMs: 0 })
1722
+ await ctx.flush()
1723
+ ctx.listeners.get('agent/created')[0]({ agent: child.agent })
1724
+ let nextCount = 0
1725
+ const next = async () => {
1726
+ nextCount += 1
1727
+ return { kind: 'enter', messages: [] }
1728
+ }
1729
+ const firstDecision = await child.stepHandlers[0](
1730
+ { modelSelection: { provider: 'other', model: 'bad' } },
1731
+ next,
1732
+ )
1733
+ assert.deepEqual(firstDecision, { kind: 'reject' })
1734
+ assert.equal(nextCount, 1)
1735
+ const secondDecision = await child.stepHandlers[0](
1736
+ { modelSelection: { provider: 'other', model: 'bad' } },
1737
+ next,
1738
+ )
1739
+ assert.deepEqual(secondDecision, { kind: 'reject' })
1740
+ assert.equal(nextCount, 1, 'stopped=true 后应短路,不再调用 next()')
1741
+
1742
+ // 2) agent.ctx.effect 清理时同步移除 stepHandler,不依赖 agent/disposed
1743
+ for (const dispose of child.agentEffects) dispose()
1744
+ assert.equal(child.stepHandlers.length, 0)
1745
+ await ctx.dispose()
1746
+
1747
+ // 3) mainToolMode='ask-edit' 下主会话步数超阈值触发温和提醒(不 select、不 cancel、不 reject)
1748
+ const budgetRegistry = createFakeRegistry()
1749
+ const mainAgent = createFakeAgent({
1750
+ id: 'main-budget',
1751
+ agentPreset: 'dev-plan',
1752
+ current: { provider: 'expensive', model: 'main' },
1753
+ })
1754
+ const budgetCtx = createFakeContext({ registry: budgetRegistry })
1755
+ index.apply(
1756
+ budgetCtx.ctx,
1757
+ { ...base(), modelGuardMode: 'off', mainToolMode: 'ask-edit', mainStepWarnThreshold: 2 },
1758
+ { verificationDelayMs: 0 },
1759
+ )
1760
+ await budgetCtx.flush()
1761
+ const created = budgetCtx.listeners.get('agent/created')
1762
+ assert.ok(Array.isArray(created) && created.length >= 1, 'mainToolMode!=none 时即便 guard=off 也应挂载主窗步数提醒')
1763
+ created[0]({ agent: mainAgent.agent })
1764
+ assert.equal(mainAgent.stepHandlers.length, 1)
1765
+
1766
+ for (let i = 0; i < 4; i += 1) {
1767
+ const decision = await mainAgent.stepHandlers[0](
1768
+ { turnId: 't1' },
1769
+ async () => ({ kind: 'enter', messages: [] }),
1770
+ )
1771
+ assert.equal(decision.kind, 'enter', '主会话步数提醒永不 reject')
1772
+ }
1773
+ assert.equal(mainAgent.selects.length, 0, '主会话永不被 select')
1774
+ assert.equal(mainAgent.cancelled.length, 0, '主会话永不被 cancel')
1775
+ assert.equal(mainAgent.injected.length, 1, '同回合超阈值只温和提醒 1 次')
1776
+ assert.match(mainAgent.injected[0].content[0].text, /转交 recon \/ develop/)
1777
+
1778
+ // 新回合重置计数
1779
+ for (let i = 0; i < 3; i += 1) {
1780
+ await mainAgent.stepHandlers[0]({ turnId: 't2' }, async () => ({ kind: 'enter', messages: [] }))
1781
+ }
1782
+ assert.equal(mainAgent.injected.length, 2)
1783
+ await budgetCtx.dispose()
1784
+ })
1785
+
1786
+ test('v0.4.0 client.js 行为与优化契约:禁用全部内部预设、304 跳过重渲染与新字段', async () => {
1787
+ const api = await loadClientTestApi()
1788
+ const T = (cn) => cn
1789
+ const choices = api.presetChoices(
1790
+ [
1791
+ { id: 'dev-plan', name: '开发规划与交付' },
1792
+ { id: 'dev-plan-scout', name: '内部侦察' },
1793
+ { id: 'dev-plan-scribe', name: '内部文书' },
1794
+ { id: 'deep-ptc', name: '深度 PTC' },
1795
+ ],
1796
+ 'standard',
1797
+ ['dev-plan', 'dev-plan-scout', 'dev-plan-scribe'],
1798
+ T,
1799
+ )
1800
+ const byValue = Object.fromEntries(choices.map((c) => [c.value, c]))
1801
+ assert.equal(byValue['dev-plan'].disabled, true)
1802
+ assert.equal(byValue['dev-plan-scout'].disabled, true)
1803
+ assert.equal(byValue['dev-plan-scribe'].disabled, true)
1804
+ assert.equal(byValue['deep-ptc'].disabled, undefined)
1805
+
1806
+ assert.equal(api.isStateConverged(null), false)
1807
+ assert.equal(
1808
+ api.isStateConverged({
1809
+ registration: 'active',
1810
+ modelCatalog: { checked: false },
1811
+ presets: { checked: true },
1812
+ }),
1813
+ false,
1814
+ )
1815
+ assert.equal(
1816
+ api.isStateConverged({
1817
+ registration: 'active',
1818
+ modelCatalog: { checked: true },
1819
+ presets: { checked: true },
1820
+ }),
1821
+ true,
1822
+ )
1823
+
1824
+ const clientSource = readFileSync(join(ROOT, 'client.js'), 'utf8')
1825
+ for (const marker of [
1826
+ 'if-none-match',
1827
+ '304',
1828
+ 'stateVersion',
1829
+ 'FAST_POLL_MS = 700',
1830
+ 'IDLE_POLL_MS = 30000',
1831
+ 'visibilitychange',
1832
+ 'document.hidden',
1833
+ 'AbortController',
1834
+ 'React.useMemo',
1835
+ 'timersRef',
1836
+ 'mainToolMode',
1837
+ 'mainStepWarnThreshold',
1838
+ 'scheduleNextRef',
1839
+ 'stateTag',
1840
+ '超过阈值仅提示转交子代理,绝不强制中断或改换主模型',
1841
+ ]) {
1842
+ assert.ok(clientSource.includes(marker), `client.js 缺少 v0.4.0 标记:${marker}`)
1843
+ }
1844
+ assert.ok(!/setInterval\(/.test(clientSource), 'client.js 不应再使用固定 setInterval 轮询')
1845
+
1846
+ const mode = P.resolveDevelopMode({ requestedMode: 'standard' })
1847
+ assert.doesNotMatch(P.buildDescription(mode, 'ask-edit'), /永不亲自写代码/)
1848
+ assert.match(P.buildDescription(mode, 'ask-edit'), /局部微改/)
1849
+ assert.match(P.buildDescription(mode, 'readonly'), /只读检索/)
1850
+ })
1851
+
1852
+ test('v0.4.0 插件重载后不同实例相同 stateVersion 不返回 304', async () => {
1853
+ const webServer1 = createFakeWebServer()
1854
+ const ctx1 = createFakeContext({ registry: createFakeRegistry(), webServer: webServer1 })
1855
+ index.apply(ctx1.ctx, base(), { verificationDelayMs: 0, prewarmModelCatalog: false })
1856
+ await ctx1.flush()
1857
+ const first = await callRoute(webServer1.handlers.get('/plugins/dev-plan-presets/state'), 'GET')
1858
+ assert.equal(first.code, 200)
1859
+ assert.ok(typeof first.body.stateTag === 'string' && first.body.stateTag.length > 0)
1860
+ await ctx1.dispose()
1861
+
1862
+ const webServer2 = createFakeWebServer()
1863
+ const ctx2 = createFakeContext({ registry: createFakeRegistry(), webServer: webServer2 })
1864
+ index.apply(ctx2.ctx, base(), { verificationDelayMs: 0, prewarmModelCatalog: false })
1865
+ await ctx2.flush()
1866
+ const handler2 = webServer2.handlers.get('/plugins/dev-plan-presets/state')
1867
+ const second = await callRoute(handler2, 'GET', undefined, { 'if-none-match': first.headers.etag })
1868
+ assert.equal(second.code, 200, '不同插件实例即使 stateVersion 相同也不应命中旧实例 ETag 返回 304')
1869
+ assert.equal(second.body.stateVersion, first.body.stateVersion)
1870
+ assert.notEqual(second.body.stateTag, first.body.stateTag)
1871
+ assert.notEqual(second.headers.etag, first.headers.etag)
1872
+ await ctx2.dispose()
1873
+ })
1874
+
1875
+ test('v0.4.0 guard 注入自身 source 消息不重置步数提醒', async () => {
1876
+ const registry = createFakeRegistry()
1877
+ const messages = [{ role: 'user', id: 'u1', content: 'start' }]
1878
+ const mainAgent = createFakeAgent({
1879
+ id: 'main-self-msg',
1880
+ agentPreset: 'dev-plan',
1881
+ current: { provider: 'expensive', model: 'main' },
1882
+ })
1883
+ mainAgent.agent.session.messages = messages
1884
+ mainAgent.agent.inject = (msg) => {
1885
+ mainAgent.injected.push(msg)
1886
+ messages.push({ role: 'user', id: `inj-${messages.length}`, ...msg })
1887
+ }
1888
+
1889
+ const ctx = createFakeContext({ registry })
1890
+ index.apply(
1891
+ ctx.ctx,
1892
+ { ...base(), modelGuardMode: 'off', mainToolMode: 'ask-edit', mainStepWarnThreshold: 2 },
1893
+ { verificationDelayMs: 0, prewarmModelCatalog: false },
1894
+ )
1895
+ await ctx.flush()
1896
+ ctx.listeners.get('agent/created')[0]({ agent: mainAgent.agent })
1897
+
1898
+ // 没有传 turnId,靠 session.messages 识别回合;第 3 步触发注入后,第 4/5/6 步不应重置再提醒
1899
+ for (let i = 0; i < 6; i += 1) {
1900
+ const decision = await mainAgent.stepHandlers[0]({}, async () => ({ kind: 'enter', messages: [] }))
1901
+ assert.equal(decision.kind, 'enter')
1902
+ }
1903
+ assert.equal(mainAgent.injected.length, 1, '自身注入的 source.kind=dev-plan-presets 消息不应重置当轮计数')
1904
+
1905
+ // 真正的新用户消息到来后,计数重置并可在超阈值后再次提醒一次
1906
+ messages.push({ role: 'user', id: 'u2', content: 'next turn' })
1907
+ for (let i = 0; i < 3; i += 1) {
1908
+ await mainAgent.stepHandlers[0]({}, async () => ({ kind: 'enter', messages: [] }))
1909
+ }
1910
+ assert.equal(mainAgent.injected.length, 2)
1911
+ await ctx.dispose()
1912
+ })