dsh-project-flow 0.9.3 → 0.10.1

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 (70) hide show
  1. package/CHANGELOG.md +197 -12
  2. package/README.md +25 -0
  3. package/checks/assertion.mjs +104 -0
  4. package/checks/command.mjs +416 -0
  5. package/checks/requirement.mjs +91 -0
  6. package/commands/slash.mjs +754 -0
  7. package/commands/steer.mjs +43 -0
  8. package/config/settings.mjs +217 -0
  9. package/docs/FEATURES.md +9 -6
  10. package/docs/anchors/file-whitelist.md +1 -1
  11. package/http/routes.mjs +252 -0
  12. package/index.js +173 -8612
  13. package/issues/issue.mjs +322 -0
  14. package/package.json +16 -1
  15. package/persistence/lock.mjs +67 -0
  16. package/persistence/log.mjs +43 -0
  17. package/persistence/recovery.mjs +118 -0
  18. package/persistence/state.mjs +202 -0
  19. package/pricing/estimate.mjs +72 -0
  20. package/prompts/rules.mjs +192 -0
  21. package/rollback/ledger.mjs +237 -0
  22. package/runner/pipeline.mjs +1190 -0
  23. package/runner/stage.mjs +370 -0
  24. package/runner/tools/context.mjs +64 -0
  25. package/runner/tools/decorate-cost.mjs +49 -0
  26. package/runner/tools/doctor.mjs +59 -0
  27. package/runner/tools/estimate.mjs +63 -0
  28. package/runner/tools/execute-run.mjs +255 -0
  29. package/runner/tools/models.mjs +55 -0
  30. package/runner/tools/resume.mjs +136 -0
  31. package/runner/tools/rollback.mjs +291 -0
  32. package/runner/tools/run.mjs +262 -0
  33. package/runner/tools/set.mjs +65 -0
  34. package/runner/tools/snapshots.mjs +83 -0
  35. package/runner/tools/status.mjs +70 -0
  36. package/runner/tools.mjs +94 -0
  37. package/shared/constants.mjs +273 -0
  38. package/shared/tool.mjs +32 -0
  39. package/shared/util.mjs +231 -0
  40. package/snapshot/repo.mjs +452 -0
  41. package/state/registry.mjs +40 -0
  42. package/tests/aesthetic.test.mjs +20 -12
  43. package/tests/apply-wiring.test.mjs +172 -0
  44. package/tests/assertions-e2e.mjs +2 -1
  45. package/tests/atomic-write.test.mjs +129 -0
  46. package/tests/client-bundle.test.mjs +3 -3
  47. package/tests/command-whitelist.test.mjs +135 -0
  48. package/tests/contract.test.mjs +2 -2
  49. package/tests/desktop.test.mjs +2 -2
  50. package/tests/domains.test.mjs +10 -7
  51. package/tests/e2e.mjs +2 -1
  52. package/tests/extra-phase.test.mjs +2 -2
  53. package/tests/feedback.test.mjs +2 -1
  54. package/tests/flow-gate.test.mjs +16 -56
  55. package/tests/issues-e2e.mjs +2 -1
  56. package/tests/panel-independence.test.mjs +2 -2
  57. package/tests/panel-report.test.mjs +2 -2
  58. package/tests/paths.mjs +70 -1
  59. package/tests/preview-path.test.mjs +2 -1
  60. package/tests/qa-assertions.test.mjs +10 -3
  61. package/tests/run-all.mjs +5 -0
  62. package/tests/snapshot-core.test.mjs +234 -0
  63. package/tests/stage-model.test.mjs +2 -2
  64. package/tests/stop-resume.test.mjs +7 -2
  65. package/tests/watch-root.test.mjs +2 -1
  66. package/ui/prompt.mjs +101 -0
  67. package/workspace/models.mjs +111 -0
  68. package/workspace/panel.mjs +359 -0
  69. package/workspace/paths.mjs +393 -0
  70. package/workspace/resume.mjs +107 -0
@@ -0,0 +1,416 @@
1
+ /**
2
+ * 判据执行器:白名单、命令解析、Windows 上的 .cmd 走法、超时、输出只留尾巴。
3
+ */
4
+ import { basename, join, isAbsolute, delimiter, dirname, relative, resolve } from 'node:path'
5
+ import { tmpdir } from 'node:os'
6
+ import { writeFileSync, rmSync, existsSync, realpathSync } from 'node:fs'
7
+ import { execFile } from 'node:child_process'
8
+ import { CHECK_MISSING_BINARY_LIMIT, CODE_ESCAPE_FLAGS, DEFAULT_ALLOWED_COMMANDS, DEFAULT_CHECK_TAIL_CHARS, DEFAULT_CHECK_TIMEOUT_MS, GIT_DANGEROUS_CONFIG, PACKAGE_RUNNERS, STRICT_ONLY_FLAGS } from '../shared/constants.mjs'
9
+ import { messageOf, tailOf } from '../shared/util.mjs'
10
+
11
+ export function commandNameOf(token) {
12
+ const base = basename(String(token ?? '').trim()).toLowerCase()
13
+ return base.replace(/\.(exe|cmd|bat|ps1)$/u, '')
14
+ }
15
+
16
+ export function checkCodeEscape(name, args, strictEval = false) {
17
+ const direct = CODE_ESCAPE_FLAGS[name]
18
+ if (Array.isArray(direct) && direct.length > 0) {
19
+ // 严格模式下才管 eval 类开关;包运行器不受这个开关影响。
20
+ const enforced = strictEval || !STRICT_ONLY_FLAGS.has(name)
21
+ if (enforced) {
22
+ for (const arg of args) {
23
+ // `--eval=code` 这样的写法也要认
24
+ const head = arg.split('=')[0]
25
+ if (direct.includes(arg) || direct.includes(head)) {
26
+ return {
27
+ escaped: true,
28
+ reason: strictEval
29
+ ? `${name} ${head} 等于直接执行一段代码(checkStrictEval 已开启,这类调用一律拒)`
30
+ : `${name} ${head} 会再起一个解释器,等于绕过白名单`,
31
+ }
32
+ }
33
+ }
34
+ }
35
+ }
36
+ // git -c key=value:只有那几个能把命令挂上去的键才拦。
37
+ if (name === 'git') {
38
+ for (let i = 0; i < args.length; i += 1) {
39
+ if (args[i] !== '-c') continue
40
+ const assignment = args[i + 1] ?? ''
41
+ const key = assignment.split('=')[0].trim()
42
+ if (GIT_DANGEROUS_CONFIG.test(key)) {
43
+ return { escaped: true, reason: `git -c ${key} 会把任意命令挂到 git 上执行,换成不带这条配置的写法` }
44
+ }
45
+ }
46
+ }
47
+ // 包运行器:npm exec / pnpm dlx 后面跟的其实是另一条命令,递归看一眼。
48
+ if (PACKAGE_RUNNERS.has(name) && args.length > 0) {
49
+ const sub = args.find(arg => !arg.startsWith('-'))
50
+ if (sub !== undefined) {
51
+ const subName = commandNameOf(sub)
52
+ if (PACKAGE_RUNNERS.has(subName) || (CODE_ESCAPE_FLAGS[subName] ?? []).length > 0) {
53
+ return { escaped: true, reason: `${name} ${sub} 会再起一个解释器,等于绕过白名单` }
54
+ }
55
+ }
56
+ }
57
+ return { escaped: false }
58
+ }
59
+
60
+ export function allowedCommandsOf(settings) {
61
+ const extra = typeof settings?.checkAllowedCommands === 'string' ? settings.checkAllowedCommands : ''
62
+ const names = [...DEFAULT_ALLOWED_COMMANDS, ...extra.split(/[,\s]+/u)]
63
+ .map(commandNameOf)
64
+ .filter(name => name !== '')
65
+ return [...new Set(names)]
66
+ }
67
+
68
+ export function tokenizeCommand(cmd) {
69
+ const text = typeof cmd === 'string' ? cmd : ''
70
+ const tokens = []
71
+ let current = ''
72
+ let quote = ''
73
+ let started = false
74
+ for (const ch of text) {
75
+ if (quote !== '') {
76
+ if (ch === quote) {
77
+ quote = ''
78
+ continue
79
+ }
80
+ current += ch
81
+ continue
82
+ }
83
+ if (ch === '"' || ch === "'") {
84
+ quote = ch
85
+ started = true
86
+ continue
87
+ }
88
+ if (/\s/u.test(ch)) {
89
+ if (started) {
90
+ tokens.push(current)
91
+ current = ''
92
+ started = false
93
+ }
94
+ continue
95
+ }
96
+ current += ch
97
+ started = true
98
+ }
99
+ if (started) tokens.push(current)
100
+ return tokens
101
+ }
102
+
103
+ /** target 是否落在 dir 里面(含相等)。跨盘符时 relative 会给出绝对路径,也算不在里面。 */
104
+ function isInside(dir, target) {
105
+ const rel = relative(dir, target)
106
+ if (rel === '' || rel === '.') return true
107
+ return !rel.startsWith('..') && !isAbsolute(rel) && !/^[a-zA-Z]:/u.test(rel)
108
+ }
109
+
110
+ /** PATH 里的目录,去掉首尾引号与空项,逐个解析成绝对路径。 */
111
+ function pathDirs() {
112
+ const dirs = []
113
+ for (const raw of (process.env.PATH ?? '').split(delimiter)) {
114
+ let entry = raw.trim()
115
+ if (entry.length >= 2 && entry.startsWith('"') && entry.endsWith('"')) entry = entry.slice(1, -1).trim()
116
+ if (entry === '') continue
117
+ try {
118
+ dirs.push(resolve(entry))
119
+ } catch {
120
+ // 这条写坏了就跳过,不影响别的
121
+ }
122
+ }
123
+ // node 自己所在目录永远算数:本机经常没有 node 在 PATH 里,
124
+ // 而 Requirement 的判据就是拿 process.execPath 跑的那条命令。
125
+ dirs.push(dirname(process.execPath))
126
+ return dirs
127
+ }
128
+
129
+ /**
130
+ * 这个 token 算不算「带路径」的写法。
131
+ *
132
+ * 只看有没有分隔符是不够的:`C:node.exe` 是盘符相对写法,一个分隔符都没有,
133
+ * 跑起来却是 C 盘当前目录下的同名二进制——按名字放行等于白名单被绕开。
134
+ * 所以盘符前缀(含 `C:` 后面不跟反斜杠的那种)一律当路径处理。
135
+ */
136
+ function isPathLike(token) {
137
+ const text = String(token ?? '')
138
+ return /[\\/]/u.test(text) || /^[A-Za-z]:/u.test(text)
139
+ }
140
+
141
+ /**
142
+ * 带路径的命令单独判一次。
143
+ *
144
+ * 白名单按「命令名」放行,而 `D:\evil\node.exe` 的名字也叫 node——光看名字
145
+ * 等于任何同名二进制都能跑。所以命令里带路径时,只认真实路径落在 PATH
146
+ * 目录(或 node 所在目录)里的那些;解析不到的(不存在、没权限)直接拒,
147
+ * 绝不退回「按名字放行」。
148
+ *
149
+ * 返回 '' 表示放行,否则返回拒的理由。
150
+ */
151
+ function pathVerdict(rawFile) {
152
+ let real
153
+ try {
154
+ // 盘符相对写法(`C:node.exe`)交给 resolve 时会被当成 C 盘根下的同名文件,
155
+ // 与 cmd 的语义(C 盘当前目录)不完全一样;这里取保守方向——解析不到就拒。
156
+ real = realpathSync(resolve(rawFile))
157
+ } catch {
158
+ return `命令带了路径,但找不到这个文件,没法确认它在 PATH 里:${rawFile}`
159
+ }
160
+ const win = process.platform === 'win32'
161
+ const target = win ? real.toLowerCase().replace(/[\\/]+$/u, '') : real
162
+ for (const dir of pathDirs()) {
163
+ const probe = win ? dir.toLowerCase().replace(/[\\/]+$/u, '') : dir
164
+ if (probe === '' || target === '') continue
165
+ if (isInside(probe, target)) return ''
166
+ }
167
+ return `命令带了路径,且不在 PATH 或 node 所在目录内:${rawFile}`
168
+ }
169
+
170
+ export function checkDenial(cmd, allowed, options = {}) {
171
+ const list = Array.isArray(allowed) ? allowed : DEFAULT_ALLOWED_COMMANDS
172
+ if (typeof cmd !== 'string' || cmd.trim() === '') return { denied: true, reason: 'check 是空的' }
173
+ const tokens = tokenizeCommand(cmd)
174
+ const name = commandNameOf(tokens[0] ?? '')
175
+ if (name === '') return { denied: true, reason: '认不出命令名' }
176
+ if (!list.includes(name)) {
177
+ return { denied: true, reason: `命令 ${name} 不在白名单里(只放行 ${list.join(' / ')})` }
178
+ }
179
+ const args = tokens.slice(1)
180
+ // 名字在白名单里还有几种绕过路子(npm exec / pnpm dlx / git -c 挂命令)。
181
+ // eval 类开关默认放行——那是写轻量判据的正常写法,见 CODE_ESCAPE_FLAGS 的说明。
182
+ const escape = checkCodeEscape(name, args, options.strictEval === true)
183
+ if (escape.escaped) return { denied: true, reason: escape.reason }
184
+ // 带路径的写法要单独查:名字对不代表跑的就是那个程序。
185
+ // `C:node.exe` 这类盘符相对写法也算路径,不然它绕开这条一路按名字放行。
186
+ const rawFile = tokens[0] ?? ''
187
+ if (isPathLike(rawFile)) {
188
+ const verdict = pathVerdict(rawFile)
189
+ if (verdict !== '') return { denied: true, reason: verdict }
190
+ }
191
+ return { denied: false, name, file: tokens[0], args }
192
+ }
193
+
194
+ /**
195
+ * 把一条参数转成能原样交回给程序的批处理写法。
196
+ *
197
+ * 两层规则叠加,顺序不能反:
198
+ * 1. 批处理先做变量展开,`%` 会被吃掉(`100%` 变 `100`,`%PATH%` 变成路径),
199
+ * 所以先 `%` → `%%`。这一步只看百分号,不参与下面的反斜杠计算。
200
+ * 2. 目标程序按 CommandLineToArgvW / CRT 的规则解析命令行:连续反斜杠只有
201
+ * 在双引号前、或位于参数末尾时才翻倍,双引号本身写成 \"。
202
+ * 以前只把 `"` 换成 `""`,那是给 cmd 内建命令用的写法,交给程序解析时是坏的。
203
+ */
204
+ export function quoteForCmd(arg) {
205
+ const text = String(arg ?? '')
206
+ if (text === '') return '""'
207
+ const escaped = text.replace(/%/gu, '%%')
208
+ let out = '"'
209
+ let slashes = 0
210
+ for (const ch of escaped) {
211
+ if (ch === '\\') {
212
+ slashes += 1
213
+ continue
214
+ }
215
+ if (ch === '"') {
216
+ out += `${'\\'.repeat(slashes * 2 + 1)}"`
217
+ slashes = 0
218
+ continue
219
+ }
220
+ out += '\\'.repeat(slashes) + ch
221
+ slashes = 0
222
+ }
223
+ out += '\\'.repeat(slashes * 2) + '"'
224
+ return out
225
+ }
226
+
227
+ export function resolveWindowsCommand(file, args) {
228
+ const list = Array.isArray(args) ? args : []
229
+ if (process.platform !== 'win32') return { file, args: list, viaCmd: false, resolved: file }
230
+
231
+ const lower = String(file).toLowerCase()
232
+ const isBatch = lower.endsWith('.cmd') || lower.endsWith('.bat')
233
+
234
+ let resolved = file
235
+ if (!isBatch) {
236
+ const found = whichSync(file)
237
+ if (found === undefined) return { file, args: list, viaCmd: false, resolved: file }
238
+ resolved = found
239
+ const foundLower = found.toLowerCase()
240
+ if (!foundLower.endsWith('.cmd') && !foundLower.endsWith('.bat')) {
241
+ // 找到的是 .exe,直接跑,不用过 cmd
242
+ return { file: found, args: list, viaCmd: false, resolved: found }
243
+ }
244
+ }
245
+
246
+ // 写一个临时 bat:把路径和参数原样写进去。
247
+ //
248
+ // 编码是个坑:cmd.exe 默认按系统 ANSI 代码页(简中 Windows 是 GBK/936)读
249
+ // 批处理,写 UTF-8 会让中文路径变成乱码,写 ascii 会丢字。这里用
250
+ // `chcp 65001` 把控制台切到 UTF-8,再以 UTF-8 写文件——这样中文、emoji
251
+ // 路径都不受系统代码页影响。切代码页只影响这个 bat 自己的进程,不外溢。
252
+ let batPath
253
+ try {
254
+ batPath = join(tmpdir(), `pf-run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.bat`)
255
+ const quotedArgs = list.map(part => quoteForCmd(part)).join(' ')
256
+ const body = [
257
+ '@echo off',
258
+ // 延迟展开关掉,否则参数里的 `!` 会被当成变量吃掉。
259
+ 'setlocal DisableDelayedExpansion',
260
+ 'chcp 65001 >nul 2>&1',
261
+ `"${resolved}"${quotedArgs === '' ? '' : ` ${quotedArgs}`}`,
262
+ // 这一行是常量,单独拼,不能进 quoteForCmd 的 % 处理。
263
+ 'exit /b %ERRORLEVEL%',
264
+ ].join('\r\n')
265
+ writeFileSync(batPath, `${body}\r\n`, 'utf8')
266
+ } catch {
267
+ // 写不出临时文件就退回直连,至少 exe 类命令不受影响
268
+ return { file: resolved, args: list, viaCmd: false, resolved }
269
+ }
270
+
271
+ return {
272
+ file: process.env.ComSpec ?? 'cmd.exe',
273
+ args: ['/d', '/s', '/c', batPath],
274
+ viaCmd: true,
275
+ resolved,
276
+ cleanup: () => {
277
+ try { rmSync(batPath, { force: true }) } catch { /* 删不掉就算了,在系统临时目录里 */ }
278
+ },
279
+ }
280
+ }
281
+
282
+ export function whichSync(name) {
283
+ if (typeof name !== 'string' || name === '') return undefined
284
+ if (isAbsolute(name)) return existsSync(name) ? name : undefined
285
+
286
+ const exts = (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(e => e !== '')
287
+ // 名字本身已经带扩展名就只试那一个
288
+ const hasExt = exts.some(ext => name.toLowerCase().endsWith(ext.toLowerCase()))
289
+ const candidates = hasExt ? [name] : exts.map(ext => `${name}${ext.toLowerCase()}`)
290
+
291
+ const dirs = [process.cwd(), ...(process.env.PATH ?? '').split(';').filter(d => d !== '')]
292
+ for (const dir of dirs) {
293
+ for (const candidate of candidates) {
294
+ const full = join(dir, candidate)
295
+ try {
296
+ if (existsSync(full)) return full
297
+ } catch {
298
+ // 这个目录不可访问,试下一个
299
+ }
300
+ }
301
+ }
302
+ return undefined
303
+ }
304
+
305
+ export function defaultSpawnCheck({ file, args, cwd, timeoutMs, env }) {
306
+ const resolved = resolveWindowsCommand(file, args)
307
+ return new Promise(resolve => {
308
+ execFile(resolved.file, resolved.args, {
309
+ cwd,
310
+ timeout: timeoutMs,
311
+ killSignal: 'SIGKILL',
312
+ windowsHide: true,
313
+ maxBuffer: 8 * 1024 * 1024,
314
+ ...(env === undefined ? {} : { env }),
315
+ }, (error, stdout, stderr) => {
316
+ // 临时 bat 用完就删,别在系统临时目录里攒
317
+ if (typeof resolved.cleanup === 'function') resolved.cleanup()
318
+ const output = `${stdout ?? ''}${stderr ?? ''}`
319
+ if (error === null || error === undefined) {
320
+ resolve({ exit: 0, output })
321
+ return
322
+ }
323
+ if (error.code === 'ENOENT') {
324
+ // 说清「找的是哪个文件」:Windows 上常见的坑是 npm 装成了 npm.cmd,
325
+ // 只报一句「命令不存在」会让人去重装,实际是路径没解析到。
326
+ resolve({
327
+ exit: 127,
328
+ output: `${output}${error.message}`,
329
+ missing: true,
330
+ ...(resolved.resolved !== file ? { triedPath: resolved.resolved } : {}),
331
+ })
332
+ return
333
+ }
334
+ const timedOut = error.killed === true || (error.signal !== undefined && error.signal !== null)
335
+ // 超时一律记 124(和 shell timeout 命令一致),不用内核信号码。
336
+ if (timedOut) {
337
+ resolve({ exit: 124, output, timedOut: true })
338
+ return
339
+ }
340
+ if (typeof error.code === 'number') {
341
+ resolve({ exit: error.code, output })
342
+ return
343
+ }
344
+ resolve({ exit: 1, output: `${output}${error.message}` })
345
+ })
346
+ })
347
+ }
348
+
349
+ export async function runRequirementChecks(options) {
350
+ const {
351
+ entries = [],
352
+ cwd,
353
+ allowed = DEFAULT_ALLOWED_COMMANDS,
354
+ strictEval = false,
355
+ timeoutMs = DEFAULT_CHECK_TIMEOUT_MS,
356
+ tailChars = DEFAULT_CHECK_TAIL_CHARS,
357
+ env,
358
+ spawnCheck = defaultSpawnCheck,
359
+ } = options ?? {}
360
+ const assertions = []
361
+ for (const entry of Array.isArray(entries) ? entries : []) {
362
+ const req = Number.isInteger(entry?.req) ? entry.req : assertions.length + 1
363
+ const cmd = typeof entry?.cmd === 'string' ? entry.cmd.trim() : ''
364
+ if (cmd === '') {
365
+ assertions.push({ req, cmd: null, exit: null, durationMs: 0, stdoutTail: '', status: 'unverified' })
366
+ continue
367
+ }
368
+ const denial = checkDenial(cmd, allowed, { strictEval })
369
+ if (denial.denied === true) {
370
+ assertions.push({
371
+ req,
372
+ cmd,
373
+ exit: 126,
374
+ durationMs: 0,
375
+ stdoutTail: `白名单拒绝:${denial.reason}`,
376
+ status: 'denied',
377
+ denied: true,
378
+ })
379
+ continue
380
+ }
381
+ const startedAt = Date.now()
382
+ let run
383
+ try {
384
+ run = await spawnCheck({ file: denial.file, args: denial.args, cwd, timeoutMs, env })
385
+ } catch (error) {
386
+ run = { exit: 1, output: messageOf(error) }
387
+ }
388
+ const durationMs = Date.now() - startedAt
389
+ const expectExit = Number.isInteger(entry?.expectExit) ? entry.expectExit : 0
390
+ const status = run.timedOut === true
391
+ ? 'fail'
392
+ : run.missing === true
393
+ ? 'missing'
394
+ : run.exit === expectExit ? 'pass' : 'fail'
395
+ assertions.push({
396
+ req,
397
+ cmd,
398
+ exit: run.exit ?? null,
399
+ durationMs,
400
+ stdoutTail: tailOf(run.output ?? '', tailChars),
401
+ status,
402
+ ...(run.timedOut === true ? { timeout: true } : {}),
403
+ ...(expectExit === 0 ? {} : { expectExit }),
404
+ })
405
+ }
406
+ const missing = assertions.filter(item => item.status === 'missing')
407
+ const degrade = missing.length > CHECK_MISSING_BINARY_LIMIT
408
+ for (const item of assertions) {
409
+ if (item.status !== 'missing') continue
410
+ // 环境里没有这条命令:少数几条按 FAIL 记(应该是这次实现要用的工具),
411
+ // 成片缺失按 unverified 记(更像是这台机器没装)。
412
+ item.status = degrade ? 'unverified' : 'fail'
413
+ }
414
+ return assertions
415
+ }
416
+
@@ -0,0 +1,91 @@
1
+ /**
2
+ * 要求里的判据:从 Requirement.md 读出来、写回去、算指纹。
3
+ */
4
+ import { createHash } from 'node:crypto'
5
+ import { quoteScalar, splitFrontMatter, unquoteScalar } from '../shared/util.mjs'
6
+
7
+ export function parseRequirementChecks(text) {
8
+ const { front } = splitFrontMatter(text)
9
+ if (front === '') return []
10
+ const entries = []
11
+ let inChecks = false
12
+ let current
13
+ for (const rawLine of front.split(/\r?\n/u)) {
14
+ const line = rawLine.replace(/\s+$/u, '')
15
+ if (/^checks\s*:\s*$/u.test(line)) {
16
+ inChecks = true
17
+ continue
18
+ }
19
+ // 顶格的非空行意味着 checks 这一段结束了。
20
+ if (inChecks && /^\S/u.test(line)) {
21
+ inChecks = false
22
+ current = undefined
23
+ }
24
+ if (!inChecks) continue
25
+ const reqMatch = /^\s*-\s*req\s*:\s*(\d+)\s*$/u.exec(line)
26
+ if (reqMatch !== null) {
27
+ current = { req: Number(reqMatch[1]), cmd: '', expectExit: 0 }
28
+ entries.push(current)
29
+ continue
30
+ }
31
+ if (current === undefined) continue
32
+ const cmdMatch = /^\s+cmd\s*:\s*(.*)$/u.exec(line)
33
+ if (cmdMatch !== null) {
34
+ current.cmd = unquoteScalar(cmdMatch[1])
35
+ continue
36
+ }
37
+ const exitMatch = /^\s+exit\s*:\s*(-?\d+)\s*$/u.exec(line)
38
+ if (exitMatch !== null) current.expectExit = Number(exitMatch[1])
39
+ }
40
+ return entries
41
+ }
42
+
43
+ export function renderRequirementChecks(entries) {
44
+ if (!Array.isArray(entries) || entries.length === 0) return ''
45
+ const lines = ['---', 'checks:']
46
+ for (const entry of entries) {
47
+ lines.push(` - req: ${entry.req}`)
48
+ lines.push(` cmd: ${quoteScalar(entry.cmd ?? '')}`)
49
+ lines.push(` exit: ${Number.isInteger(entry.expectExit) ? entry.expectExit : 0}`)
50
+ }
51
+ lines.push('---')
52
+ return lines.join('\n')
53
+ }
54
+
55
+ export function requirementFingerprint(entries) {
56
+ const list = Array.isArray(entries) ? entries : []
57
+ const canonical = JSON.stringify(
58
+ list.map(entry => ({
59
+ req: Number.isInteger(entry.req) ? entry.req : 0,
60
+ cmd: typeof entry.cmd === 'string' ? entry.cmd : '',
61
+ expectedExit: Number.isInteger(entry.expectExit) ? entry.expectExit : 0,
62
+ })),
63
+ )
64
+ return createHash('sha256').update(canonical, 'utf8').digest('hex')
65
+ }
66
+
67
+ export function buildCheckEntries(requirements, checks) {
68
+ const list = Array.isArray(requirements) ? requirements : []
69
+ const extra = Array.isArray(checks) ? checks : []
70
+ return list.map((line, index) => {
71
+ const text = typeof line === 'string' ? line : String(line ?? '')
72
+ const inline = /(?:\r?\n|\s*\|\|\s*)\s*check\s*:\s*([\s\S]+)$/u.exec(text)
73
+ const fromList = extra.find(item => item !== null && typeof item === 'object' && Number(item.req) === index + 1)
74
+ const listed = fromList !== undefined && typeof fromList.check === 'string' && fromList.check.trim() !== ''
75
+ ? fromList.check.trim()
76
+ : ''
77
+ const cmd = listed !== '' ? listed : inline === null ? '' : inline[1].trim()
78
+ // checks 列表中 exit 等价于 checkExit:两个字段都接收,checkExit 优先,缺省均为 0
79
+ const rawExit = fromList !== undefined
80
+ ? (Number.isInteger(Number(fromList.checkExit)) ? fromList.checkExit : (Number.isInteger(Number(fromList.exit)) ? fromList.exit : undefined))
81
+ : undefined
82
+ const expectExit = Number.isInteger(Number(rawExit)) ? Number(rawExit) : 0
83
+ return { req: index + 1, cmd, expectExit }
84
+ })
85
+ }
86
+
87
+ export function stripInlineCheck(line) {
88
+ const text = typeof line === 'string' ? line : String(line ?? '')
89
+ return text.replace(/(?:\r?\n|\s*\|\|\s*)\s*check\s*:\s*[\s\S]+$/u, '').trim()
90
+ }
91
+