dsh-vscode-mode 0.38.0 → 0.40.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.
Files changed (66) hide show
  1. package/README.md +38 -33
  2. package/lib/client.js +87 -68
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +11406 -4920
  5. package/lib/index.js.map +1 -1
  6. package/package.json +3 -2
  7. package/skills/dsh-vscodemode-html-plan/SKILL.md +44 -42
  8. package/skills/dsh-vscodemode-test-check/SKILL.md +82 -0
  9. package/src/archiveDb.ts +24 -0
  10. package/src/attachmentBytes.ts +84 -0
  11. package/src/client/htmlPlan/HtmlPlanModeChip.ts +181 -0
  12. package/src/client/htmlPlan/HtmlPlanPanel.ts +230 -61
  13. package/src/client/htmlPlan/planActions.ts +38 -8
  14. package/src/client/htmlPlan/planPage.ts +111 -9
  15. package/src/client/index.ts +9 -0
  16. package/src/client/openReceipt.ts +5 -2
  17. package/src/client/planBridge.ts +27 -2
  18. package/src/client/planState.ts +51 -4
  19. package/src/client/sidebar/panels/TestCheckPanel.ts +485 -0
  20. package/src/client/sidebar/panels/useTestCheckData.ts +414 -0
  21. package/src/client/sidebar/types.ts +2 -0
  22. package/src/client/state/diffSummary.ts +3 -0
  23. package/src/client/styles/editor.css +91 -0
  24. package/src/client/testCheck/TestCheckChip.ts +181 -0
  25. package/src/client/testCheck/TestCheckPanel.ts +339 -0
  26. package/src/client/testCheckPanelState.ts +173 -0
  27. package/src/client/ui/EditorView.ts +77 -7
  28. package/src/client/ui/McpSettings.ts +2 -2
  29. package/src/client/ui/OfficialReview.ts +6 -4
  30. package/src/htmlPlanAttachments.ts +4 -1
  31. package/src/htmlPlanCommand.ts +87 -235
  32. package/src/htmlPlanGuidance.ts +67 -0
  33. package/src/htmlPlanMode.ts +547 -0
  34. package/src/index.ts +28 -55
  35. package/src/officialCapture.ts +58 -9
  36. package/src/pending/externalCapture.ts +195 -401
  37. package/src/pending/kernel.ts +24 -1
  38. package/src/pending/persist.ts +109 -22
  39. package/src/pending/provenance.ts +5 -28
  40. package/src/pending/store.ts +109 -100
  41. package/src/pending/tracking.ts +81 -0
  42. package/src/pendingCompat.ts +26 -1
  43. package/src/pendingRpc.ts +8 -56
  44. package/src/planAutoPage.ts +306 -0
  45. package/src/planPagePack.ts +148 -0
  46. package/src/registry.ts +7 -2
  47. package/src/reviewDb.ts +1 -1
  48. package/src/reviewRpc.ts +14 -6
  49. package/src/rpc.ts +34 -0
  50. package/src/shared/htmlPlanMode.ts +26 -0
  51. package/src/shared/pendingReview.ts +15 -7
  52. package/src/shared/review.ts +5 -0
  53. package/src/shared/rpc.ts +53 -7
  54. package/src/shared/testCheck.ts +759 -0
  55. package/src/shared/testCheckHtml.ts +276 -0
  56. package/src/shared/testCheckPolicyDefault.ts +37 -0
  57. package/src/shared/testCheckSnippets.ts +197 -0
  58. package/src/store.ts +17 -1
  59. package/src/testCheckCommand.ts +287 -0
  60. package/src/testCheckGuidance.ts +79 -0
  61. package/src/testCheckMode.ts +654 -0
  62. package/src/testCheckPolicy.ts +141 -0
  63. package/src/testCheckRpc.ts +196 -0
  64. package/src/testCheckStore.ts +822 -0
  65. package/src/pending/externalAlign.ts +0 -297
  66. package/src/pending/vcs.ts +0 -584
@@ -0,0 +1,654 @@
1
+ /**
2
+ * dsh-vscode-mode host — 测试验收模式(`/test-check`,独立模式,结构对齐 `htmlPlanMode.ts`)。
3
+ *
4
+ * 四件套:
5
+ * 1. `sessionProjections` 注册 `test-check` 投影:折叠 `/test-check` 命令事件,得到 `{ active, entered, id }`;
6
+ * `entered` 粘性,让规则段落「首次进入后常驻」。
7
+ * 2. 两条系统提示 section:`test-check:policy`(常驻规则,首句限定只在活跃时适用)与
8
+ * `test-check:status`(每个请求按 active 输出一句话)。
9
+ * 3. 两个工具:`test_check_report`(每验一项必须带证据上报)与 `test_check_finish`(导出快照),
10
+ * 从首次进入起常驻准入(`when`),执行时再校验模式活跃。
11
+ * 4. `/test-check [off|任务]` 命令:切模式 + 建单目录 + 把任务送进会话。
12
+ *
13
+ * 与官方 `/plan`、`/html-plan` 的关系:本模式独立,不碰官方 plan 投影;成功进入那两者时
14
+ * 本模式折回 inactive(三模式互斥,同一时刻只有一个在管规则)。
15
+ * @author ddj 2026年11月25号
16
+ */
17
+ import { z } from 'zod'
18
+ import { log } from './log.js'
19
+ import { loadHostModule } from './hostImport.js'
20
+ import { cwdOfSession, type Ctx } from './store.js'
21
+ import { checkCommand, type CheckInvocation, type CheckStage } from './testCheckCommand.js'
22
+ import { testCheckPolicyText, testCheckStatusText } from './testCheckGuidance.js'
23
+ import { exportSnapshot, projectRootOf, writeEvent } from './testCheckStore.js'
24
+ import { policyTextOf } from './testCheckPolicy.js'
25
+ import {
26
+ TEST_CHECK_COMMAND,
27
+ TEST_CHECK_DEFAULT_ID,
28
+ TEST_CHECK_FINISH_TOOL,
29
+ TEST_CHECK_MODE_KEY,
30
+ TEST_CHECK_OFF_LINE,
31
+ TEST_CHECK_REPORT_TOOL,
32
+ normalizeStatus,
33
+ parseCheckInput,
34
+ testCheckIdOf,
35
+ type TestCheckCounts,
36
+ type TestCheckEvidence,
37
+ } from './shared/testCheck.js'
38
+
39
+ //region 结构面
40
+
41
+ /** 投影状态(只描述模式本身)。 */
42
+ export interface CheckModeState {
43
+ /** 模式当前是否活跃。 */
44
+ active: boolean
45
+ /** 是否进入过模式(粘性;规则段落据此常驻)。 */
46
+ entered: boolean
47
+ /** 当前单子 id(退出后保留,便于 chip/页签继续显示同一张单)。 */
48
+ id: string
49
+ /** 尚未结算的命令事件(run 与 done 配对用)。 */
50
+ running: { commandId: string; off: boolean; id: string } | null
51
+ }
52
+
53
+ /** 投影初始状态。 */
54
+ export const TEST_CHECK_INITIAL: CheckModeState = { active: false, entered: false, id: '', running: null }
55
+
56
+ /** 投影定义里运行时的最小结构面。 */
57
+ interface ProjectionHandleLike {
58
+ stateOf: (session: unknown) => unknown
59
+ }
60
+
61
+ /** 会话投影服务最小结构面。 */
62
+ interface ProjectionsLike {
63
+ register?: (definition: unknown) => Promise<ProjectionHandleLike>
64
+ }
65
+
66
+ /** 系统提示服务最小结构面。 */
67
+ interface SystemPromptLike {
68
+ section?: (spec: unknown) => unknown
69
+ getSectionOrder?: (name: string) => number
70
+ }
71
+
72
+ /** 工具服务最小结构面。 */
73
+ interface ToolsLike {
74
+ register?: (definition: unknown, options?: { when?: (context: { agent: { session: unknown } }) => boolean }) => unknown
75
+ }
76
+
77
+ /** 命令服务最小结构面。 */
78
+ interface CommandsLike {
79
+ register?: (definition: unknown) => unknown
80
+ execute?: (agent: unknown, line: string, attachments: readonly unknown[], signal?: AbortSignal) => Promise<{ result?: { kind?: string; text?: string } } | undefined>
81
+ }
82
+
83
+ /** 工具执行上下文最小结构面。 */
84
+ interface ToolExec {
85
+ agent?: { session?: unknown } | undefined
86
+ signal?: AbortSignal
87
+ }
88
+
89
+ /** 安装选项(测试可替换宿主模块加载与消息构造)。 */
90
+ export interface CheckModeOptions {
91
+ /** 把纯文本包成宿主用户消息;缺省从 `@deepseek-ai/dsh-llm` 取 createUserMessage。 */
92
+ buildUserMessage?: (text: string) => unknown
93
+ /** 附件准备(默认落盘到 `.dsh/test-check/<id>/assets/`);测试可替换。 */
94
+ prepareAttachments?: (invocation: CheckInvocation, id: string) => Promise<CheckStage>
95
+ /** 宿主模块加载(测试可注入假的)。 */
96
+ loadModule?: (specifier: string) => Promise<unknown>
97
+ /** 宿主上下文(取会话工作区与附件服务)。 */
98
+ hostCtx?: unknown
99
+ }
100
+
101
+ //endregion
102
+
103
+ //region 投影折叠(纯)
104
+
105
+ /**
106
+ * 折叠一条会话事件到模式状态。
107
+ *
108
+ * 只认 `command/run` 与配对的 `command/done`:本命令成功则按 off 收尾;进入官方 `/plan`
109
+ * 或 `/html-plan` 时把本模式折回 inactive(同一时刻只有一个模式在管规则)。
110
+ * @author ddj 2026年11月25号
111
+ * @param state 上一状态
112
+ * @param event 会话事件(只读 type/data)
113
+ * @returns 新状态;不关心的事件返回原引用
114
+ */
115
+ export function foldCheckMode(state: CheckModeState, event: unknown): CheckModeState {
116
+ const row = event !== null && typeof event === 'object' ? event as { type?: unknown; data?: unknown } : {}
117
+ const type = typeof row.type === 'string' ? row.type : ''
118
+ const data = row.data !== null && typeof row.data === 'object' ? row.data as Record<string, unknown> : {}
119
+
120
+ if (type === 'command/run') {
121
+ const name = typeof data.name === 'string' ? data.name : ''
122
+ const args = typeof data.args === 'string' ? data.args : ''
123
+ const commandId = typeof data.commandId === 'string' ? data.commandId : ''
124
+ const keyword = args.trim().toLowerCase()
125
+ if (name === TEST_CHECK_COMMAND) {
126
+ const parsed = parseCheckInput(args)
127
+ const id = parsed.action === 'off' ? '' : testCheckIdOf(parsed.task)
128
+ return { ...state, running: { commandId, off: parsed.action === 'off', id } }
129
+ }
130
+ if (name === 'plan' || name === 'html-plan') {
131
+ // 另一个模式被「进入」时关闭本模式;它们自己的 off 动作不算。
132
+ if (keyword === 'off') return state
133
+ return { ...state, running: { commandId, off: true, id: '' } }
134
+ }
135
+ return state
136
+ }
137
+
138
+ if (type === 'command/done') {
139
+ const running = state.running
140
+ if (!running) return state
141
+ if (String(data.commandId ?? '') !== running.commandId) return state
142
+ if (data.kind !== 'success') return { ...state, running: null }
143
+ if (running.off) return { ...state, active: false, running: null }
144
+ return { active: true, entered: true, id: running.id, running: null }
145
+ }
146
+
147
+ return state
148
+ }
149
+
150
+ /** 投影定义(key/版本/校验/折叠/wire 视图)。 */
151
+ export const checkProjectionDefinition = {
152
+ key: TEST_CHECK_MODE_KEY,
153
+ stateVersion: 1,
154
+ stateSchema: z.object({
155
+ active: z.boolean(),
156
+ entered: z.boolean(),
157
+ id: z.string(),
158
+ running: z.object({ commandId: z.string(), off: z.boolean(), id: z.string() }).strict().nullable(),
159
+ }).strict(),
160
+ init: (): CheckModeState => TEST_CHECK_INITIAL,
161
+ apply: (state: CheckModeState, event: unknown): CheckModeState => foldCheckMode(state, event),
162
+ wire: {
163
+ viewSchema: z.object({ active: z.boolean(), id: z.string() }).strict(),
164
+ view: (state: CheckModeState) => ({ active: state.active, id: state.id }),
165
+ },
166
+ }
167
+
168
+ //endregion
169
+
170
+ //region 工具定义
171
+
172
+ /** 上报工具依赖。 */
173
+ export interface ReportToolDeps {
174
+ /** 会话工作区。 */
175
+ cwdOf: (session: unknown) => string | null
176
+ /** 会话当前单子 id。 */
177
+ idOf: (session: unknown) => string
178
+ /** 模式是否活跃。 */
179
+ activeOf: (session: unknown) => boolean
180
+ }
181
+
182
+ /** 上报工具回执。 */
183
+ export interface ReportToolResult {
184
+ ok: boolean
185
+ item?: string
186
+ status?: string
187
+ file?: string
188
+ counts?: TestCheckCounts
189
+ error?: string
190
+ }
191
+
192
+ /** 上报工具参数。 */
193
+ interface ReportArgs {
194
+ item?: unknown
195
+ status?: unknown
196
+ summary?: unknown
197
+ kind?: unknown
198
+ command?: unknown
199
+ exitCode?: unknown
200
+ path?: unknown
201
+ }
202
+
203
+ /**
204
+ * 构造 `test_check_report` 定义(每验一项必须调用它,且必须带证据)。
205
+ * @author ddj 2026年11月25号
206
+ * @param deps 会话解析与模式状态
207
+ * @returns 工具定义参数
208
+ */
209
+ export function reportToolOptions(deps: ReportToolDeps) {
210
+ /**
211
+ * 上报一条结果;参数问题返回可读原因,不抛错。
212
+ * @author ddj 2026年11月25号
213
+ * @param args 模型参数
214
+ * @param exec 执行上下文
215
+ * @returns 回执
216
+ */
217
+ async function execute(args: ReportArgs, exec: ToolExec): Promise<ReportToolResult> {
218
+ const session = exec?.agent?.session
219
+ if (!deps.activeOf(session)) return { ok: false, error: '测试验收模式未激活:先 /test-check 进入模式' }
220
+ const cwd = deps.cwdOf(session)
221
+ if (!cwd) return { ok: false, error: '上报需要所属会话的工作区' }
222
+ if (exec?.signal?.aborted) return { ok: false, error: '上报已取消' }
223
+
224
+ const item = typeof args?.item === 'string' ? args.item.trim() : ''
225
+ const status = normalizeStatus(args?.status)
226
+ const summary = typeof args?.summary === 'string' ? args.summary.trim() : ''
227
+ if (!item) return { ok: false, error: 'item 必填:写验收单里的测试点 id(如 settings.claude-style.004)' }
228
+ if (!status) return { ok: false, error: 'status 必填,只能是 pass / fail / blocked / skip' }
229
+ if (!summary) return { ok: false, error: 'summary 必填:它就是这次验证的证据(测试名、命令或日志路径)' }
230
+
231
+ const evidence: TestCheckEvidence = {
232
+ kind: typeof args.kind === 'string' && args.kind.trim() ? args.kind.trim() : 'test',
233
+ summary,
234
+ }
235
+ if (typeof args.command === 'string' && args.command.trim()) evidence.command = args.command.trim()
236
+ if (typeof args.exitCode === 'number' && Number.isFinite(args.exitCode)) evidence.exitCode = args.exitCode
237
+ if (typeof args.path === 'string' && args.path.trim()) evidence.path = args.path.trim()
238
+
239
+ try {
240
+ const written = await writeEvent({
241
+ cwd,
242
+ id: deps.idOf(session),
243
+ item,
244
+ status,
245
+ evidence,
246
+ })
247
+ return { ok: true, item, status, file: written.file, counts: written.view.counts }
248
+ } catch (error) {
249
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
250
+ }
251
+ }
252
+
253
+ /** @author ddj 2026年11月25号 @param _args 参数 @param result 回执 @returns 模型可见文本 */
254
+ function render(_args: ReportArgs, result: ReportToolResult): Array<{ type: string; text: string }> {
255
+ if (!result?.ok) return [{ type: 'text', text: '上报未记录:' + String(result?.error ?? '未知原因') }]
256
+ const counts = result.counts
257
+ const tally = counts ? '(通过 ' + String(counts.pass) + '/' + String(counts.total) + ' · 失败 ' + String(counts.fail) + ' · 需复验 ' + String(counts.stale) + ')' : ''
258
+ return [{ type: 'text', text: '已记录 ' + String(result.item) + ' = ' + String(result.status) + ' → ' + String(result.file ?? '') + tally }]
259
+ }
260
+
261
+ return {
262
+ name: TEST_CHECK_REPORT_TOOL,
263
+ description: 'Record one acceptance result with evidence. Every verified item must be reported here; '
264
+ + 'a pass without evidence does not count. Args: item (id from items.json), status (pass|fail|blocked|skip), '
265
+ + 'summary (the evidence: test name, command or log path).',
266
+ parameters: {
267
+ item: { type: 'string', required: true, description: 'Test point id from items.json, e.g. settings.claude-style.004.' },
268
+ status: { type: 'string', required: true, description: 'pass | fail | blocked | skip.' },
269
+ summary: { type: 'string', required: true, description: 'The evidence in one line: test file and counts, command, or log path.' },
270
+ kind: { type: 'string', description: 'Evidence kind: test | command | file | log | manual (default test).' },
271
+ command: { type: 'string', description: 'The command that produced the evidence, if any.' },
272
+ exitCode: { type: 'number', description: 'Exit code of that command.' },
273
+ path: { type: 'string', description: 'Evidence file path in the workspace (relative to the project root).' },
274
+ },
275
+ output: { schema: { type: 'json' }, render },
276
+ isConcurrencySafe: false,
277
+ execute,
278
+ }
279
+ }
280
+
281
+ /** 收尾工具依赖。 */
282
+ export interface FinishToolDeps {
283
+ /** 会话工作区。 */
284
+ cwdOf: (session: unknown) => string | null
285
+ /** 会话当前单子 id。 */
286
+ idOf: (session: unknown) => string
287
+ /** 模式是否活跃。 */
288
+ activeOf: (session: unknown) => boolean
289
+ /** 退出模式(执行 `/test-check off`)。 */
290
+ exitMode: (agent: unknown, signal?: AbortSignal) => Promise<{ ok: boolean; error?: string }>
291
+ }
292
+
293
+ /** 收尾工具回执。 */
294
+ export interface FinishToolResult {
295
+ ok: boolean
296
+ path?: string
297
+ counts?: TestCheckCounts
298
+ /** 导出后是否已退出模式。 */
299
+ exited?: boolean
300
+ /** 退出失败的原因(导出本身仍然成功)。 */
301
+ exitError?: string
302
+ error?: string
303
+ }
304
+
305
+ /**
306
+ * 构造 `test_check_finish` 定义:导出 `docs/acceptance-<id>.html`,默认随后退出模式。
307
+ *
308
+ * 收尾就是流程终点,所以默认把模式一起关掉;要留在模式里继续补验,带 `stay: true`。
309
+ * 退出失败不影响导出结果,只在回执里说明并让模型手动 `/test-check off`。
310
+ * @author ddj 2026年11月25号
311
+ * @param deps 会话解析、模式状态与退出动作
312
+ * @returns 工具定义参数
313
+ */
314
+ export function finishToolOptions(deps: FinishToolDeps) {
315
+ /**
316
+ * 导出快照,默认随后退出模式;失败返回可读原因。
317
+ * @author ddj 2026年11月25号
318
+ * @param args 参数(stay 为真时保留模式)
319
+ * @param exec 执行上下文
320
+ * @returns 回执
321
+ */
322
+ async function execute(args: { stay?: unknown }, exec: ToolExec): Promise<FinishToolResult> {
323
+ const session = exec?.agent?.session
324
+ if (!deps.activeOf(session)) return { ok: false, error: '测试验收模式未激活:先 /test-check 进入模式' }
325
+ const cwd = deps.cwdOf(session)
326
+ if (!cwd) return { ok: false, error: '导出需要所属会话的工作区' }
327
+ let result: { path: string; view: { counts: TestCheckCounts } }
328
+ try {
329
+ result = await exportSnapshot({ cwd, id: deps.idOf(session) })
330
+ } catch (error) {
331
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
332
+ }
333
+
334
+ if (args?.stay === true) return { ok: true, path: result.path, counts: result.view.counts, exited: false }
335
+ const exited = await deps.exitMode(exec?.agent, exec?.signal)
336
+ return exited.ok
337
+ ? { ok: true, path: result.path, counts: result.view.counts, exited: true }
338
+ : { ok: true, path: result.path, counts: result.view.counts, exited: false, exitError: exited.error ?? '未知原因' }
339
+ }
340
+
341
+ /** @author ddj 2026年11月25号 @param _args 参数 @param result 回执 @returns 模型可见文本 */
342
+ function render(_args: unknown, result: FinishToolResult): Array<{ type: string; text: string }> {
343
+ if (!result?.ok) return [{ type: 'text', text: '导出失败:' + String(result?.error ?? '未知原因') }]
344
+ const counts = result.counts
345
+ const tally = counts
346
+ ? '(通过 ' + String(counts.pass) + '/' + String(counts.total)
347
+ + (counts.todo + counts.stale > 0 ? ',未验 ' + String(counts.todo) + ' · 需复验 ' + String(counts.stale) : '')
348
+ + ')'
349
+ : ''
350
+ const mode = result.exited
351
+ ? ';测试验收模式已退出。'
352
+ : result.exitError
353
+ ? ';模式没能自动退出(' + result.exitError + '),请手动执行 /test-check off。'
354
+ : ';模式保留(stay),验完用 /test-check off 离开。'
355
+ return [{ type: 'text', text: '验收快照已导出:' + String(result.path ?? '') + tally + mode }]
356
+ }
357
+
358
+ return {
359
+ name: TEST_CHECK_FINISH_TOOL,
360
+ description: 'Export the acceptance sheet to docs/acceptance-<id>.html and leave test-check mode. '
361
+ + 'Pass stay: true to keep the mode active for one more round of verification.',
362
+ parameters: {
363
+ stay: { type: 'boolean', description: 'Keep test-check mode active after exporting (default false: finish also leaves the mode).' },
364
+ },
365
+ output: { schema: { type: 'json' }, render },
366
+ isConcurrencySafe: false,
367
+ execute,
368
+ }
369
+ }
370
+
371
+ //endregion
372
+
373
+ //region 装配
374
+
375
+ /**
376
+ * 从(注入作用域的)宿主上下文取服务:优先 `ctx.get`,退回同名属性。
377
+ * @author ddj 2026年11月25号
378
+ * @param ctx 宿主上下文
379
+ * @param name 服务名
380
+ * @returns 服务实例或 undefined
381
+ */
382
+ function serviceOf(ctx: unknown, name: string): unknown {
383
+ const scope = ctx as { get?: (key: string) => unknown } | undefined
384
+ if (scope && typeof scope.get === 'function') {
385
+ try {
386
+ const value = scope.get(name)
387
+ if (value !== undefined) return value
388
+ } catch {
389
+ /* 未注入的服务在旧宿主上可能抛错:退回属性读取 */
390
+ }
391
+ }
392
+ return (ctx as Record<string, unknown> | undefined)?.[name]
393
+ }
394
+
395
+ /**
396
+ * 在宿主生命期里执行一次注册:有 `effect` 就交给它托管卸载,没有就直接跑。
397
+ * @author ddj 2026年11月25号
398
+ * @param ctx 宿主上下文
399
+ * @param run 注册动作
400
+ * @param label 诊断标签
401
+ * @returns 无
402
+ */
403
+ function effectOf(ctx: unknown, run: () => unknown, label: string): void {
404
+ const scope = ctx as { effect?: (action: () => unknown, label?: string) => unknown } | undefined
405
+ if (scope && typeof scope.effect === 'function') {
406
+ scope.effect(run, label)
407
+ return
408
+ }
409
+ run()
410
+ }
411
+
412
+ /**
413
+ * 加载可选宿主模块;失败返回 undefined(不阻断装配)。
414
+ * @author ddj 2026年11月25号
415
+ * @param load 加载函数
416
+ * @param specifier 模块名
417
+ * @returns 模块命名空间或 undefined
418
+ */
419
+ async function safeLoad(load: (specifier: string) => Promise<unknown>, specifier: string): Promise<unknown> {
420
+ try {
421
+ return await load(specifier)
422
+ } catch (error) {
423
+ log.warn('宿主模块加载失败(' + specifier + '):' + (error instanceof Error ? error.message : String(error)))
424
+ return undefined
425
+ }
426
+ }
427
+
428
+ /**
429
+ * 装配测试验收模式:用 `ctx.inject` 等齐四项宿主服务后再注册。
430
+ *
431
+ * 服务齐了才装配(缺任何一项都不做半截模式);旧宿主没有 `sessionProjections` 时
432
+ * 调用会一直等待、不报错——`/test-check` 自然不可用,其余功能不受影响。
433
+ * @author ddj 2026年11月25号
434
+ * @param ctx 宿主上下文
435
+ * @param options 安装选项
436
+ * @returns 是否已调度装配
437
+ */
438
+ export function installCheckMode(ctx: Ctx, options: CheckModeOptions = {}): boolean {
439
+ if (typeof ctx?.inject !== 'function') {
440
+ log.warn('/test-check 未装配:DSH 未提供 ctx.inject')
441
+ return false
442
+ }
443
+ try {
444
+ ctx.inject(
445
+ ['sessionProjections', 'systemPrompt', 'tools', 'commands'],
446
+ (sctx: unknown) => {
447
+ void setupCheckMode(sctx, { ...options, hostCtx: sctx }).catch((error: unknown) => {
448
+ log.warn('/test-check 装配失败:' + (error instanceof Error ? error.message : String(error)))
449
+ })
450
+ },
451
+ )
452
+ return true
453
+ } catch (error) {
454
+ log.warn('/test-check 装配调度失败:' + (error instanceof Error ? error.message : String(error)))
455
+ return false
456
+ }
457
+ }
458
+
459
+ /**
460
+ * 真正把投影、两条 section、两个工具与命令挂到宿主上。
461
+ * @author ddj 2026年11月25号
462
+ * @param ctx 已注入服务的宿主上下文
463
+ * @param options 安装选项
464
+ * @returns 是否装配成功
465
+ */
466
+ export async function setupCheckMode(ctx: unknown, options: CheckModeOptions = {}): Promise<boolean> {
467
+ const loadModule = typeof options.loadModule === 'function' ? options.loadModule : loadHostModule
468
+ const projections = serviceOf(ctx, 'sessionProjections') as ProjectionsLike | undefined
469
+ if (!projections || typeof projections.register !== 'function') {
470
+ log.warn('/test-check 未装配:宿主没有 sessionProjections 服务(测试验收模式不可用)')
471
+ return false
472
+ }
473
+
474
+ let handle: ProjectionHandleLike
475
+ try {
476
+ handle = await projections.register(checkProjectionDefinition as unknown)
477
+ } catch (error) {
478
+ log.warn('/test-check 未装配:会话投影注册失败:' + (error instanceof Error ? error.message : String(error)))
479
+ return false
480
+ }
481
+
482
+ /** @author ddj 2026年11月25号 @param session 会话 @returns 投影状态(异常按未进入处理) */
483
+ function stateOf(session: unknown): CheckModeState {
484
+ if (!session) return TEST_CHECK_INITIAL
485
+ try {
486
+ const raw = handle.stateOf(session) as Partial<CheckModeState> | undefined
487
+ return {
488
+ active: raw?.active === true,
489
+ entered: raw?.entered === true,
490
+ id: typeof raw?.id === 'string' ? raw.id : '',
491
+ running: raw?.running ?? null,
492
+ }
493
+ } catch {
494
+ return TEST_CHECK_INITIAL
495
+ }
496
+ }
497
+ /** @author ddj 2026年11月25号 @param session 会话 @returns 是否活跃 */
498
+ function activeOf(session: unknown): boolean {
499
+ return stateOf(session).active === true
500
+ }
501
+ /** @author ddj 2026年11月25号 @param session 会话 @returns 是否进入过模式 */
502
+ function enteredOf(session: unknown): boolean {
503
+ return stateOf(session).entered === true
504
+ }
505
+ /** @author ddj 2026年11月25号 @param session 会话 @returns 当前单子 id(缺省用默认 id) */
506
+ function idOf(session: unknown): string {
507
+ const id = stateOf(session).id
508
+ return id || TEST_CHECK_DEFAULT_ID
509
+ }
510
+ /** @author ddj 2026年11月25号 @param session 会话 @returns 会话工作区 */
511
+ function cwdOf(session: unknown): string | null {
512
+ if (!session) return null
513
+ try {
514
+ return cwdOfSession(ctx as never, session as never)
515
+ } catch {
516
+ return null
517
+ }
518
+ }
519
+ /** @author ddj 2026年11月25号 @param session 会话 @returns 项目根(拿不到工作区时为空串) */
520
+ function rootOf(session: unknown): string {
521
+ const cwd = cwdOf(session)
522
+ if (!cwd) return ''
523
+ try {
524
+ return projectRootOf(cwd)
525
+ } catch {
526
+ return ''
527
+ }
528
+ }
529
+
530
+ // 两条系统提示 section(对齐官方 plan:policy / plan:status)。
531
+ const systemPrompt = serviceOf(ctx, 'systemPrompt') as SystemPromptLike | undefined
532
+ if (systemPrompt && typeof systemPrompt.section === 'function') {
533
+ let baseOrder = 550
534
+ try {
535
+ if (typeof systemPrompt.getSectionOrder === 'function') {
536
+ const order = systemPrompt.getSectionOrder('PLAN_POLICY')
537
+ if (typeof order === 'number' && Number.isFinite(order)) baseOrder = order
538
+ }
539
+ } catch {
540
+ /* 旧宿主没有该常量表:用回退顺序 */
541
+ }
542
+ const policy = {
543
+ name: 'vscode-mode:test-check-policy',
544
+ retirement: 'Test-check mode is no longer available. Its instructions no longer apply.',
545
+ order: baseOrder + 0.7,
546
+ /** @author ddj 2026年11月25号 / 2026年11月26号 @param asm 装配上下文 @returns 规则文本或空串 */
547
+ text: (asm: { agent?: { session?: unknown } }) => {
548
+ const session = asm?.agent?.session
549
+ if (!enteredOf(session)) return ''
550
+ const policy = policyTextOf(rootOf(session))
551
+ return testCheckPolicyText(policy.text, !policy.isDefault)
552
+ },
553
+ }
554
+ const status = {
555
+ name: 'vscode-mode:test-check-status',
556
+ replacement: '',
557
+ order: baseOrder + 1.7,
558
+ /** @author ddj 2026年11月25号 @param asm 装配上下文 @returns 一行状态或空串 */
559
+ text: (asm: { agent?: { session?: unknown } }) => {
560
+ const session = asm?.agent?.session
561
+ if (!session) return ''
562
+ const state = stateOf(session)
563
+ return testCheckStatusText(state.entered, state.active)
564
+ },
565
+ }
566
+ effectOf(ctx, () => systemPrompt.section!(policy), 'vscode-mode: test-check policy section')
567
+ effectOf(ctx, () => systemPrompt.section!(status), 'vscode-mode: test-check status section')
568
+ } else {
569
+ log.warn('/test-check 规则未注入:宿主没有 systemPrompt.section 服务')
570
+ }
571
+
572
+ // 两个工具:从首次进入起常驻准入(对齐官方渐进式披露),执行时再校验活跃。
573
+ try {
574
+ const toolsModule = await loadModule('@deepseek-ai/dsh-tools') as { defineTool?: (options: unknown) => unknown }
575
+ if (typeof toolsModule?.defineTool === 'function') {
576
+ const deps = {
577
+ cwdOf,
578
+ idOf,
579
+ activeOf,
580
+ exitMode: (agent: unknown, signal?: AbortSignal) => runExitLine(ctx, agent, signal),
581
+ }
582
+ const definitions = [
583
+ toolsModule.defineTool(reportToolOptions(deps)),
584
+ toolsModule.defineTool(finishToolOptions(deps)),
585
+ ]
586
+ effectOf(ctx, () => {
587
+ const tools = serviceOf(ctx, 'tools') as ToolsLike | undefined
588
+ if (!tools || typeof tools.register !== 'function') {
589
+ log.warn('test_check_report / test_check_finish 未注册:宿主没有 tools 服务')
590
+ return undefined
591
+ }
592
+ for (const definition of definitions) {
593
+ tools.register(definition, { when: (context) => enteredOf(context?.agent?.session) })
594
+ }
595
+ return undefined
596
+ }, 'vscode-mode: test-check tools')
597
+ } else {
598
+ log.warn('test_check_report / test_check_finish 未注册:无法从宿主加载 defineTool')
599
+ }
600
+ } catch (error) {
601
+ log.warn('test_check_report / test_check_finish 未注册:' + (error instanceof Error ? error.message : String(error)))
602
+ }
603
+
604
+ // 命令:`/test-check [off|任务]`(commands 已在注入列表里,不会缺席)。
605
+ const llm = await safeLoad(loadModule, '@deepseek-ai/dsh-llm') as { createUserMessage?: (input: unknown) => unknown } | undefined
606
+ const buildUserMessage = typeof options.buildUserMessage === 'function'
607
+ ? options.buildUserMessage
608
+ : (typeof llm?.createUserMessage === 'function'
609
+ ? (text: string) => llm!.createUserMessage!({ content: [{ type: 'text', text }], source: { kind: 'user' } })
610
+ : undefined)
611
+
612
+ const commands = serviceOf(ctx, 'commands') as CommandsLike | undefined
613
+ if (!commands || typeof commands.register !== 'function') {
614
+ log.warn('/test-check 命令未注册:commands 服务不支持 register')
615
+ return false
616
+ }
617
+ try {
618
+ const definition = checkCommand({
619
+ buildUserMessage,
620
+ prepareAttachments: options.prepareAttachments,
621
+ hostCtx: options.hostCtx ?? ctx,
622
+ })
623
+ effectOf(ctx, () => commands.register!(definition), 'vscode-mode: test-check command')
624
+ log.info('/test-check 已注册:测试验收模式(投影 + 规则 + 上报/导出工具)')
625
+ } catch (error) {
626
+ log.warn('/test-check 注册失败:' + (error instanceof Error ? error.message : String(error)))
627
+ return false
628
+ }
629
+ return true
630
+ }
631
+
632
+ /**
633
+ * 执行 `/test-check off` 并归一成败(收尾工具自动退出用)。
634
+ * @author ddj 2026年11月25号
635
+ * @param ctx 宿主上下文
636
+ * @param agent 调用方 agent
637
+ * @param signal 取消信号
638
+ * @returns ok + 失败原因
639
+ */
640
+ async function runExitLine(ctx: unknown, agent: unknown, signal?: AbortSignal): Promise<{ ok: boolean; error?: string }> {
641
+ const commands = serviceOf(ctx, 'commands') as CommandsLike | undefined
642
+ if (!commands || typeof commands.execute !== 'function') return { ok: false, error: '命令服务不可用' }
643
+ try {
644
+ const execution = await commands.execute(agent, TEST_CHECK_OFF_LINE, [], signal)
645
+ if (!execution) return { ok: false, error: '命令没有返回结果' }
646
+ const kind = execution.result?.kind
647
+ if (kind === 'success') return { ok: true }
648
+ return { ok: false, error: String(execution.result?.text ?? '未知原因') }
649
+ } catch (error) {
650
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
651
+ }
652
+ }
653
+
654
+ //endregion