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,759 @@
1
+ /**
2
+ * dsh-vscode-mode shared — 测试验收模式(`/test-check`)的跨平面契约。
3
+ *
4
+ * 宿主注册模式、工具与 RPC,客户端投影与页签都要认同一套名字、ID 规则与派生口径,
5
+ * 所以常量、纯函数与视图类型全部放这里,避免两侧各写一份后悄悄漂移。
6
+ *
7
+ * 本模块是纯函数、零 IO、不 import node 内置模块(客户端也要打包它):
8
+ * 文件读取、watch 与 sha256 都在 host 的 `testCheckStore.ts` 里做。
9
+ * @author ddj 2026年11月25号
10
+ */
11
+
12
+ //region 常量
13
+
14
+ /** 会话投影 key(`sessionProjections.register` 的 key,也是客户端 `useProjection` 的入参)。 */
15
+ export const TEST_CHECK_MODE_KEY = 'test-check'
16
+
17
+ /** 进入/离开模式的命令名(官方命令语法:小写字母开头)。 */
18
+ export const TEST_CHECK_COMMAND = 'test-check'
19
+
20
+ /** 离开模式的完整命令行(chip 与提示文案共用)。 */
21
+ export const TEST_CHECK_OFF_LINE = '/test-check off'
22
+
23
+ /** AI 上报一条结果(必须带证据)的工具名。 */
24
+ export const TEST_CHECK_REPORT_TOOL = 'test_check_report'
25
+
26
+ /** 收尾并导出快照的工具名。 */
27
+ export const TEST_CHECK_FINISH_TOOL = 'test_check_finish'
28
+
29
+ /** 数据根目录(相对项目根,不进版本库)。 */
30
+ export const TEST_CHECK_BASE_DIR = '.dsh/test-check'
31
+
32
+ /** 覆盖数据根目录的环境变量(值即 `<id>/` 的父目录)。 */
33
+ export const TEST_CHECK_ENV = 'DSH_TEST_CHECK_DIR'
34
+
35
+ /** 定义文件名。 */
36
+ export const TEST_CHECK_ITEMS = 'items.json'
37
+
38
+ /** 结果目录名(每个结果一个 JSON 文件)。 */
39
+ export const TEST_CHECK_EVENTS = 'events'
40
+
41
+ /** 上报片段文件(插件生成,可重生成)。 */
42
+ export const TEST_CHECK_SNIPPETS = 'snippets.md'
43
+
44
+ /** 交付快照目录(相对项目根,进版本库)。 */
45
+ export const TEST_CHECK_DOCS = 'docs'
46
+
47
+ /** 页签轮询间隔(毫秒):验收标准要求写事件后 1 秒内反映。 */
48
+ export const TEST_CHECK_POLL_MS = 1000
49
+
50
+ /** 底部栏 chip 的轮询间隔(毫秒):只要计数,慢一点省开销。 */
51
+ export const TEST_CHECK_CHIP_MS = 2500
52
+
53
+ /** 一次最多读多少个事件文件(按文件名倒序取最近的)。 */
54
+ export const TEST_CHECK_MAX_EVENTS = 2000
55
+
56
+ /** 没有任务文本时用的固定单子 id。 */
57
+ export const TEST_CHECK_DEFAULT_ID = 'check'
58
+
59
+ /** 结果状态(可落盘的四个)。 */
60
+ export type TestCheckStatus = 'pass' | 'fail' | 'blocked' | 'skip'
61
+
62
+ /** 全部合法结果状态。 */
63
+ export const TEST_CHECK_STATUSES: readonly TestCheckStatus[] = ['pass', 'fail', 'blocked', 'skip']
64
+
65
+ /** 派生状态(含未验、声明无证据与需复验)。 */
66
+ export type TestCheckVerdict = 'todo' | 'pass' | 'claimed' | 'fail' | 'blocked' | 'skip' | 'stale'
67
+
68
+ /** 派生状态的中文标签(页签与快照共用)。 */
69
+ export const TEST_CHECK_LABELS: Readonly<Record<TestCheckVerdict, string>> = {
70
+ todo: '未验',
71
+ pass: '通过',
72
+ claimed: '无证据',
73
+ fail: '失败',
74
+ blocked: '阻塞',
75
+ skip: '跳过',
76
+ stale: '需复验',
77
+ }
78
+
79
+ //endregion
80
+
81
+ //region 单子 ID
82
+
83
+ /** 单子 id 允许的字符:小写字母/数字开头,允许连字符。 */
84
+ const SHEET_ID = /^[a-z0-9][a-z0-9-]{0,63}$/
85
+
86
+ /** 派生 id 时忽略的常见词(避免把 a/the 拼进目录名)。 */
87
+ const ID_STOP = new Set(['the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'use', 'using'])
88
+
89
+ /**
90
+ * FNV-1a 32 位哈希:只要稳定、两端一致,不需要密码学强度。
91
+ * @author ddj 2026年11月25号
92
+ * @param text 输入文本
93
+ * @returns 8 位十六进制
94
+ */
95
+ function fnv1a(text: string): string {
96
+ let hash = 0x811c9dc5
97
+ for (let index = 0; index < text.length; index += 1) {
98
+ hash ^= text.charCodeAt(index)
99
+ hash = Math.imul(hash, 0x01000193) >>> 0
100
+ }
101
+ return hash.toString(16).padStart(8, '0')
102
+ }
103
+
104
+ /**
105
+ * 由任务文本派生单子 id(kebab-case,确定性:宿主与客户端算出来必须一致)。
106
+ *
107
+ * 先取前三个 ASCII 词;中文任务没有可用词时退回 `check-<8 位哈希>`;
108
+ * 完全没有任务时用固定 `check`,保证 `/test-check` 与 `/test-check off` 可配对。
109
+ * @author ddj 2026年11月25号
110
+ * @param task 任务文本
111
+ * @returns 单子 id
112
+ */
113
+ export function testCheckIdOf(task: unknown): string {
114
+ const text = String(task ?? '').trim()
115
+ const words = text.toLowerCase().match(/[a-z0-9]+/g) ?? []
116
+ const meaningful = words.filter((word) => word.length > 1 && !ID_STOP.has(word)).slice(0, 3)
117
+ const slug = meaningful.join('-').slice(0, 32).replace(/-+/g, '-').replace(/^-|-$/g, '')
118
+ if (slug.length >= 3) return slug
119
+ if (!text) return TEST_CHECK_DEFAULT_ID
120
+ return 'check-' + fnv1a(text)
121
+ }
122
+
123
+ /**
124
+ * 单子 id 是否合法(也用于校验 `items.json` 里的 id 字段)。
125
+ * @author ddj 2026年11月25号
126
+ * @param value 待校验值
127
+ * @returns 合法为 true
128
+ */
129
+ export function isSheetId(value: unknown): boolean {
130
+ return typeof value === 'string' && SHEET_ID.test(value)
131
+ }
132
+
133
+ //endregion
134
+
135
+ //region 测试点 ID
136
+
137
+ /** 测试点 id:`<scope>.<area>.<3 位序号>`,段前缀必须是小写字母。 */
138
+ const ITEM_ID = /^([a-z][a-z0-9-]{0,31})\.([a-z][a-z0-9-]{0,31})\.([0-9]{3})$/
139
+
140
+ /** 单个段内不允许首尾连字符(`a-`、`-a` 视为错字)。 */
141
+ const ITEM_SEGMENT = /^[a-z](?:[a-z0-9-]*[a-z0-9])?$/
142
+
143
+ /**
144
+ * 测试点 id 是否合法。
145
+ * @author ddj 2026年11月25号
146
+ * @param value 待校验值
147
+ * @returns 合法为 true
148
+ */
149
+ export function isItemId(value: unknown): boolean {
150
+ const match = ITEM_ID.exec(typeof value === 'string' ? value : '')
151
+ return match !== null && ITEM_SEGMENT.test(match[1]) && ITEM_SEGMENT.test(match[2])
152
+ }
153
+
154
+ /**
155
+ * 取测试点 id 的非法原因(用于逐条列错,报告能指到具体段)。
156
+ * @author ddj 2026年11月25号
157
+ * @param value 待校验值
158
+ * @returns 原因文案;合法时 null
159
+ */
160
+ export function idProblemOf(value: unknown): string | null {
161
+ const text = typeof value === 'string' ? value : ''
162
+ if (!text) return 'ID 为空'
163
+ const parts = text.split('.')
164
+ if (parts.length !== 3) return 'ID 要三段:<scope>.<area>.<3 位序号>'
165
+ if (!ITEM_SEGMENT.test(parts[0]) || !ITEM_SEGMENT.test(parts[1])) return '前两段要小写字母开头、不超过 32 字符、首尾不许连字符'
166
+ if (!/^[0-9]{3}$/.test(parts[2])) return '序号要 3 位数字(001…999)'
167
+ return null
168
+ }
169
+
170
+ //endregion
171
+
172
+ //region 输入解析
173
+
174
+ /** `/test-check` 的输入解析结果。 */
175
+ export interface TestCheckInput {
176
+ /** off = 离开模式;enter = 进入模式(可带任务)。 */
177
+ action: 'off' | 'enter'
178
+ /** 剥离开关后的任务文本。 */
179
+ task: string
180
+ }
181
+
182
+ /**
183
+ * 解析 `/test-check` 的输入:`off` 离开,其余文本原样作为任务。
184
+ * @author ddj 2026年11月25号
185
+ * @param rawInput 官方命令的 rawInput
186
+ * @returns 动作与任务文本
187
+ */
188
+ export function parseCheckInput(rawInput: unknown): TestCheckInput {
189
+ const text = String(rawInput ?? '').trim()
190
+ if (/^off$/i.test(text)) return { action: 'off', task: '' }
191
+ return { action: 'enter', task: text }
192
+ }
193
+
194
+ //endregion
195
+
196
+ //region 数据形状
197
+
198
+ /** 定义文件里的一条验收点。 */
199
+ export interface TestCheckItemDef {
200
+ /** `<scope>.<area>.<3 位序号>`,全局唯一、只增不改。 */
201
+ id: string
202
+ /** 一句话说明这一条验什么。 */
203
+ title: string
204
+ /** 分组名(缺省「未分组」)。 */
205
+ group?: string
206
+ /** 被验文件(相对项目根,用于需复验判定)。 */
207
+ files?: string[]
208
+ /** 已删除的条目:保留编号但不计分。 */
209
+ retired?: boolean
210
+ }
211
+
212
+ /** 定义文件(`items.json`)。 */
213
+ export interface TestCheckDefinition {
214
+ /** 单子 id(建议与目录名一致)。 */
215
+ id?: string
216
+ /** 单子标题。 */
217
+ title?: string
218
+ /** 格式版本,当前只有 1。 */
219
+ version?: number
220
+ /** 验收点清单。 */
221
+ items: TestCheckItemDef[]
222
+ }
223
+
224
+ /** 证据(全部可选;至少一项非空才算有证据)。 */
225
+ export interface TestCheckEvidence {
226
+ /** test / command / file / log / manual。 */
227
+ kind?: string
228
+ /** 一句话证据(测试名、命令、文件)。 */
229
+ summary?: string
230
+ /** 跑过的命令。 */
231
+ command?: string
232
+ /** 命令退出码。 */
233
+ exitCode?: number
234
+ /** 证据文件路径(相对项目根或绝对)。 */
235
+ path?: string
236
+ }
237
+
238
+ /** 结果事件里的被验对象(用于需复验判定)。 */
239
+ export interface TestCheckSubject {
240
+ /** `sha256:<hex>`,算法见 `subjectHashOf` 的注释。 */
241
+ hash?: string
242
+ }
243
+
244
+ /** 一条结果事件(一个事件文件的内容)。 */
245
+ export interface TestCheckEvent {
246
+ /** 测试点 id(必填)。 */
247
+ item: string
248
+ /** 结果状态(必填)。 */
249
+ status: TestCheckStatus
250
+ /** ISO 时间;缺省用文件 mtime。 */
251
+ at?: string
252
+ /** 证据(缺省表示「没证据」)。 */
253
+ evidence?: TestCheckEvidence
254
+ /** 被验对象指纹。 */
255
+ subject?: TestCheckSubject
256
+ }
257
+
258
+ /** 从磁盘读到的一条事件(带文件名与时间戳)。 */
259
+ export interface TestCheckEventFile {
260
+ /** 事件文件名。 */
261
+ file: string
262
+ /** 排序用毫秒时间戳(`at` 解析失败时取文件 mtime)。 */
263
+ at: number
264
+ /** 解析后的事件。 */
265
+ event: TestCheckEvent
266
+ }
267
+
268
+ /** 被忽略的事件文件(坏 JSON / 未知条目 / 非法状态)。 */
269
+ export interface TestCheckIgnored {
270
+ /** 文件名(不含目录)。 */
271
+ file: string
272
+ /** 忽略原因。 */
273
+ reason: string
274
+ }
275
+
276
+ /** 一条验收点在页签里的样子。 */
277
+ export interface TestCheckItemView {
278
+ /** 测试点 id。 */
279
+ id: string
280
+ /** 说明。 */
281
+ title: string
282
+ /** 分组名。 */
283
+ group: string
284
+ /** 是否已退役。 */
285
+ retired: boolean
286
+ /** 最近一次落盘状态(没有事件时为 todo)。 */
287
+ status: TestCheckStatus | 'todo'
288
+ /** 派生状态。 */
289
+ verdict: TestCheckVerdict
290
+ /** 中文标签。 */
291
+ label: string
292
+ /** 事件时间(ISO);没有事件时不带。 */
293
+ at?: string
294
+ /** 证据;没有时不带。 */
295
+ evidence?: TestCheckEvidence
296
+ /** 是否计入通过数(无证据的 pass 不计)。 */
297
+ counted: boolean
298
+ /** 是否需复验。 */
299
+ stale: boolean
300
+ }
301
+
302
+ /** 一个分组。 */
303
+ export interface TestCheckGroupView {
304
+ /** 分组名。 */
305
+ name: string
306
+ /** 该组的验收点(按定义顺序)。 */
307
+ items: TestCheckItemView[]
308
+ }
309
+
310
+ /** 汇总计数(固定五格)。 */
311
+ export interface TestCheckCounts {
312
+ /** 有效验收点总数(不含退役)。 */
313
+ total: number
314
+ /** 有证据且未失效的通过数。 */
315
+ pass: number
316
+ /** 失败数。 */
317
+ fail: number
318
+ /** 阻塞数。 */
319
+ blocked: number
320
+ /** 未验数(含跳过与「声明通过无证据」)。 */
321
+ todo: number
322
+ /** 需复验数。 */
323
+ stale: number
324
+ }
325
+
326
+ /** 全部验收单列表里的一行(侧栏面板用;计数口径与页签同源)。 */
327
+ export interface TestCheckSheetSummary {
328
+ /** 单子 id。 */
329
+ id: string
330
+ /** 单子标题(缺省为 id)。 */
331
+ title: string
332
+ /** 汇总计数(与 `edrv.testCheck.get` 的视图一致)。 */
333
+ counts: TestCheckCounts
334
+ /** 定义文件绝对路径。 */
335
+ itemsPath: string
336
+ /** 对应交付快照绝对路径(`docs/acceptance-<id>.html`)。 */
337
+ snapshotPath: string
338
+ /** 快照文件是否存在(不存在时面板给「移除」入口)。 */
339
+ hasSnapshot: boolean
340
+ /** 最近活动时间(毫秒;快照 mtime 优先,其次单子目录)。 */
341
+ updatedAt: number
342
+ }
343
+
344
+ /** 验收单派生视图(RPC 载荷、页签与快照共用)。 */
345
+ export interface TestCheckView {
346
+ /** 单子 id。 */
347
+ id: string
348
+ /** 单子标题。 */
349
+ title: string
350
+ /** 项目根(/ 分隔的绝对路径)。 */
351
+ root: string
352
+ /** 单子目录(/ 分隔的绝对路径)。 */
353
+ dir: string
354
+ /** ready = 定义读到了;missing = 还没建单;invalid = 定义有错。 */
355
+ state: 'ready' | 'missing' | 'invalid'
356
+ /** state 不为 ready 时的可读原因/逐条错误(多行)。 */
357
+ error?: string
358
+ /** 定义文件绝对路径。 */
359
+ itemsPath: string
360
+ /** 结果目录绝对路径。 */
361
+ eventsDir: string
362
+ /** 按分组排好的验收点。 */
363
+ groups: TestCheckGroupView[]
364
+ /** 汇总。 */
365
+ counts: TestCheckCounts
366
+ /** 被忽略的事件文件。 */
367
+ ignored: TestCheckIgnored[]
368
+ /** 数据指纹:变了才重绘 iframe。 */
369
+ stamp: string
370
+ }
371
+
372
+ //endregion
373
+
374
+ //region 定义校验
375
+
376
+ /** 定义校验结果。 */
377
+ export interface DefinitionCheck {
378
+ /** 校验通过的规范化定义;有错时不带。 */
379
+ definition?: TestCheckDefinition
380
+ /** 逐条错误文案(空数组表示通过)。 */
381
+ errors: string[]
382
+ }
383
+
384
+ /**
385
+ * 判断 `files` 项是否是安全的相对路径(不许绝对路径、不许 `..`)。
386
+ * @author ddj 2026年11月25号
387
+ * @param value 待校验值
388
+ * @returns 安全为 true
389
+ */
390
+ function isRelativeFile(value: unknown): boolean {
391
+ if (typeof value !== 'string') return false
392
+ const text = value.trim().replace(/\\/g, '/')
393
+ if (!text) return false
394
+ if (/^(?:[a-z]:\/|\/)/i.test(text)) return false
395
+ return !text.split('/').includes('..')
396
+ }
397
+
398
+ /**
399
+ * 校验 `items.json`:JSON 已解析成对象,这里只查语义。
400
+ *
401
+ * 重复 ID、非法 ID、空标题都进 errors(不静默丢条目);`retired` 条目同样要过校验,
402
+ * 因为编号是永久占位的,写错号就等于丢失编号。
403
+ * @author ddj 2026年11月25号
404
+ * @param raw 解析后的 JSON
405
+ * @param expectId 目录名(用作缺省 id,便于「目录与文件不一致」时仍能显示)
406
+ * @returns 规范化定义或逐条错误
407
+ */
408
+ export function checkDefinition(raw: unknown, expectId = ''): DefinitionCheck {
409
+ const errors: string[] = []
410
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
411
+ return { errors: ['items.json 顶层必须是对象'] }
412
+ }
413
+ const row = raw as Record<string, unknown>
414
+ if (row.version !== undefined && row.version !== 1) errors.push('version 只支持 1,当前是 ' + String(row.version))
415
+ if (row.items !== undefined && !Array.isArray(row.items)) return { errors: [...errors, 'items 必须是数组'] }
416
+
417
+ const list = Array.isArray(row.items) ? row.items : []
418
+ const seen = new Set<string>()
419
+ const items: TestCheckItemDef[] = []
420
+ list.forEach((entry, index) => {
421
+ const at = '第 ' + String(index + 1) + ' 条'
422
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
423
+ errors.push(at + ':必须是对象')
424
+ return
425
+ }
426
+ const item = entry as Record<string, unknown>
427
+ const problem = idProblemOf(item.id)
428
+ const itemId = typeof item.id === 'string' ? item.id.trim() : ''
429
+ if (problem) errors.push(at + ':' + problem + (itemId ? '(' + itemId + ')' : ''))
430
+ else if (seen.has(itemId)) errors.push(at + ':重复 ID ' + itemId)
431
+ if (!problem) seen.add(itemId)
432
+
433
+ const title = typeof item.title === 'string' ? item.title.trim() : ''
434
+ if (!title) errors.push(at + ':title 不能为空')
435
+
436
+ const retired = item.retired === true
437
+ const group = typeof item.group === 'string' && item.group.trim() ? item.group.trim() : undefined
438
+ let files: string[] | undefined
439
+ if (item.files !== undefined) {
440
+ if (!Array.isArray(item.files)) errors.push(at + ':files 必须是数组')
441
+ else {
442
+ files = []
443
+ for (const file of item.files) {
444
+ if (!isRelativeFile(file)) {
445
+ errors.push(at + ':files 里 ' + JSON.stringify(file) + ' 不是相对项目根的路径')
446
+ continue
447
+ }
448
+ files.push(String(file).trim().replace(/\\/g, '/'))
449
+ }
450
+ }
451
+ }
452
+ if (problem || !title) return
453
+ const normalized: TestCheckItemDef = { id: itemId, title }
454
+ if (group) normalized.group = group
455
+ if (files && files.length) normalized.files = files
456
+ if (retired) normalized.retired = true
457
+ items.push(normalized)
458
+ })
459
+
460
+ if (errors.length) return { errors }
461
+ const definition: TestCheckDefinition = { items }
462
+ if (typeof row.id === 'string' && isSheetId(row.id)) definition.id = row.id
463
+ else if (expectId && isSheetId(expectId)) definition.id = expectId
464
+ if (typeof row.title === 'string' && row.title.trim()) definition.title = row.title.trim()
465
+ definition.version = 1
466
+ return { definition, errors }
467
+ }
468
+
469
+ //endregion
470
+
471
+ //region 派生
472
+
473
+ /**
474
+ * 证据是否算「有」:任一摘要字段非空,或退出码是数字。
475
+ * @author ddj 2026年11月25号
476
+ * @param evidence 证据
477
+ * @returns 有证据为 true
478
+ */
479
+ export function hasEvidence(evidence: TestCheckEvidence | undefined): boolean {
480
+ if (!evidence || typeof evidence !== 'object') return false
481
+ if (typeof evidence.exitCode === 'number' && Number.isFinite(evidence.exitCode)) return true
482
+ for (const key of ['summary', 'command', 'path'] as const) {
483
+ const value = evidence[key]
484
+ if (typeof value === 'string' && value.trim()) return true
485
+ }
486
+ return false
487
+ }
488
+
489
+ /**
490
+ * 归一化状态:只认四个合法值,其余返回 null(调用方按非法事件处理)。
491
+ * @author ddj 2026年11月25号
492
+ * @param value 原始状态
493
+ * @returns 合法状态或 null
494
+ */
495
+ export function normalizeStatus(value: unknown): TestCheckStatus | null {
496
+ return typeof value === 'string' && (TEST_CHECK_STATUSES as readonly string[]).includes(value)
497
+ ? value as TestCheckStatus
498
+ : null
499
+ }
500
+
501
+ /**
502
+ * 把每条事件折成「每个测试点最新一条」。
503
+ *
504
+ * 排序口径:`at`(解析失败用文件 mtime)升序;同一时刻按文件名升序,保证结果稳定可测。
505
+ * @author ddj 2026年11月25号
506
+ * @param events 事件列表(顺序无关)
507
+ * @returns 测试点 id → 最新事件
508
+ */
509
+ export function latestPerItem(events: readonly TestCheckEventFile[]): Map<string, TestCheckEventFile> {
510
+ const sorted = [...events].sort((left, right) => {
511
+ if (left.at !== right.at) return left.at - right.at
512
+ return left.file < right.file ? -1 : left.file > right.file ? 1 : 0
513
+ })
514
+ const latest = new Map<string, TestCheckEventFile>()
515
+ for (const entry of sorted) latest.set(entry.event.item, entry)
516
+ return latest
517
+ }
518
+
519
+ /**
520
+ * 拼出被验对象的待哈希文本(口径固定,片段与宿主都按它算):
521
+ * `files` 按路径排序,逐个拼 `path + '\n' + sha256(内容) + '\n'`。
522
+ *
523
+ * 这里只拼文本、不算 sha256——客户端也要用本模块,不能 import node:crypto;
524
+ * 最终摘要由宿主(`testCheckStore.ts`)与各语言片段各自用真实的 sha256 算。
525
+ * @author ddj 2026年11月25号
526
+ * @param files 路径与内容 sha256(十六进制)
527
+ * @returns 待哈希文本;没有文件时返回空串
528
+ */
529
+ export function subjectHashLines(files: ReadonlyArray<{ path: string; sha256: string }>): string {
530
+ if (!files.length) return ''
531
+ return [...files]
532
+ .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))
533
+ .map((file) => file.path + '\n' + file.sha256 + '\n')
534
+ .join('')
535
+ }
536
+
537
+ /**
538
+ * 读一条证据的展示文案(快照与页签共用;没有摘要时退回命令)。
539
+ * @author ddj 2026年11月25号
540
+ * @param evidence 证据
541
+ * @returns 一行文案;什么都没有时空串
542
+ */
543
+ export function evidenceTextOf(evidence: TestCheckEvidence | undefined): string {
544
+ if (!evidence) return ''
545
+ const summary = typeof evidence.summary === 'string' ? evidence.summary.trim() : ''
546
+ if (summary) return summary
547
+ const command = typeof evidence.command === 'string' ? evidence.command.trim() : ''
548
+ if (command) {
549
+ const code = typeof evidence.exitCode === 'number' ? ' · 退出码 ' + String(evidence.exitCode) : ''
550
+ return command + code
551
+ }
552
+ const path = typeof evidence.path === 'string' ? evidence.path.trim() : ''
553
+ return path
554
+ }
555
+
556
+ /**
557
+ * 把任意长度的文本混成 32 位十六进制(仅用于 stamp 与「没有 SHA 也要有个指纹」的场合)。
558
+ * @author ddj 2026年11月25号
559
+ * @param text 输入
560
+ * @returns 32 位十六进制
561
+ */
562
+ export function mixHex(text: string): string {
563
+ return fnv1a(text) + fnv1a(text + '\u0001') + fnv1a(text + '\u0002') + fnv1a(text + '\u0003')
564
+ }
565
+
566
+ /**
567
+ * 由事件、失效标记与状态推导展示状态。
568
+ * @author ddj 2026年11月25号
569
+ * @param event 最新事件(可能没有)
570
+ * @param stale 是否需复验
571
+ * @returns 派生状态
572
+ */
573
+ export function verdictOf(event: TestCheckEventFile | undefined, stale: boolean): TestCheckVerdict {
574
+ if (!event) return 'todo'
575
+ const status = normalizeStatus(event.event.status)
576
+ if (!status) return 'todo'
577
+ if (stale) return 'stale'
578
+ if (status === 'pass') return hasEvidence(event.event.evidence) ? 'pass' : 'claimed'
579
+ if (status === 'fail') return 'fail'
580
+ if (status === 'blocked') return 'blocked'
581
+ return 'skip'
582
+ }
583
+
584
+ /** 派生视图的入参(宿主把磁盘事实读好后交给纯函数)。 */
585
+ export interface DeriveInput {
586
+ /** 单子 id。 */
587
+ id: string
588
+ /** 单子标题(缺省用 id)。 */
589
+ title?: string
590
+ /** 项目根。 */
591
+ root: string
592
+ /** 单子目录。 */
593
+ dir: string
594
+ /** 定义文件路径。 */
595
+ itemsPath: string
596
+ /** 结果目录路径。 */
597
+ eventsDir: string
598
+ /** 已校验的定义。 */
599
+ definition: TestCheckDefinition
600
+ /** 读到的事件。 */
601
+ events: readonly TestCheckEventFile[]
602
+ /** 测试点 id → 当前文件指纹(空串/缺省表示不比对)。 */
603
+ hashes?: Readonly<Record<string, string>>
604
+ /** 被忽略的事件文件。 */
605
+ ignored?: readonly TestCheckIgnored[]
606
+ }
607
+
608
+ /**
609
+ * 由定义 + 事件 + 当前指纹派生验收单视图。
610
+ *
611
+ * 计数口径:退役条目不参与;`pass` 只有「有证据且未失效」才计入通过;
612
+ * `skip` 与「声明通过无证据」都进「未验」;失效单独进「需复验」。
613
+ * @author ddj 2026年11月25号
614
+ * @param input 磁盘事实
615
+ * @returns 派生视图(含数据指纹)
616
+ */
617
+ export function deriveSheetView(input: DeriveInput): TestCheckView {
618
+ const latest = latestPerItem(input.events)
619
+ const hashes = input.hashes ?? {}
620
+ const counts: TestCheckCounts = { total: 0, pass: 0, fail: 0, blocked: 0, todo: 0, stale: 0 }
621
+ const groups = new Map<string, TestCheckItemView[]>()
622
+
623
+ for (const item of input.definition.items) {
624
+ if (item.retired) continue
625
+ counts.total += 1
626
+ const event = latest.get(item.id)
627
+ const group = item.group ?? '未分组'
628
+ const current = hashes[item.id] ?? ''
629
+ const declared = event?.event.subject?.hash ?? ''
630
+ const stale = Boolean(event) && Boolean(current) && Boolean(declared) && current !== declared
631
+ const verdict = verdictOf(event, stale)
632
+ if (verdict === 'pass') counts.pass += 1
633
+ else if (verdict === 'fail') counts.fail += 1
634
+ else if (verdict === 'blocked') counts.blocked += 1
635
+ else if (verdict === 'stale') counts.stale += 1
636
+ else counts.todo += 1
637
+
638
+ const view: TestCheckItemView = {
639
+ id: item.id,
640
+ title: item.title,
641
+ group,
642
+ retired: false,
643
+ status: event ? (normalizeStatus(event.event.status) ?? 'todo') : 'todo',
644
+ verdict,
645
+ label: TEST_CHECK_LABELS[verdict],
646
+ counted: verdict === 'pass',
647
+ stale,
648
+ }
649
+ if (event?.event.at) view.at = event.event.at
650
+ if (event?.event.evidence) view.evidence = event.event.evidence
651
+ const bucket = groups.get(group) ?? []
652
+ bucket.push(view)
653
+ groups.set(group, bucket)
654
+ }
655
+
656
+ const view: TestCheckView = {
657
+ id: input.id,
658
+ title: input.title ?? input.definition.title ?? input.id,
659
+ root: input.root,
660
+ dir: input.dir,
661
+ state: 'ready',
662
+ itemsPath: input.itemsPath,
663
+ eventsDir: input.eventsDir,
664
+ groups: [...groups.entries()].map(([name, items]) => ({ name, items })),
665
+ counts,
666
+ ignored: [...(input.ignored ?? [])],
667
+ stamp: '',
668
+ }
669
+ view.stamp = stampOf(view)
670
+ return view
671
+ }
672
+
673
+ /**
674
+ * 数据指纹:状态、计数、每条的派生状态与时间都参与;数据没变就返回同一个串。
675
+ * @author ddj 2026年11月25号
676
+ * @param view 派生视图
677
+ * @returns 指纹
678
+ */
679
+ export function stampOf(view: TestCheckView): string {
680
+ const parts = [
681
+ view.state,
682
+ String(view.counts.total),
683
+ String(view.counts.pass),
684
+ String(view.counts.fail),
685
+ String(view.counts.blocked),
686
+ String(view.counts.todo),
687
+ String(view.counts.stale),
688
+ String(view.ignored.length),
689
+ ]
690
+ for (const group of view.groups) {
691
+ for (const item of group.items) parts.push(item.id + ':' + item.verdict + ':' + (item.at ?? ''))
692
+ }
693
+ return mixHex(parts.join('|'))
694
+ }
695
+
696
+ /**
697
+ * 构造「还没建单」或「定义有错」的视图(没有条目,但结构完整,页签照常渲染)。
698
+ * @author ddj 2026年11月25号
699
+ * @param input 基本信息
700
+ * @param state missing / invalid
701
+ * @param error 可读原因(多行)
702
+ * @param ignored 被忽略的事件
703
+ * @returns 派生视图
704
+ */
705
+ export function emptyView(
706
+ input: { id: string; title?: string; root: string; dir: string; itemsPath: string; eventsDir: string },
707
+ state: 'missing' | 'invalid',
708
+ error?: string,
709
+ ignored: readonly TestCheckIgnored[] = [],
710
+ ): TestCheckView {
711
+ const view: TestCheckView = {
712
+ id: input.id,
713
+ title: input.title ?? input.id,
714
+ root: input.root,
715
+ dir: input.dir,
716
+ state,
717
+ itemsPath: input.itemsPath,
718
+ eventsDir: input.eventsDir,
719
+ groups: [],
720
+ counts: { total: 0, pass: 0, fail: 0, blocked: 0, todo: 0, stale: 0 },
721
+ ignored: [...ignored],
722
+ stamp: '',
723
+ }
724
+ if (error) view.error = error
725
+ view.stamp = stampOf(view)
726
+ return view
727
+ }
728
+
729
+ //endregion
730
+
731
+ //region 结果文件名
732
+
733
+ /**
734
+ * 交付快照文件名(放在项目根 `docs/` 下):`acceptance-<id>.html`。
735
+ * @author ddj 2026年11月26号
736
+ * @param id 单子 id
737
+ * @returns 文件名
738
+ */
739
+ export function snapshotNameOf(id: string): string {
740
+ return 'acceptance-' + id + '.html'
741
+ }
742
+
743
+ /**
744
+ * 生成事件文件名:`<时间戳>-<随机>.json`,并发写不会互相覆盖。
745
+ * @author ddj 2026年11月25号
746
+ * @param at 时间点(默认当下)
747
+ * @param random 0~1 随机数来源(测试可注入固定值)
748
+ * @returns 文件名
749
+ */
750
+ export function eventFileNameOf(at: Date = new Date(), random: () => number = Math.random): string {
751
+ const pad = (value: number): string => String(value).padStart(2, '0')
752
+ const stamp = String(at.getUTCFullYear())
753
+ + pad(at.getUTCMonth() + 1) + pad(at.getUTCDate())
754
+ + 'T' + pad(at.getUTCHours()) + pad(at.getUTCMinutes()) + pad(at.getUTCSeconds())
755
+ const salt = Math.floor(Math.abs(random()) * 0xffff).toString(16).padStart(4, '0')
756
+ return stamp + '-' + salt + '.json'
757
+ }
758
+
759
+ //endregion