sillyspec 3.26.10 → 3.26.13

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 (101) hide show
  1. package/.claude/skills/sillyspec-archive/SKILL.md +85 -85
  2. package/.claude/skills/sillyspec-brainstorm/SKILL.md +114 -114
  3. package/.claude/skills/sillyspec-commit/SKILL.md +109 -109
  4. package/.claude/skills/sillyspec-continue/SKILL.md +45 -45
  5. package/.claude/skills/sillyspec-doctor/SKILL.md +76 -76
  6. package/.claude/skills/sillyspec-execute/SKILL.md +200 -200
  7. package/.claude/skills/sillyspec-explore/SKILL.md +95 -95
  8. package/.claude/skills/sillyspec-knowledge/SKILL.md +269 -269
  9. package/.claude/skills/sillyspec-plan/SKILL.md +148 -148
  10. package/.claude/skills/sillyspec-quick/SKILL.md +115 -111
  11. package/.claude/skills/sillyspec-resume/SKILL.md +68 -68
  12. package/.claude/skills/sillyspec-scan/SKILL.md +79 -79
  13. package/.claude/skills/sillyspec-state/SKILL.md +64 -64
  14. package/.claude/skills/sillyspec-status/SKILL.md +54 -54
  15. package/.claude/skills/sillyspec-verify/SKILL.md +83 -83
  16. package/.claude/skills/sillyspec-workspace/SKILL.md +169 -169
  17. package/.gitattributes +2 -0
  18. package/.husky/pre-push +20 -20
  19. package/README.md +203 -201
  20. package/SKILL.md +91 -90
  21. package/package.json +39 -39
  22. package/packages/dashboard/dist/assets/index-Bq_Z2hne.js +7446 -7446
  23. package/packages/dashboard/dist/assets/index-O2W5RV4z.css +1 -1
  24. package/packages/dashboard/dist/index.html +16 -16
  25. package/packages/dashboard/package.json +25 -25
  26. package/packages/dashboard/server/executor.js +95 -86
  27. package/packages/dashboard/server/index.js +663 -601
  28. package/packages/dashboard/server/parser.js +526 -526
  29. package/src/change-risk-profile.js +254 -254
  30. package/src/classify-change.js +109 -109
  31. package/src/config-schema.js +313 -310
  32. package/src/contract-matrix.js +388 -379
  33. package/src/db.js +370 -350
  34. package/src/dispatch/backends/local-agent.js +155 -155
  35. package/src/dispatch/backends/sillyhub-mcp.js +245 -245
  36. package/src/dispatch/probe.js +246 -210
  37. package/src/dispatch/strategy.js +121 -121
  38. package/src/docs-check.js +188 -16
  39. package/src/docs-debt.js +6 -2
  40. package/src/docs-gate.js +1 -0
  41. package/src/doctor-diagnostics.js +898 -711
  42. package/src/endpoint-extractor.js +401 -401
  43. package/src/fs-atomic.js +71 -69
  44. package/src/git-helper.js +82 -79
  45. package/src/hooks/claude-pre-tool-use.cjs +125 -125
  46. package/src/hooks/worktree-guard.js +854 -848
  47. package/src/index.js +251 -20
  48. package/src/init.js +624 -623
  49. package/src/knowledge-match.js +130 -130
  50. package/src/local-detect.js +128 -120
  51. package/src/machine-interface.js +543 -543
  52. package/src/migrate.js +127 -127
  53. package/src/modules.js +7 -5
  54. package/src/progress/change-registry.js +297 -260
  55. package/src/progress/consistency-doctor.js +355 -355
  56. package/src/progress/shared.js +36 -36
  57. package/src/progress/stage-machine.js +589 -550
  58. package/src/progress/step-store.js +261 -261
  59. package/src/progress.js +1285 -1127
  60. package/src/quicklog.js +724 -693
  61. package/src/review-tier.js +77 -77
  62. package/src/run/command.js +1408 -1364
  63. package/src/run/complete-handlers.js +1450 -1399
  64. package/src/run/complete.js +1181 -920
  65. package/src/run/gates.js +878 -755
  66. package/src/run/prompt.js +765 -761
  67. package/src/run/quick-audit.js +155 -146
  68. package/src/run/shared.js +1348 -1215
  69. package/src/run/stage.js +527 -479
  70. package/src/scan-postcheck.js +371 -371
  71. package/src/setup.js +414 -416
  72. package/src/sillyhub-mcp/client.js +597 -529
  73. package/src/spec-dir-typo.js +3 -24
  74. package/src/spec-sync.js +358 -319
  75. package/src/stage-contract.js +871 -897
  76. package/src/stage-review.js +549 -549
  77. package/src/stages/archive.js +156 -155
  78. package/src/stages/brainstorm-auto.js +236 -236
  79. package/src/stages/brainstorm.js +597 -597
  80. package/src/stages/cmd-existence.js +145 -145
  81. package/src/stages/doctor.js +386 -371
  82. package/src/stages/execute.js +1014 -1003
  83. package/src/stages/explore.js +34 -34
  84. package/src/stages/index.js +29 -29
  85. package/src/stages/knowledge.js +498 -498
  86. package/src/stages/plan-postcheck.js +1323 -1302
  87. package/src/stages/plan.js +642 -623
  88. package/src/stages/quick.js +153 -151
  89. package/src/stages/scan.js +607 -607
  90. package/src/stages/status.js +64 -64
  91. package/src/stages/verify.js +264 -264
  92. package/src/sync.js +1325 -1135
  93. package/src/task-review.js +1204 -1019
  94. package/src/taskcard.js +178 -0
  95. package/src/verify-postcheck.js +1199 -1186
  96. package/src/workflow.js +600 -600
  97. package/src/worktree-apply.js +1237 -1136
  98. package/src/worktree-deps.js +453 -353
  99. package/src/worktree.js +1527 -1481
  100. package/templates/workflows/archive-impact.yaml +79 -79
  101. package/templates/workflows/scan-docs.yaml +132 -132
@@ -1,1186 +1,1199 @@
1
- /**
2
- * Verify Postcheck — CLI 客观测试执行与自报告对账
3
- *
4
- * verify 阶段历史上完全依赖 agent 自报告(跑没跑测试、结果如何全写在
5
- * verify-result.md 里),可被文案绕过。此模块让 CLI 在 verify 完成时
6
- * 亲自执行 local.yaml 配置的测试命令,与 verify-result.md 的结论对账:
7
- * 自报告 PASS 但实测失败 → 阻断 verify 完成。
8
- *
9
- * 未配置 commands.test(或标记 unavailable)时降级为 warning 不阻断,
10
- * 兼容无测试项目。
11
- *
12
- * test_strategy 支持(D-002@v1):
13
- * - full(默认):整跑 commands.test(brownfield 行为不变)
14
- * - module:按 local.yaml modules 映射,仅跑 git diff 命中的模块子集
15
- * 测试,避免 monorepo 全量测试超 gate timeout。
16
- */
17
-
18
- import { execSync, execFileSync } from 'child_process'
19
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
20
- import { join } from 'path'
21
- import { verifyApiParity } from './contract-matrix.js'
22
- import { parseFileChangeListDetailed, pathMatches } from './change-list.js'
23
- import { filterDeliverableFiles } from './worktree-apply.js'
24
-
25
- // 测试命令最长执行时间;超时视为失败(防止 CLI 被挂起的测试卡死)
26
- const TEST_TIMEOUT_MS = Number(process.env.SILLYSPEC_TEST_TIMEOUT_MS) || 10 * 60 * 1000
27
- const OUTPUT_TAIL_CHARS = 4000
28
-
29
- /**
30
- * 从 local.yaml 文本提取 commands.test。
31
- * 轻量正则(与 worktree-deps/scan-postcheck 同风格,不引 yaml 依赖):
32
- * 支持带引号与不带引号两种写法;'unavailable' 视为未配置。
33
- */
34
- export function extractTestCommand(yamlText) {
35
- if (!yamlText) return null
36
- const doubleQuoted = yamlText.match(/^\s*test:\s*"([^"]+)"\s*(?:#.*)?$/m)
37
- const singleQuoted = yamlText.match(/^\s*test:\s*'([^']+)'\s*(?:#.*)?$/m)
38
- const quoted = doubleQuoted || singleQuoted
39
- if (quoted && quoted[1]) {
40
- return quoted[1].toLowerCase() === 'unavailable' ? null : quoted[1].trim()
41
- }
42
- const bare = yamlText.match(/^\s*test:\s*([^\n#"']+?)\s*(?:#.*)?$/m)
43
- if (bare && bare[1]) {
44
- const cmd = bare[1].trim()
45
- return cmd.toLowerCase() === 'unavailable' ? null : cmd
46
- }
47
- return null
48
- }
49
-
50
- /**
51
- * 从 local.yaml 文本提取顶层 test_strategy。
52
- * 轻量正则(与 extractTestCommand 同风格,不引 yaml 依赖)。
53
- *
54
- * @param {string} yamlText
55
- * @returns {'full'|'module'|null} - 解析到的策略;缺省/无法解析返回 null(调用方按 full 处理)
56
- */
57
- export function extractTestStrategy(yamlText) {
58
- if (!yamlText) return null
59
- const m = yamlText.match(/^\s*test_strategy:\s*([A-Za-z_]+)\s*(?:#.*)?$/m)
60
- if (!m || !m[1]) return null
61
- const v = m[1].trim().toLowerCase()
62
- if (v === 'module') return 'module'
63
- if (v === 'full') return 'full'
64
- return null
65
- }
66
-
67
- /**
68
- * 计算全量 fallback 的原因文本(供 printVerifyTestCheck / facet 给 agent/daemon 明示)。
69
- *
70
- * 返回 null 表示不需要 hint:显式 test_strategy:full(用户有意跑全量),
71
- * 或 test_strategy:module 已成功命中模块子集(该情况不会走到全量路径)。
72
- * 其余走全量路径的情况都返回原因字符串,让结果可正确解读——
73
- * 否则 agent/daemon 会把"全量 commands.test"当成"按变更范围测的",误把
74
- * 未变更模块的预存错误归因到本次变更(见 3.24 verify 坑1)。
75
- *
76
- * 语义对齐 runVerifyTestCheck 的分支:
77
- * - strategy==='full' → null
78
- * - strategy==='module' 但无有效 modules 块 → hint
79
- * - strategy==='module' 有块但 git 不可用(hitCount=-1)→ hint
80
- * - strategy==='module' 有块但 0 命中(hitCount=0)→ hint
81
- * - strategy==='module' 有块且命中(hitCount>0)→ null(走子集)
82
- * - strategy===null(缺省)→ hint(默认全量)
83
- *
84
- * @param {object} ctx
85
- * @param {'full'|'module'|null} ctx.strategy
86
- * @param {boolean} ctx.modulesPresent - extractModules 是否返回有效映射
87
- * @param {number} ctx.hitCount - git diff 命中的模块数;-1 表示 git 不可用/非仓库
88
- * @returns {string|null}
89
- */
90
- export function computeFullFallbackReason({ strategy, modulesPresent, hitCount }) {
91
- if (strategy === 'full') return null
92
- if (strategy === 'module') {
93
- if (!modulesPresent) {
94
- return 'test_strategy: module 但 local.yaml 未配置有效的 modules: 块(需 inline flow: name: { path, test }),回退全量'
95
- }
96
- if (hitCount < 0) {
97
- return 'test_strategy: module 但 git 不可用/非 git 仓库,无法判定命中模块,回退全量'
98
- }
99
- if (hitCount === 0) {
100
- return 'test_strategy: module 但本次 git diff 未命中任何已配置 modules,回退全量'
101
- }
102
- return null
103
- }
104
- // strategy === null(缺省 → 默认全量)
105
- return 'local.yaml 未配置 test_strategy(默认全量 commands.test,未按变更范围收窄)'
106
- }
107
-
108
- /**
109
- * 从 local.yaml 文本解析 modules 映射块。
110
- * 设计约定(见 change 2026-07-10-tooling-followups design.md #2 方案 A):
111
- *
112
- * modules:
113
- * backend: { path: "backend/", test: "cd backend && uv run pytest" }
114
- * frontend: { path: "frontend/", test: "cd frontend && pnpm test" }
115
- *
116
- * 每个模块一行 inline flow mapping,含 path 与 test 两个键。
117
- * 轻量行扫描(与 modules.js parseModuleMapSimple 同风格,不引 yaml 依赖)。
118
- *
119
- * @param {string} yamlText
120
- * @returns {Record<string, {path:string, test:string}>|null}
121
- * - 找不到 modules 块 → null(调用方 fallback commands.test)
122
- * - 找到块但无有效条目 → null
123
- */
124
- export function extractModules(yamlText) {
125
- if (!yamlText) return null
126
- const lines = yamlText.split('\n')
127
-
128
- // 定位 modules: 起始行(必须是顶层 key,行首无缩进或仅注释后顶层)
129
- let startIdx = -1
130
- for (let i = 0; i < lines.length; i++) {
131
- const m = lines[i].match(/^modules:\s*(?:#.*)?$/)
132
- if (m) { startIdx = i; break }
133
- }
134
- if (startIdx === -1) return null
135
-
136
- const modules = {}
137
- for (let i = startIdx + 1; i < lines.length; i++) {
138
- const line = lines[i]
139
- // 子条目:以 2 空格缩进 + key + ':' 开头
140
- const entry = line.match(/^ ([A-Za-z0-9_.\-]+):\s*(.*)$/)
141
- if (!entry) {
142
- // 遇到新的顶层 key(行首非空格且非注释)→ modules 块结束
143
- if (line.length > 0 && !line.startsWith(' ') && !line.startsWith('#') && line.trim() !== '') break
144
- continue
145
- }
146
- const name = entry[1]
147
- const rest = entry[2].trim()
148
- if (rest === '' || rest.startsWith('#')) continue // 子块展开式(本实现只支持 inline flow)
149
- // 解析 inline flow mapping: { path: "...", test: "..." }
150
- const pathVal = parseFlowValue(rest, 'path')
151
- const testVal = parseFlowValue(rest, 'test')
152
- if (pathVal && testVal) {
153
- modules[name] = { path: pathVal, test: testVal }
154
- }
155
- }
156
-
157
- return Object.keys(modules).length > 0 ? modules : null
158
- }
159
-
160
- /**
161
- * 从 inline flow mapping 文本(如 `{ path: "backend/", test: "cd ..." }`)
162
- * 提取指定键的值。支持双引号/单引号/bare 值。
163
- */
164
- function parseFlowValue(flowText, key) {
165
- // 键可能带引号也可能不带:path: "x" 或 "path": "x"
166
- const re = new RegExp(String.raw`(?:^|[{,]\s*)"?${key}"?\s*:\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|(?:[^,}]+?))\s*(?=[,}]|$)`)
167
- const m = flowText.match(re)
168
- if (!m) return null
169
- let v = m[1].trim()
170
- if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
171
- v = v.slice(1, -1)
172
- }
173
- return v.length > 0 ? v : null
174
- }
175
-
176
- /**
177
- * 根据变更文件列表 + modules 映射,算出被命中的模块(去重保序)。
178
- * 文件路径以 module.path 为前缀(含子目录)即视为命中。
179
- *
180
- * @param {string[]} changedFiles - git diff 产出的相对路径列表
181
- * @param {Record<string, {path:string, test:string}>} modules - extractModules 解析结果
182
- * @returns {Array<{name:string, path:string, test:string}>} - 命中的模块(按 modules 声明顺序去重)
183
- */
184
- export function pickHitModules(changedFiles, modules) {
185
- if (!Array.isArray(changedFiles) || changedFiles.length === 0) return []
186
- if (!modules || typeof modules !== 'object') return []
187
-
188
- const files = changedFiles.map(f => String(f).replace(/\\/g, '/'))
189
- const hits = []
190
- for (const [name, mod] of Object.entries(modules)) {
191
- if (!mod || !mod.path) continue
192
- const modPath = String(mod.path).replace(/\\/g, '/')
193
- const prefix = modPath.endsWith('/') ? modPath : modPath + '/'
194
- // path 本身被改 或 path/ 下任意文件被改
195
- const hit = files.some(f => f === modPath || f.startsWith(prefix))
196
- if (hit) hits.push({ name, path: modPath, test: mod.test })
197
- }
198
- return hits
199
- }
200
-
201
- /**
202
- * 聚合多个模块测试结果为单一 status。
203
- * - 全 passed → 'passed'
204
- * - 任一 failed → 'failed'
205
- * - 空 → null(调用方按 fallback 处理)
206
- *
207
- * @param {Array<{status:'passed'|'failed'}>} results
208
- * @returns {'passed'|'failed'|null}
209
- */
210
- export function aggregateStatus(results) {
211
- if (!Array.isArray(results) || results.length === 0) return null
212
- if (results.every(r => r && r.status === 'passed')) return 'passed'
213
- return 'failed'
214
- }
215
-
216
- /**
217
- * 从 local.yaml 提取 known_failures 声明(预存失败豁免清单,坑 verify-worktree-... 修复方向 2)。
218
- * 支持块式与流式两种写法:
219
- * known_failures:
220
- * - "tests/test_ppm.py::test_legacy"
221
- * - app/modules/plan/test_old
222
- * 或 known_failures: [a, b]
223
- * 每条作为子串(大小写不敏感)匹配测试输出中的失败行。
224
- *
225
- * @param {string} yamlText
226
- * @returns {string[]} 模式列表;无声明返回 []
227
- */
228
- export function extractKnownFailures(yamlText) {
229
- if (!yamlText) return []
230
- const inline = yamlText.match(/^known_failures:\s*\[([^\]]*)\]\s*(?:#.*)?$/m)
231
- if (inline) {
232
- return inline[1].split(',').map(s => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean)
233
- }
234
- const block = yamlText.match(/^known_failures:\s*\n((?:[ \t]+-[ \t].+\n?)+)/m)
235
- if (block) {
236
- return (block[1].match(/^[ \t]+-[ \t]+(.+)/gm) || [])
237
- .map(s => s.replace(/^[ \t]+-[ \t]+/, '').trim().replace(/^['"]|['"]$/g, '').replace(/#.*$/, '').trim())
238
- .filter(Boolean)
239
- }
240
- return []
241
- }
242
-
243
- // 单条失败行标记(跨 pytest/jest/vitest/go/generic)。大小写不敏感。
244
- // 刻意用 FAIL/FAILED + 配合 SUMMARY_LINE_RE 排除汇总行:否则 pytest/jest 的
245
- // "N failed" 汇总会被误判为「需豁免的失败行」→ 永远 remaining>0 → known_failures 失效。
246
- const PER_TEST_FAIL_RE = /(FAILED|\bFAIL\b|✕|✗|✘|panic\s*:|assertionerror|traceback|---\s*fail|error:|exception)/i
247
- // 汇总/计数行(非单条失败):pytest === 框、jest "Tests:"、裸 "N failed/passed"、go "FAILED in Ns" 等。
248
- const SUMMARY_LINE_RE = /(={2,}.*={2,}|^\s*\d+\s+(failed|passed|skipped|pending)\b|tests?\s*:|test\s+suites?\s*:|failed\s+in\s+\d)/i
249
-
250
- /**
251
- * 把测试输出按行筛出「失败行」,再按 known_failures 模式分为已豁免 / 未豁免。
252
- * @param {string} output
253
- * @param {string[]} knownFailures 子串模式列表(大小写不敏感)
254
- * @returns {{ failureLines: string[], exempted: string[], remaining: string[] }}
255
- */
256
- export function partitionFailures(output, knownFailures) {
257
- const lines = String(output || '').split(/\r?\n/)
258
- const failureLines = lines.filter(l => PER_TEST_FAIL_RE.test(l) && !SUMMARY_LINE_RE.test(l))
259
- const pats = (knownFailures || []).map(p => String(p).toLowerCase()).filter(Boolean)
260
- const exempted = []
261
- const remaining = []
262
- for (const l of failureLines) {
263
- const ll = l.toLowerCase()
264
- if (pats.some(p => ll.includes(p))) exempted.push(l)
265
- else remaining.push(l)
266
- }
267
- return { failureLines, exempted, remaining }
268
- }
269
-
270
- /**
271
- * 结合 known_failures 判定单次测试运行的状态(fail-safe)。
272
- * - exitCode 0 → passed
273
- * - exitCode≠0 且无 known_failures → failed(原行为)
274
- * - exitCode≠0 且有 known_failures:
275
- * 检测到失败行且全部命中豁免 → passed(披露:请人工复核清单是否过宽)
276
- * 有未豁免失败行 / 检测不到失败行(保守)→ failed
277
- * fail-safe:检测不到失败行绝不自动 pass(避免解析盲区导致假 PASS)。
278
- *
279
- * @returns {{ status: 'passed'|'failed', reason: string|null, exemptedCount: number }}
280
- */
281
- export function judgeWithKnownFailures(exitCode, output, baseReason, knownFailures) {
282
- if (exitCode === 0) return { status: 'passed', reason: baseReason, exemptedCount: 0 }
283
- if (!knownFailures || knownFailures.length === 0) {
284
- return { status: 'failed', reason: baseReason, exemptedCount: 0 }
285
- }
286
- const { failureLines, exempted, remaining } = partitionFailures(output, knownFailures)
287
- if (failureLines.length > 0 && remaining.length === 0) {
288
- return {
289
- status: 'passed',
290
- reason: `全部 ${failureLines.length} 个失败行命中 known_failures 已豁免(${exempted.length} 条)— 请人工复核豁免清单是否过宽`,
291
- exemptedCount: exempted.length,
292
- }
293
- }
294
- // 剩余未豁免失败行:列出具体行 + 预存债指引(坑 verify-known-failures-stale-list)。
295
- // known_failures 清单常滞后于新预存测试 → 同源预存债漏入清单,agent 跑完才发现要手动补。
296
- // 这里点出具体未命中行,让 agent 一眼分辨"补清单 vs 修代码",不替它判断(确定性:列已算出的 remaining)。
297
- let detail
298
- if (remaining.length > 0) {
299
- const sample = remaining.slice(0, 5).map(l => {
300
- const t = String(l).trim()
301
- return t.length > 120 ? t.slice(0, 120) + '…' : t
302
- })
303
- const more = remaining.length > 5 ? `\n …(其余 ${remaining.length - 5} 行见上方测试输出)` : ''
304
- detail = `${remaining.length} 个失败行未命中 known_failures 清单:\n - ${sample.join('\n - ')}${more}\n → 若是预存债(变更前就失败),加入 local.yaml 的 known_failures 清单;若是本次变更引入的真实失败,请修复`
305
- } else {
306
- detail = '失败输出未检测到可豁免的失败行(保守判 fail)'
307
- }
308
- return {
309
- status: 'failed',
310
- reason: baseReason ? `${baseReason}(${detail})` : detail,
311
- exemptedCount: exempted.length,
312
- }
313
- }
314
-
315
- /**
316
- * 决定 verify 实测的执行动作(纯函数,便于测试;坑 verify-worktree-... 修复方向 3)。
317
- * - module + 命中模块 → 'module-subset'
318
- * - module + 0 命中 → 'module-zero-hit-skip'(不静默回退注定超时/预存失败的全量)
319
- * - 其余(full / module 无块 / module git 不可用 hitCount=-1)→ 'full'
320
- * @returns {'module-subset'|'module-zero-hit-skip'|'full'}
321
- */
322
- export function decideVerifyTestAction({ strategy, modulesPresent, hitCount }) {
323
- if (strategy === 'module' && modulesPresent) {
324
- if (hitCount > 0) return 'module-subset'
325
- if (hitCount === 0) return 'module-zero-hit-skip'
326
- return 'full' // hitCount === -1(git 不可用)→ 落全量兜底
327
- }
328
- return 'full'
329
- }
330
-
331
- /**
332
- * 跑单个模块的 test 命令(串行调用方逐个调用)。
333
- * @returns {{name, status:'passed'|'failed', command, exitCode, durationMs, outputTail, reason}}
334
- */
335
- function runOneModule(name, testCommand, cwd, knownFailures = []) {
336
- const startedAt = Date.now()
337
- let exitCode = 0
338
- let output = ''
339
- let reason = null
340
- try {
341
- output = execSync(testCommand, {
342
- cwd,
343
- encoding: 'utf8',
344
- timeout: TEST_TIMEOUT_MS,
345
- maxBuffer: 32 * 1024 * 1024,
346
- stdio: ['ignore', 'pipe', 'pipe'],
347
- })
348
- } catch (e) {
349
- exitCode = typeof e.status === 'number' ? e.status : 1
350
- output = [e.stdout, e.stderr].filter(Boolean).join('\n') || e.message
351
- reason = e.signal === 'SIGTERM' && Date.now() - startedAt >= TEST_TIMEOUT_MS
352
- ? `模块 ${name} 测试超时(>${TEST_TIMEOUT_MS / 1000}s)`
353
- : `模块 ${name} 测试退出码 ${exitCode}`
354
- }
355
- const durationMs = Date.now() - startedAt
356
- const outputTail = output.length > OUTPUT_TAIL_CHARS ? '…' + output.slice(-OUTPUT_TAIL_CHARS) : output
357
- const judged = judgeWithKnownFailures(exitCode, output, reason, knownFailures)
358
- return {
359
- name,
360
- status: judged.status,
361
- command: testCommand,
362
- exitCode,
363
- durationMs,
364
- outputTail,
365
- reason: judged.reason,
366
- exemptedCount: judged.exemptedCount,
367
- }
368
- }
369
-
370
- // refSpec 来源 meta.json(agent 可写),仅放行 git ref/range 安全字符(含 HEAD~1..HEAD 类区间),
371
- // 防经 shell 的命令/参数注入。剥空白与引号/分号/反引号/$ 等 shell 元字符。
372
- // 注:允许 ".."/"../.."(相对路径 ref 语法上合法)不影响安全——execFileSync 数组形式下它只是
373
- // 一个 git rev 参数,git 自会报 not a valid ref,无 shell 解释面。
374
- function assertSafeRefSpec(refSpec) {
375
- if (typeof refSpec !== 'string') return null
376
- if (!/^[A-Za-z0-9._~/^-]+$/.test(refSpec)) return null
377
- if (/~~/.test(refSpec)) return null // 连续 ~(垃圾串)
378
- return refSpec
379
- }
380
-
381
- /**
382
- * 在指定 cwd 跑 `git diff --name-only <refSpec>`,返回相对仓库根的文件列表。
383
- * git 不可用 / 非仓库 / ref 无效 → 返回 null(调用方 fallback)。
384
- */
385
- function runGitDiffNameOnly(cwd, refSpec) {
386
- try {
387
- const ref = refSpec ? assertSafeRefSpec(refSpec) : null
388
- if (refSpec && !ref) return null
389
- const args = ['diff', '--name-only']
390
- if (ref) args.push(ref)
391
- const out = execFileSync('git', args, {
392
- cwd,
393
- encoding: 'utf8',
394
- timeout: 30 * 1000,
395
- stdio: ['ignore', 'pipe', 'pipe'],
396
- })
397
- return out.split('\n').map(l => l.trim()).filter(Boolean)
398
- } catch {
399
- return null
400
- }
401
- }
402
-
403
- /**
404
- * 在指定 cwd 跑 `git diff --name-status <refSpec>`,返回原始文本(调用方按行解析,
405
- * 保留状态字母 D/R/C 供删除探针识别删除/重命名)。git 不可用 / 非仓库 / ref 无效 → 返回 null。
406
- */
407
- function runGitDiffNameStatus(cwd, refSpec) {
408
- try {
409
- const ref = refSpec ? assertSafeRefSpec(refSpec) : null
410
- if (refSpec && !ref) return null
411
- const args = ['diff', '--name-status']
412
- if (ref) args.push(ref)
413
- return execFileSync('git', args, {
414
- cwd,
415
- encoding: 'utf8',
416
- timeout: 30 * 1000,
417
- stdio: ['ignore', 'pipe', 'pipe'],
418
- })
419
- } catch {
420
- return null
421
- }
422
- }
423
-
424
- /**
425
- * 取主工作区 git 变更文件列表(unstaged + staged,相对仓库根)。
426
- * `git diff --name-only HEAD` 同时覆盖已暂存与未暂存改动(相对 HEAD),
427
- * 最适合 brownfield(apply 后未 commit / in-place 改动)场景。
428
- * git 不可用 / 非仓库 → 返回 null(调用方 fallback)。
429
- *
430
- * 注意:worktree 隔离模式下主仓只剩 .sillyspec/ 文档改动、代码在 worktree,
431
- * 本函数看不到——runVerifyTestCheck 用 resolveVerifyChangedFiles 统一处理。
432
- */
433
- function gitChangedFiles(cwd) {
434
- const head = runGitDiffNameOnly(cwd, 'HEAD')
435
- if (head !== null) return head
436
- // HEAD 不存在(空仓库)或 git 不可用 → 尝试纯 unstaged
437
- return runGitDiffNameOnly(cwd, '')
438
- }
439
-
440
- /**
441
- * 解析 verify 对账用的变更文件集(worktree-aware)。
442
- *
443
- * worktree 隔离模式下 execute 的代码改动落在 worktree,主仓工作区只剩
444
- * .sillyspec/ 文档改动。若仍用主仓 `git diff --name-only HEAD`,hitCount=0
445
- * → 回退注定超时且含预存失败的全量 commands.test → verify 完成被阻断
446
- * (坑 verify-worktree-mode-test-reconciliation-fallback-full)。
447
- *
448
- * 判定(与 checkExecuteCodeEvidence / task-review 同源,meta.json 为权威):
449
- * 1. change 有 worktree meta 且 baseHash 存在 → 在 worktree(或 in-place 的 cwd)
450
- * 跑 `git diff --name-only <baseHash>..HEAD` 取真实代码改动集
451
- * ⚠️ baseline checkpoint 修复:优先用 baselineCommit/actualBaseHash(baseline overlay
452
- * 之后),否则 baseHash(pre-baseline)会把 baseline 同步的跨模块文件算进 verify diff
453
- * → 命中无关模块(如 ppm 变更误测 daemon/frontend)。与 task-review.js 同源。
454
- * 2. 无 worktree meta / diff 异常 → 主仓 `git diff --name-only HEAD`(brownfield 原行为)
455
- *
456
- * 跨仓支持(task-06 / D-004 / design §6 A6):ctx 参数可选,缺省走单仓原逻辑(零回归,
457
- * GOAL-2)。ctx 非空且含跨仓 entry 时,主仓 diff 走原逻辑,再 per-repo 在各跨仓仓
458
- * gitDir 跑 `git diff --name-only HEAD` 合并入结果(design §6 行 136 「per-repo 取 diff
459
- * 合并」字面契约)。跨仓仓 diff 路径相对各自仓根。
460
- *
461
- * 注:runVerifyTestCheck 的 module 子集策略只消费主仓 diff(跨仓仓不参与 module 子集,
462
- * 跨仓仓无 module 映射,design §6 + §5.4),故本函数的跨仓合并 diff 在 module 子集
463
- * 路径无副作用——本函数仅供「per-repo diff 合并」语义契约 + 未来 consumer 复用。
464
- *
465
- * @param {string} cwd - 项目根目录(主仓)
466
- * @param {string|null} changeName
467
- * @param {object|null} [ctx] - MultiRepoContext 实例(可选,缺省/null 走单仓原逻辑)
468
- * @returns {string[]|null} 变更文件列表;git 不可用返回 null(调用方按 hitCount=-1 处理)
469
- */
470
- export function resolveVerifyChangedFiles(cwd, changeName, ctx = null) {
471
- // 主仓 diff(原逻辑不动,单仓零回归)
472
- const mainFiles = resolveMainChangedFiles(cwd, changeName)
473
-
474
- // 无 ctx / ctx 无跨仓 entry → 主仓 diff 即结果(零回归)
475
- if (!ctx || typeof ctx.repos !== 'object' || ctx.repos === null) return mainFiles
476
- const crossEntries = []
477
- for (const entry of ctx.repos.values()) {
478
- if (entry && entry.isMain === false) crossEntries.push(entry)
479
- }
480
- if (crossEntries.length === 0) return mainFiles
481
-
482
- // 主仓 git 不可用(null)→ 不强制兜底,保留 null 语义让调用方按 hitCount=-1 处理。
483
- // 跨仓仓 diff 各自取,任一可用即合并;全不可用且主仓 null → 返 null。
484
- // 跨仓仓 diff 锚点:HEAD~1..HEAD(跨仓 task 子代理 commit 到主干,verify 时最近一笔 commit
485
- // 即本次 task 改动;多 task 同仓时仅反映最近一笔,精确范围由 task 卡 base/head 锡点锚定,
486
- // 那是 task-04 的 scope,本函数不消费锡点——跨仓合并 diff 在 verify-postcheck 内仅供
487
- // 「per-repo diff 合并」语义契约 + 未来 consumer,module 子集只用主仓 diff)。
488
- const merged = mainFiles ? mainFiles.slice() : []
489
- let anyAvailable = mainFiles !== null
490
- for (const entry of crossEntries) {
491
- // 跨仓仓 gitDir = 跨仓仓根(MultiRepoContext._buildCrossRepoEntry 已 fail-closed 保证可达)
492
- const files = runGitDiffNameOnly(entry.gitDir, 'HEAD~1..HEAD')
493
- if (files !== null) {
494
- anyAvailable = true
495
- for (const f of files) {
496
- if (!merged.includes(f)) merged.push(f)
497
- }
498
- }
499
- }
500
- return anyAvailable ? merged : null
501
- }
502
-
503
- /**
504
- * 主仓变更文件解析(原 resolveVerifyChangedFiles 逻辑,单仓零回归基线)。
505
- * 抽出供 resolveVerifyChangedFiles 复用,跨仓合并时主仓部分走此函数(不动)。
506
- *
507
- * @param {string} cwd - 主仓根
508
- * @param {string|null} changeName
509
- * @returns {string[]|null}
510
- */
511
- function resolveMainChangedFiles(cwd, changeName) {
512
- if (changeName) {
513
- const metaPath = join(cwd, '.sillyspec', '.runtime', 'worktrees', changeName, 'meta.json')
514
- if (existsSync(metaPath)) {
515
- let meta = null
516
- try { meta = JSON.parse(readFileSync(metaPath, 'utf8')) } catch {}
517
- // 优先 baselineCommit/actualBaseHash(baseline checkpoint 之后),回退 baseHash
518
- const diffBase = meta?.baselineCommit || meta?.actualBaseHash || meta?.baseHash
519
- if (diffBase) {
520
- const gitDir = (meta.worktreePath && meta.mode !== 'in-place-fallback' && existsSync(meta.worktreePath))
521
- ? meta.worktreePath
522
- : cwd
523
- const files = runGitDiffNameOnly(gitDir, `${diffBase}..HEAD`)
524
- if (files !== null) return files
525
- // worktree diff 异常 → 落主仓兜底(保持与原 gitChangedFiles 相同的 null 语义)
526
- }
527
- }
528
- }
529
- return gitChangedFiles(cwd)
530
- }
531
-
532
- /**
533
- * 执行 verify 实测:读取 local.yaml 配置,按 test_strategy 决定全量或模块子集。
534
- *
535
- * 跨仓支持(task-06 / D-004 / design §5.4 + §6 A6 + §9):opts.ctx 可选,缺省走单仓
536
- * 原逻辑(零回归,GOAL-2)。ctx 非空且含跨仓 entry 时,主仓跑原 module 子集 / full npm
537
- * test(行为不变),再 per-repo cwd 在各跨仓仓根跑 full npm test(跨仓仓不参与 module
538
- * 子集策略——跨仓仓无主仓的 module 映射,design §6 + §5.4);跨仓仓无 package.json 则
539
- * 跳过 + warn 不阻断 verify(design §9 兼容策略「跨仓仓无 package.json 跳过 warn」)。
540
- * 任一仓 fail → 整体 fail(fail-fast 语义,跨仓仓的真实失败不能被主仓 PASS 掩盖)。
541
- *
542
- * @param {object} opts
543
- * @param {string} opts.cwd - 项目根目录(主仓,测试执行目录)
544
- * @param {string} opts.specBase - .sillyspec(或平台 specRoot)目录
545
- * @param {string|null} [opts.changeName]
546
- * @param {object|null} [opts.ctx] - MultiRepoContext 实例(可选,缺省/null 走单仓原逻辑)
547
- * @returns {{
548
- * status: 'passed'|'failed'|'skipped',
549
- * command: string|null,
550
- * exitCode: number|null,
551
- * durationMs: number|null,
552
- * outputTail: string|null,
553
- * reason: string|null,
554
- * resultPath: string|null,
555
- * }}
556
- */
557
- export function runVerifyTestCheck({ cwd, specBase, changeName = null, ctx = null }) {
558
- const localYamlPath = join(specBase, 'local.yaml')
559
- const yamlText = existsSync(localYamlPath) ? readFileSync(localYamlPath, 'utf8') : null
560
-
561
- const strategy = extractTestStrategy(yamlText)
562
- const knownFailures = extractKnownFailures(yamlText)
563
-
564
- // —— 模块子集路径(test_strategy: module):算 modulesPresent / hitCount / hits ——
565
- // resolveVerifyChangedFiles 返回 null 表示 git 不可用 → hitCount=-1(与 0 命中区分)。
566
- // 注:module 子集策略只用主仓 diff(跨仓仓不参与 module 子集,design §6 + §5.4),
567
- // 故此处不传 ctx(避免跨仓路径误命中主仓 module 映射)。
568
- let modulesPresent = false
569
- let hitCount = 0
570
- let hits = []
571
- if (strategy === 'module') {
572
- const modules = extractModules(yamlText)
573
- if (modules) {
574
- modulesPresent = true
575
- const changedFiles = resolveVerifyChangedFiles(cwd, changeName)
576
- if (changedFiles === null) {
577
- hitCount = -1 // git 不可用 / 非仓库
578
- } else {
579
- hits = pickHitModules(changedFiles, modules)
580
- hitCount = hits.length
581
- }
582
- }
583
- }
584
-
585
- const action = decideVerifyTestAction({ strategy, modulesPresent, hitCount })
586
- let mainResult
587
- if (action === 'module-subset') {
588
- mainResult = runModuleSubset({ cwd, specBase, changeName, hits, knownFailures })
589
- } else if (action === 'module-zero-hit-skip') {
590
- // module 模式 0 命中:不静默回退注定超时/含预存失败的全量(坑 verify-worktree-... 修复方向 3)。
591
- // 据 verify-result.md 自报告判定;想跑全量请显式设 test_strategy: full。
592
- mainResult = {
593
- status: 'skipped',
594
- command: null,
595
- exitCode: null,
596
- durationMs: null,
597
- outputTail: null,
598
- reason: 'test_strategy: module 但本次变更未命中任何已配置 modules(0 命中)。为避免回退到注定超时/含预存失败的全量 commands.test,CLI 未自动跑全量——据 verify-result.md 自报告判定测试。若需全量覆盖,显式设 test_strategy: full。',
599
- resultPath: null,
600
- mode: 'module-zero-hit',
601
- fallbackReason: null,
602
- }
603
- } else {
604
- // —— 全量路径(full / module 无块 / module git 不可用)——
605
- // fallbackReason 非 null 表示本次全量是"非显式"的(缺省/配置不全/未命中),需明示。
606
- const fallbackReason = computeFullFallbackReason({ strategy, modulesPresent, hitCount })
607
- mainResult = runFullCommand({ yamlText, localYamlPath, cwd, specBase, changeName, fallbackReason, knownFailures })
608
- }
609
-
610
- // —— 跨仓仓 per-repo cwd 跑 full npm test(task-06 / D-004 / design §5.4 + §6 A6)——
611
- // ctx 为空或无跨仓 entry → 直接返主仓结果(单仓零回归,GOAL-2)。
612
- // 跨仓仓不参与 module 子集策略,只跑 full npm test(design §6 + §5.4);
613
- // 跨仓仓无 package.json → 跳过 + warn 不阻断(design §9 兼容策略)。
614
- // 任一跨仓仓 fail → 整体 fail(合并语义)。
615
- return mergeCrossRepoResults(mainResult, ctx)
616
- }
617
-
618
- /**
619
- * per-repo cwd 跑跨仓仓 full npm test,合并进主仓结果。
620
- *
621
- * design §6 A6 + §5.4 + §9 兼容策略:
622
- * - 跨仓仓有 package.json → 在该仓 projectRoot cwd 跑 full npm test(跨仓仓 own local.yaml
623
- * 若有 commands.test 用之,否则 fallback `npm test`)
624
- * - 跨仓仓无 package.json → 跳过 + console.warn(不阻断 verify)
625
- * - 跨仓仓只跑 full npm test,不参与 module 子集策略(module 映射主仓强相关)
626
- * - 任一仓 fail → 整体 fail;主仓 skipped + 跨仓仓 passed → 整体 passed(跨仓仓有测试即有效)
627
- *
628
- * 单仓 ctx(无跨仓 entry)→ 直接返主仓结果,零行为变化(GOAL-2)。
629
- *
630
- * @param {object} mainResult - 主仓 runVerifyTestCheck 结果
631
- * @param {object|null} ctx - MultiRepoContext 实例
632
- * @returns {object} 合并后结果(shape 同 mainResult)
633
- */
634
- function mergeCrossRepoResults(mainResult, ctx) {
635
- if (!ctx || typeof ctx.repos !== 'object' || ctx.repos === null) return mainResult
636
- const crossEntries = []
637
- for (const entry of ctx.repos.values()) {
638
- if (entry && entry.isMain === false) crossEntries.push(entry)
639
- }
640
- if (crossEntries.length === 0) return mainResult
641
-
642
- const crossResults = []
643
- for (const entry of crossEntries) {
644
- const crossResult = runCrossRepoFullTest(entry)
645
- crossResults.push({ repoKey: entry.repoKey, projectRoot: entry.projectRoot, result: crossResult })
646
- }
647
-
648
- // 合并:任一 fail → fail;否则取主仓 status(passed/skipped 与跨仓 passed 合并)
649
- const failedRepos = crossResults.filter(r => r.result.status === 'failed')
650
- if (failedRepos.length > 0) {
651
- return mergeResultStatus({
652
- status: 'failed',
653
- mainResult,
654
- crossResults,
655
- reason: `跨仓仓测试失败:${failedRepos.map(r => r.repoKey).join(', ')}`,
656
- })
657
- }
658
- // 跨仓仓全 passed 或 skipped(无 package.json)→ 主仓 status 不变(合并跨仓信息到 outputTail)
659
- return mergeResultInfo(mainResult, crossResults)
660
- }
661
-
662
- /**
663
- * 在单个跨仓仓根跑 full npm test(跨仓仓不参与 module 子集,只跑 full)。
664
- * 跨仓仓 own local.yaml 若存在且配 commands.test → 用之;否则 fallback `npm test`。
665
- * 跨仓仓无 package.json → 跳过 + warn。
666
- *
667
- * @param {object} entry - RepoEntry(isMain=false)
668
- * @returns {object} 结果 shape 对齐 runFullCommand 返回
669
- */
670
- function runCrossRepoFullTest(entry) {
671
- const projectRoot = entry.projectRoot
672
- // 跨仓仓无 package.json → 跳过 + warn(design §9 兼容策略,不阻断 verify)
673
- if (!existsSync(join(projectRoot, 'package.json'))) {
674
- console.warn(`⚠️ 跨仓 repo "${entry.repoKey}"(${projectRoot})无 package.json,跳过该仓 npm test(design §9 兼容策略,不阻断 verify)。`)
675
- return {
676
- status: 'skipped',
677
- command: null,
678
- exitCode: null,
679
- durationMs: null,
680
- outputTail: null,
681
- reason: `跨仓 repo "${entry.repoKey}" 无 package.json,跳过 npm test`,
682
- resultPath: null,
683
- mode: 'cross-repo-skip',
684
- repoKey: entry.repoKey,
685
- }
686
- }
687
-
688
- // 跨仓仓 own local.yaml(在跨仓仓 .sillyspec/ 下,若存在)配 commands.test → 用之;否则 `npm test`
689
- // 注:跨仓仓按 NG-1 不建 .sillyspec/,但容错读取(用户可手动放 local.yaml 配跨仓仓特定测试命令)
690
- const crossLocalYaml = join(projectRoot, '.sillyspec', 'local.yaml')
691
- let command = 'npm test'
692
- let crossKnownFailures = []
693
- if (existsSync(crossLocalYaml)) {
694
- try {
695
- const crossYaml = readFileSync(crossLocalYaml, 'utf8')
696
- const extracted = extractTestCommand(crossYaml)
697
- if (extracted) command = extracted
698
- crossKnownFailures = extractKnownFailures(crossYaml)
699
- } catch { /* 读取失败 fallback npm test */ }
700
- }
701
-
702
- const startedAt = Date.now()
703
- let exitCode = 0
704
- let output = ''
705
- let reason = null
706
- try {
707
- output = execSync(command, {
708
- cwd: projectRoot,
709
- encoding: 'utf8',
710
- timeout: TEST_TIMEOUT_MS,
711
- maxBuffer: 32 * 1024 * 1024,
712
- stdio: ['ignore', 'pipe', 'pipe'],
713
- })
714
- } catch (e) {
715
- exitCode = typeof e.status === 'number' ? e.status : 1
716
- output = [e.stdout, e.stderr].filter(Boolean).join('\n') || e.message
717
- reason = e.signal === 'SIGTERM' && Date.now() - startedAt >= TEST_TIMEOUT_MS
718
- ? `跨仓 repo "${entry.repoKey}" 测试超时(>${TEST_TIMEOUT_MS / 1000}s)`
719
- : `跨仓 repo "${entry.repoKey}" 测试退出码 ${exitCode}`
720
- }
721
- const durationMs = Date.now() - startedAt
722
- const outputTail = output.length > OUTPUT_TAIL_CHARS ? '…' + output.slice(-OUTPUT_TAIL_CHARS) : output
723
- const judged = judgeWithKnownFailures(exitCode, output, reason, crossKnownFailures)
724
-
725
- return {
726
- status: judged.status,
727
- command,
728
- exitCode,
729
- durationMs,
730
- outputTail,
731
- reason: judged.reason,
732
- resultPath: null,
733
- mode: 'cross-repo-full',
734
- repoKey: entry.repoKey,
735
- exemptedCount: judged.exemptedCount,
736
- }
737
- }
738
-
739
- /**
740
- * 合并失败状态:整体 failed,保留主仓 + 各跨仓仓明细到 outputTail / reason。
741
- */
742
- function mergeResultStatus({ status, mainResult, crossResults, reason }) {
743
- const parts = []
744
- parts.push(`── main (${mainResult.status}) ──\n${mainResult.outputTail || mainResult.reason || ''}`)
745
- for (const cr of crossResults) {
746
- parts.push(`── cross-repo ${cr.repoKey} (${cr.result.status}) ──\n${cr.result.outputTail || cr.result.reason || ''}`)
747
- }
748
- const mergedTail = parts.join('\n')
749
- return {
750
- status,
751
- command: mainResult.command ? `${mainResult.command} + cross-repo[${crossResults.map(r => r.repoKey).join(',')}]` : `cross-repo[${crossResults.map(r => r.repoKey).join(',')}]`,
752
- exitCode: 1,
753
- durationMs: (mainResult.durationMs || 0) + crossResults.reduce((n, r) => n + (r.result.durationMs || 0), 0),
754
- outputTail: mergedTail.length > OUTPUT_TAIL_CHARS ? '…' + mergedTail.slice(-OUTPUT_TAIL_CHARS) : mergedTail,
755
- reason,
756
- resultPath: mainResult.resultPath,
757
- mode: 'cross-repo-merged',
758
- fallbackReason: mainResult.fallbackReason || null,
759
- }
760
- }
761
-
762
- /**
763
- * 合并信息(跨仓仓全 passed/skipped):主仓 status 保留,跨仓仓 PASSED 信息附入 outputTail。
764
- */
765
- function mergeResultInfo(mainResult, crossResults) {
766
- const crossPassed = crossResults.filter(r => r.result.status === 'passed')
767
- const crossSkipped = crossResults.filter(r => r.result.status === 'skipped')
768
- if (crossPassed.length === 0 && crossSkipped.length === 0) return mainResult
769
- const crossSummary = []
770
- for (const cr of crossPassed) crossSummary.push(`cross-repo ${cr.repoKey}: PASS`)
771
- for (const cr of crossSkipped) crossSummary.push(`cross-repo ${cr.repoKey}: SKIP(${cr.result.reason || 'no package.json'})`)
772
- const crossLine = `\n── 跨仓仓 npm test ──\n${crossSummary.join('\n')}`
773
- const mergedTail = (mainResult.outputTail || '') + crossLine
774
- return {
775
- ...mainResult,
776
- outputTail: mergedTail.length > OUTPUT_TAIL_CHARS ? '…' + mergedTail.slice(-OUTPUT_TAIL_CHARS) : mergedTail,
777
- mode: mainResult.mode ? `${mainResult.mode}+cross-repo` : 'cross-repo-merged',
778
- }
779
- }
780
-
781
- /**
782
- * 全量跑 commands.test(现有逻辑,brownfield 行为不变)。
783
- */
784
- function runFullCommand({ yamlText, localYamlPath, cwd, specBase, changeName, fallbackReason = null, knownFailures = [] }) {
785
- const command = extractTestCommand(yamlText)
786
-
787
- if (!command) {
788
- return {
789
- status: 'skipped',
790
- command: null,
791
- exitCode: null,
792
- durationMs: null,
793
- outputTail: null,
794
- reason: yamlText
795
- ? 'local.yaml 未配置 commands.test(或标记 unavailable)'
796
- : `local.yaml 不存在(${localYamlPath})`,
797
- resultPath: null,
798
- mode: 'full',
799
- fallbackReason,
800
- }
801
- }
802
-
803
- const startedAt = Date.now()
804
- let exitCode = 0
805
- let output = ''
806
- let reason = null
807
- try {
808
- output = execSync(command, {
809
- cwd,
810
- encoding: 'utf8',
811
- timeout: TEST_TIMEOUT_MS,
812
- maxBuffer: 32 * 1024 * 1024,
813
- stdio: ['ignore', 'pipe', 'pipe'],
814
- })
815
- } catch (e) {
816
- exitCode = typeof e.status === 'number' ? e.status : 1
817
- output = [e.stdout, e.stderr].filter(Boolean).join('\n') || e.message
818
- reason = e.signal === 'SIGTERM' && Date.now() - startedAt >= TEST_TIMEOUT_MS
819
- ? `测试命令超时(>${TEST_TIMEOUT_MS / 1000}s)`
820
- : `测试命令退出码 ${exitCode}`
821
- }
822
- const durationMs = Date.now() - startedAt
823
- const outputTail = output.length > OUTPUT_TAIL_CHARS ? '…' + output.slice(-OUTPUT_TAIL_CHARS) : output
824
-
825
- const judged = judgeWithKnownFailures(exitCode, output, reason, knownFailures)
826
- const result = {
827
- status: judged.status,
828
- command,
829
- exitCode,
830
- durationMs,
831
- outputTail,
832
- reason: judged.reason,
833
- resultPath: null,
834
- mode: 'full',
835
- fallbackReason,
836
- exemptedCount: judged.exemptedCount,
837
- }
838
-
839
- writeRunResult({ specBase, changeName, result, extra: fallbackReason ? { fallback_reason: fallbackReason } : {} })
840
- return result
841
- }
842
-
843
- /**
844
- * 串行跑命中的模块子集,聚合结果。
845
- * 返回 shape 与 runFullCommand 一致(status/command/exitCode/durationMs/outputTail/reason/resultPath)。
846
- */
847
- function runModuleSubset({ cwd, specBase, changeName, hits, knownFailures = [] }) {
848
- const subsetStartedAt = Date.now()
849
- const perModule = hits.map(h => runOneModule(h.name, h.test, cwd, knownFailures))
850
- const status = aggregateStatus(perModule)
851
-
852
- const command = `module[${hits.map(h => h.name).join(',')}]`
853
- const exitCode = status === 'passed' ? 0 : 1
854
- const durationMs = Date.now() - subsetStartedAt
855
-
856
- // 合并各模块输出尾部(标注模块名)
857
- const outputTail = perModule
858
- .map(r => `── module ${r.name} (${r.status}) ──\n${r.outputTail || ''}`)
859
- .join('\n')
860
- const reason = status === 'passed'
861
- ? null
862
- : `模块子集测试失败:${perModule.filter(r => r.status === 'failed').map(r => r.name).join(', ')}`
863
-
864
- const result = {
865
- status,
866
- command,
867
- exitCode,
868
- durationMs,
869
- outputTail: outputTail.length > OUTPUT_TAIL_CHARS ? '…' + outputTail.slice(-OUTPUT_TAIL_CHARS) : outputTail,
870
- reason,
871
- resultPath: null,
872
- mode: 'module-subset',
873
- fallbackReason: null,
874
- exemptedCount: perModule.reduce((n, r) => n + (r.exemptedCount || 0), 0),
875
- }
876
-
877
- writeRunResult({
878
- specBase,
879
- changeName,
880
- result,
881
- extra: {
882
- modules: perModule.map(r => ({
883
- name: r.name,
884
- command: r.command,
885
- exit_code: r.exitCode,
886
- status: r.status,
887
- duration_ms: r.durationMs,
888
- output_tail: r.outputTail,
889
- reason: r.reason,
890
- })),
891
- },
892
- })
893
- return result
894
- }
895
-
896
- /**
897
- * 结果落盘到 .runtime/verify-runs/<ts>/test-result.json(供追溯与 SillyHub 消费)。
898
- * 多模块时 extra.modules 描述各模块明细。
899
- */
900
- function writeRunResult({ specBase, changeName, result, extra = {} }) {
901
- try {
902
- const ts = new Date().toISOString().slice(0, 19).replace(/[-T:]/g, '')
903
- const runDir = join(specBase, '.runtime', 'verify-runs', ts)
904
- mkdirSync(runDir, { recursive: true })
905
- const resultPath = join(runDir, 'test-result.json')
906
- writeFileSync(resultPath, JSON.stringify({
907
- change: changeName,
908
- command: result.command,
909
- exit_code: result.exitCode,
910
- status: result.status,
911
- duration_ms: result.durationMs,
912
- output_tail: result.outputTail,
913
- reason: result.reason,
914
- ran_at: new Date().toISOString(),
915
- ...extra,
916
- }, null, 2) + '\n')
917
- result.resultPath = resultPath
918
- } catch (e) {
919
- console.warn(`⚠️ verify 实测结果落盘失败: ${e.message}`)
920
- }
921
- }
922
-
923
- /** 打印实测结果(人类/agent 可读) */
924
- export function printVerifyTestCheck(result) {
925
- if (result.status === 'skipped') {
926
- console.warn(`\n⚠️ Verify 实测跳过:${result.reason}`)
927
- console.warn(' 建议在 local.yaml 的 commands.test 配置真实测试命令,让 CLI 可客观对账。')
928
- return
929
- }
930
- if (result.status === 'passed') {
931
- if (result.exemptedCount > 0) {
932
- console.log(`\n✅ Verify 实测通过(含 ${result.exemptedCount} 个 known_failures 豁免):\`${result.command}\` — ${result.reason}`)
933
- console.warn(' ⚠️ 本次 PASS 依赖 known_failures 豁免清单——请人工复核清单是否过宽(避免误豁免本变更引入的真实失败)。')
934
- } else {
935
- console.log(`\n✅ Verify 实测通过:\`${result.command}\` 退出码 0(${(result.durationMs / 1000).toFixed(1)}s)`)
936
- }
937
- } else {
938
- console.error(`\n❌ Verify 实测失败:\`${result.command}\` — ${result.reason}`)
939
- if (result.outputTail) {
940
- const tail = result.outputTail.split('\n').slice(-20).join('\n')
941
- console.error(' 输出(末尾):')
942
- for (const line of tail.split('\n')) console.error(` | ${line}`)
943
- }
944
- }
945
- // —— 全量 fallback 明示(skipped 已提前 return,此处仅 passed/failed)——
946
- // 让 agent 知道本次跑的是全量 commands.test、非变更范围子集;失败可能含未变更模块
947
- // 的预存错误,需先核对用例归属再归因到本次变更(见 3.24 verify 坑1)。
948
- if (result.mode === 'full' && result.fallbackReason) {
949
- if (result.status === 'failed') {
950
- console.warn(` ⚠️ 本次跑的是 commands.test 全量(${result.fallbackReason})。`)
951
- console.warn(' 失败可能含与本变更无关的预存错误——先核对失败用例是否属于你的变更范围;')
952
- console.warn(' 或在 local.yaml 配置 test_strategy: module + modules: 块以收窄到变更模块。')
953
- } else {
954
- console.warn(` ⚠️ 本次跑的是 commands.test 全量(${result.fallbackReason})。`)
955
- console.warn(' 如耗时过长,可在 local.yaml 配置 test_strategy: module + modules: 块按模块收窄。')
956
- }
957
- }
958
- if (result.resultPath) {
959
- console.log(`📄 实测结果已写入: ${result.resultPath}`)
960
- }
961
- }
962
-
963
- /**
964
- * API parity 对账(advisory):前端调用 vs execute 提取的后端 endpoint artifact。
965
- * 三态:skipped(无 provider artifact → 非全栈项目不打扰)/ warning(missingBackend>0)/ passed。
966
- * 启发式正则、多假阳源 → advisory 不阻断 verify 完成(与 SillySpec 确定性校验定位一致)。
967
- *
968
- * @param {object} opts
969
- * @param {string} opts.cwd - 扫描前端调用的根(主工作区,verify 时代码在此)
970
- * @param {string} opts.specBase
971
- * @param {string|null} [opts.changeName]
972
- * @param {string|null} [opts.runtimeRoot]
973
- * @returns {{ status: 'skipped'|'warning'|'passed', missingBackend: Array, unusedBackend: Array, summary: string, reason: string|null }}
974
- */
975
- export function runVerifyParityCheck({ cwd, specBase, changeName = null, runtimeRoot = null }) {
976
- const r = verifyApiParity(specBase, cwd, runtimeRoot, changeName)
977
- // 无 provider artifact(execute 未提取 / 非后端项目)→ 不打扰
978
- if (r.backendCount === 0) {
979
- return { status: 'skipped', missingBackend: [], unusedBackend: [], summary: r.summary, reason: '无后端契约 artifact(非全栈项目或 execute 未提取端点)' }
980
- }
981
- if (r.missingBackend.length > 0) {
982
- return { status: 'warning', missingBackend: r.missingBackend, unusedBackend: r.unusedBackend, summary: r.summary, reason: null }
983
- }
984
- return { status: 'passed', missingBackend: [], unusedBackend: r.unusedBackend, summary: r.summary, reason: null }
985
- }
986
-
987
- /** 打印 parity 对账结果(advisory,不阻断) */
988
- export function printVerifyParityCheck(result) {
989
- if (result.status === 'skipped') return // 静默,不打扰非全栈项目
990
- if (result.status === 'passed') {
991
- console.log(`\n✅ API parity 对账通过:${result.summary}`)
992
- return
993
- }
994
- // warning
995
- console.warn(`\n⚠️ API parity 对账发现 ${result.missingBackend.length} 个前端调用无对应后端端点(advisory,不阻断归档):`)
996
- for (const m of result.missingBackend.slice(0, 20)) {
997
- console.warn(` - ${m.method} ${m.path} ← ${m.consumerFile}:${m.consumerLine}`)
998
- }
999
- if (result.missingBackend.length > 20) console.warn(` …还有 ${result.missingBackend.length - 20} 个`)
1000
- console.warn(' 提示:检查是否后端漏实现,或前端调用了尚未实现的端点。确认无误可在 design.md 标注豁免。')
1001
- }
1002
-
1003
- /**
1004
- * 删除探针(advisory):用 git 事实客观对账本次变更删除的文件 vs design.md 声明的操作。
1005
- *
1006
- * 切斯特顿栅栏护栏——verify 对「agent 静默删除代码」本是盲区:agent 删一段它看不懂的
1007
- * 旧代码,只要路径合规、不碰风险关键词,5 探针 + 风险分级 + 测试对账全都不会响。本探针
1008
- * 不信任 agent 自报告,用 `git diff --name-status HEAD` 客观提取删除文件,对账 design
1009
- * 清单声明的操作(声明「新增/修改」却整文件删除 = 高风险)。warning 不阻断 verify 完成
1010
- * (advisory 起步)——「检测到删除」是确定性事实(做),「该不该删」是意图(只报不拦)。
1011
- *
1012
- * 信号源:apply(git apply --3way)不 commit,verify 时主仓 HEAD 仍是变更前 commit,
1013
- * 删除的文件在工作树消失但仍在 HEAD → `git diff --name-status HEAD` 显示 D。
1014
- *
1015
- * @param {object} opts
1016
- * @param {string} opts.cwd - 项目根(主仓,代码在此)
1017
- * @param {string} opts.specBase - .sillyspec(或平台 specRoot)
1018
- * @param {string|null} [opts.changeName]
1019
- * @returns {{
1020
- * status: 'skipped'|'warning'|'passed',
1021
- * highRisk: Array<{path:string, declaredOp:string, reason:string}>,
1022
- * mediumRisk: Array<{path:string, reason:string}>,
1023
- * compliant: Array<{path:string, declaredOp:string}>,
1024
- * summary: string,
1025
- * reason: string|null,
1026
- * }}
1027
- */
1028
- export function runVerifyDeletionCheck({ cwd, specBase, changeName = null }) {
1029
- const statusRaw = runGitDiffNameStatus(cwd, 'HEAD')
1030
- if (statusRaw === null) {
1031
- return { status: 'skipped', highRisk: [], mediumRisk: [], compliant: [],
1032
- summary: '', reason: 'git 不可用或非仓库,删除对账跳过' }
1033
- }
1034
-
1035
- // 解析 D(删除);R/C 的旧路径等价删除(防御 committed rename;标准 apply 流程
1036
- // rename 表现为纯 D,故本探针不加 -M,D 统一处理)。
1037
- const deletions = []
1038
- for (const line of statusRaw.split('\n').filter(Boolean)) {
1039
- const parts = line.split('\t')
1040
- const st = parts[0]
1041
- if (!st) continue
1042
- if (st.startsWith('D')) {
1043
- deletions.push({ path: parts[1], kind: 'D' })
1044
- } else if ((st.startsWith('R') || st.startsWith('C')) && parts.length >= 3) {
1045
- // rename/copy 旧路径(parts[1])等价删除,新路径 parts[2]
1046
- deletions.push({ path: parts[1], kind: 'R-old', renamedTo: parts[2] })
1047
- }
1048
- }
1049
-
1050
- // 排除交付物外文件(.sillyspec/ 变更包/运行时/quicklog + meta.json),避免污染删除信号。
1051
- // 复用 worktree-apply.js 的 filterDeliverableFiles 去双写(坑3:保留 .sillyspec/docs/)。
1052
- const deliverable = filterDeliverableFiles(deletions.map(d => d.path))
1053
- .map(p => deletions.find(d => d.path === p))
1054
-
1055
- if (deliverable.length === 0) {
1056
- return { status: 'skipped', highRisk: [], mediumRisk: [], compliant: [],
1057
- summary: '', reason: '本次变更无文件删除(或改动已被 commit,主仓 HEAD 已推进,删除对账无锚点)' }
1058
- }
1059
-
1060
- // 读 design 声明(operation)。无清单章节 → [],所有删除归「未声明」。
1061
- const designPath = changeName
1062
- ? join(specBase, 'changes', changeName, 'design.md') : null
1063
- const designEntries = designPath && existsSync(designPath)
1064
- ? parseFileChangeListDetailed(designPath) : []
1065
-
1066
- const highRisk = []
1067
- const mediumRisk = []
1068
- const compliant = []
1069
- for (const d of deliverable) {
1070
- const hit = designEntries.find(e => pathMatches(d.path, e.path))
1071
- if (!hit) {
1072
- mediumRisk.push({ path: d.path, reason: d.kind === 'R-old'
1073
- ? `重命名源文件未在 design 清单(→ ${d.renamedTo})`
1074
- : 'design 清单未列出该删除文件' })
1075
- continue
1076
- }
1077
- if (hit.operation === '新增' || hit.operation === '修改') {
1078
- highRisk.push({ path: d.path, declaredOp: hit.operation,
1079
- reason: `design 声明「${hit.operation}」但 git 显示整文件删除` })
1080
- } else if (hit.operation === '删除') {
1081
- compliant.push({ path: d.path, declaredOp: '删除' })
1082
- } else {
1083
- // operation=null(未声明操作)或 重命名:删除发生但声明不明确
1084
- mediumRisk.push({ path: d.path,
1085
- reason: `design 列出但操作为「${hit.operation || '未声明'}」,与删除不一致` })
1086
- }
1087
- }
1088
-
1089
- if (highRisk.length > 0 || mediumRisk.length > 0) {
1090
- return { status: 'warning', highRisk, mediumRisk, compliant,
1091
- summary: `${highRisk.length} 个高风险删除 + ${mediumRisk.length} 个未声明删除`, reason: null }
1092
- }
1093
- return { status: 'passed', highRisk: [], mediumRisk: [], compliant,
1094
- summary: `所有 ${compliant.length} 个删除均在 design 声明为「删除」`, reason: null }
1095
- }
1096
-
1097
- /** 打印删除对账结果(advisory,不阻断 verify 完成) */
1098
- export function printVerifyDeletionCheck(result) {
1099
- if (result.status === 'skipped') return // 静默:无删除 / git 不可用 / 改动已 commit
1100
- if (result.status === 'passed') {
1101
- console.log(`\n✅ 删除对账通过:${result.summary}`)
1102
- return
1103
- }
1104
- // warning
1105
- if (result.highRisk.length > 0) {
1106
- console.warn(`\n⚠️ 删除对账发现 ${result.highRisk.length} 个高风险删除(design 声明新增/修改却被整文件删除,advisory 不阻断):`)
1107
- for (const m of result.highRisk.slice(0, 20)) console.warn(` - ${m.path} (${m.reason})`)
1108
- if (result.highRisk.length > 20) console.warn(` …还有 ${result.highRisk.length - 20} 个`)
1109
- }
1110
- if (result.mediumRisk.length > 0) {
1111
- console.warn(`⚠️ ${result.mediumRisk.length} 个未声明删除(design 清单未列出 / 操作不一致):`)
1112
- for (const m of result.mediumRisk.slice(0, 20)) console.warn(` - ${m.path} (${m.reason})`)
1113
- if (result.mediumRisk.length > 20) console.warn(` …还有 ${result.mediumRisk.length - 20} 个`)
1114
- }
1115
- console.warn(' 提示:确认删除是否预期。预期删除请在 design.md 清单用「删除」操作显式声明;误删请恢复。')
1116
- }
1117
-
1118
- /**
1119
- * required-evidence 对账(advisory,不阻断 verify 完成)。
1120
- *
1121
- * execute 阶段 Task Review Gate 把 cannot_verify 任务的 requiredEvidence 写入
1122
- * changes/<change>/verify-required-evidence.json(schema: {generatedAt, schemaVersion, items:[{task, verdict, evidence:string[]}]})。
1123
- * 历史"死链"(sss1.md 矛盾2):只写不读——verify agent 不在 verify-result.md 体现也不会被发现,
1124
- * 且 verify.js prompt 让 agent 读 `requiredEvidence` 键(字段名错配,实际是 items[].evidence),照做必落空。
1125
- * 本探针闭合该链:读 evidence 文件,对每个 cannot_verify 任务检查 verify-result.md 是否提及该任务 id;
1126
- * 未提及 → warning(advisory)。CLI 只做"任务被提及"的机械存在性检查,evidence 是否真正满足
1127
- * (satisfied/missing/partial)由 agent 在 verify-result.md 诚实自报告——不假装语义判定(与删除探针同 altitude)。
1128
- *
1129
- * @param {{cwd:string, specBase:string, changeName?:string}} args
1130
- * @returns {{status:'skipped'|'passed'|'warning', items:Array, unacknowledged:Array, summary:string, reason:string|null}}
1131
- */
1132
- export function runVerifyRequiredEvidenceCheck({ cwd, specBase, changeName = null }) {
1133
- if (!changeName) {
1134
- return { status: 'skipped', items: [], unacknowledged: [], summary: '', reason: '无 changeName(quick 等无关联变更场景),evidence 对账跳过' }
1135
- }
1136
- const evidencePath = join(specBase, 'changes', changeName, 'verify-required-evidence.json')
1137
- if (!existsSync(evidencePath)) {
1138
- return { status: 'skipped', items: [], unacknowledged: [], summary: '', reason: '无 verify-required-evidence.json(execute 无 cannot_verify 任务),evidence 对账跳过' }
1139
- }
1140
-
1141
- let data
1142
- try {
1143
- data = JSON.parse(readFileSync(evidencePath, 'utf8'))
1144
- } catch (e) {
1145
- return { status: 'skipped', items: [], unacknowledged: [], summary: '', reason: `verify-required-evidence.json 解析失败(${e.message}),evidence 对账跳过` }
1146
- }
1147
- const items = Array.isArray(data.items) ? data.items : []
1148
-
1149
- // 读 verify-result.md(不存在则所有 evidence 任务都"未体现")
1150
- const verifyResultPath = join(specBase, 'changes', changeName, 'verify-result.md')
1151
- const report = existsSync(verifyResultPath) ? readFileSync(verifyResultPath, 'utf8') : ''
1152
-
1153
- const unacknowledged = []
1154
- for (const item of items) {
1155
- const task = item && item.task
1156
- if (!task) continue
1157
- // 机械存在性检查:verify-result.md 是否提及该 cannot_verify 任务 id。
1158
- // evidence 数组的具体满足度(satisfied/missing/partial)由 agent 自报告,CLI 不判定。
1159
- if (!report.includes(task)) {
1160
- const evidenceCount = Array.isArray(item.evidence) ? item.evidence.length : 0
1161
- unacknowledged.push({ task, verdict: item.verdict || 'cannot_verify', evidenceCount,
1162
- reason: `cannot_verify 任务 ${task} 未在 verify-result.md 中体现(需逐条 evidence 给结论 satisfied/missing/partial)` })
1163
- }
1164
- }
1165
-
1166
- if (unacknowledged.length > 0) {
1167
- return { status: 'warning', items, unacknowledged,
1168
- summary: `${items.length} 个 cannot_verify evidence 任务中 ${unacknowledged.length} 个未在 verify-result.md 体现`, reason: null }
1169
- }
1170
- return { status: 'passed', items, unacknowledged: [],
1171
- summary: `${items.length} 个 cannot_verify evidence 任务均在 verify-result.md 体现(满足度由 agent 自报告)`, reason: null }
1172
- }
1173
-
1174
- /** 打印 required-evidence 对账结果(advisory,不阻断 verify 完成) */
1175
- export function printVerifyRequiredEvidenceCheck(result) {
1176
- if (result.status === 'skipped') return // 静默:无 evidence 文件 / 无 changeName / 解析失败
1177
- if (result.status === 'passed') {
1178
- console.log(`\n✅ required-evidence 对账通过:${result.summary}`)
1179
- return
1180
- }
1181
- // warning
1182
- console.warn(`\n⚠️ required-evidence 对账发现 ${result.unacknowledged.length} 个 cannot_verify 任务未在 verify-result.md 体现(advisory 不阻断):`)
1183
- for (const u of result.unacknowledged.slice(0, 20)) console.warn(` - ${u.task} (${u.reason})`)
1184
- if (result.unacknowledged.length > 20) console.warn(` …还有 ${result.unacknowledged.length - 20} 个`)
1185
- console.warn(' 提示:execute 标记的 cannot_verify 任务需在 verify-result.md 逐条给 evidence 结论(satisfied/missing/partial)。CLI 仅查任务被提及,是否真满足由你诚实判定。')
1186
- }
1
+ /**
2
+ * Verify Postcheck — CLI 客观测试执行与自报告对账
3
+ *
4
+ * verify 阶段历史上完全依赖 agent 自报告(跑没跑测试、结果如何全写在
5
+ * verify-result.md 里),可被文案绕过。此模块让 CLI 在 verify 完成时
6
+ * 亲自执行 local.yaml 配置的测试命令,与 verify-result.md 的结论对账:
7
+ * 自报告 PASS 但实测失败 → 阻断 verify 完成。
8
+ *
9
+ * 未配置 commands.test(或标记 unavailable)时降级为 warning 不阻断,
10
+ * 兼容无测试项目。
11
+ *
12
+ * test_strategy 支持(D-002@v1):
13
+ * - full(默认):整跑 commands.test(brownfield 行为不变)
14
+ * - module:按 local.yaml modules 映射,仅跑 git diff 命中的模块子集
15
+ * 测试,避免 monorepo 全量测试超 gate timeout。
16
+ */
17
+
18
+ import { execSync } from 'child_process'
19
+ import { gitQuiet } from './git-helper.js'
20
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
21
+ import { join } from 'path'
22
+ import { verifyApiParity } from './contract-matrix.js'
23
+ import { parseFileChangeListDetailed, pathMatches } from './change-list.js'
24
+ import { filterDeliverableFiles } from './worktree-apply.js'
25
+
26
+ // 测试命令最长执行时间;超时视为失败(防止 CLI 被挂起的测试卡死)
27
+ const TEST_TIMEOUT_MS = Number(process.env.SILLYSPEC_TEST_TIMEOUT_MS) || 10 * 60 * 1000
28
+ const OUTPUT_TAIL_CHARS = 4000
29
+
30
+ /**
31
+ * 行尾归一(坑 verify-modules-crlf-blanket-fallback,2026-08-20 实证):Windows 仓的
32
+ * local.yaml 常为 CRLF(编辑器/CLI 写入),手写行扫描器的逐行正则里 `.` 不匹配 `\r`、
33
+ * `$`(无 m 标志)又要求真串尾——`\r` 残留行尾导致条目正则整条失配。实证受害:
34
+ * extractModules 返回 null(modules 映射恒失效 → 永远回退全量 → 600s 默认超时必炸)、
35
+ * extractKnownFailures 块式只捕获第一条。统一在解析入口归一,JS 的 `\r?\n` 拆分与
36
+ * yaml 库均兼容 LF 文本(零回归)。
37
+ */
38
+ function normalizeLineEndings(text) {
39
+ return String(text || '').replace(/\r\n?/g, '\n')
40
+ }
41
+
42
+ /**
43
+ * 从 local.yaml 文本提取 commands.test。
44
+ * 轻量正则(与 worktree-deps/scan-postcheck 同风格,不引 yaml 依赖):
45
+ * 支持带引号与不带引号两种写法;'unavailable' 视为未配置。
46
+ */
47
+ export function extractTestCommand(yamlText) {
48
+ if (!yamlText) return null
49
+ const doubleQuoted = yamlText.match(/^\s*test:\s*"([^"]+)"\s*(?:#.*)?$/m)
50
+ const singleQuoted = yamlText.match(/^\s*test:\s*'([^']+)'\s*(?:#.*)?$/m)
51
+ const quoted = doubleQuoted || singleQuoted
52
+ if (quoted && quoted[1]) {
53
+ return quoted[1].toLowerCase() === 'unavailable' ? null : quoted[1].trim()
54
+ }
55
+ const bare = yamlText.match(/^\s*test:\s*([^\n#"']+?)\s*(?:#.*)?$/m)
56
+ if (bare && bare[1]) {
57
+ const cmd = bare[1].trim()
58
+ return cmd.toLowerCase() === 'unavailable' ? null : cmd
59
+ }
60
+ return null
61
+ }
62
+
63
+ /**
64
+ * 从 local.yaml 文本提取顶层 test_strategy。
65
+ * 轻量正则(与 extractTestCommand 同风格,不引 yaml 依赖)。
66
+ *
67
+ * @param {string} yamlText
68
+ * @returns {'full'|'module'|null} - 解析到的策略;缺省/无法解析返回 null(调用方按 full 处理)
69
+ */
70
+ export function extractTestStrategy(yamlText) {
71
+ if (!yamlText) return null
72
+ const m = yamlText.match(/^\s*test_strategy:\s*([A-Za-z_]+)\s*(?:#.*)?$/m)
73
+ if (!m || !m[1]) return null
74
+ const v = m[1].trim().toLowerCase()
75
+ if (v === 'module') return 'module'
76
+ if (v === 'full') return 'full'
77
+ return null
78
+ }
79
+
80
+ /**
81
+ * 计算全量 fallback 的原因文本(供 printVerifyTestCheck / facet 给 agent/daemon 明示)。
82
+ *
83
+ * 返回 null 表示不需要 hint:显式 test_strategy:full(用户有意跑全量),
84
+ * 或 test_strategy:module 已成功命中模块子集(该情况不会走到全量路径)。
85
+ * 其余走全量路径的情况都返回原因字符串,让结果可正确解读——
86
+ * 否则 agent/daemon 会把"全量 commands.test"当成"按变更范围测的",误把
87
+ * 未变更模块的预存错误归因到本次变更(见 3.24 verify 坑1)。
88
+ *
89
+ * 语义对齐 runVerifyTestCheck 的分支:
90
+ * - strategy==='full' → null
91
+ * - strategy==='module' 但无有效 modules 块 → hint
92
+ * - strategy==='module' 有块但 git 不可用(hitCount=-1)→ hint
93
+ * - strategy==='module' 有块但 0 命中(hitCount=0)→ hint
94
+ * - strategy==='module' 有块且命中(hitCount>0)→ null(走子集)
95
+ * - strategy===null(缺省)→ hint(默认全量)
96
+ *
97
+ * @param {object} ctx
98
+ * @param {'full'|'module'|null} ctx.strategy
99
+ * @param {boolean} ctx.modulesPresent - extractModules 是否返回有效映射
100
+ * @param {number} ctx.hitCount - git diff 命中的模块数;-1 表示 git 不可用/非仓库
101
+ * @returns {string|null}
102
+ */
103
+ export function computeFullFallbackReason({ strategy, modulesPresent, hitCount }) {
104
+ if (strategy === 'full') return null
105
+ if (strategy === 'module') {
106
+ if (!modulesPresent) {
107
+ return 'test_strategy: module 但 local.yaml 未配置有效的 modules: 块(需 inline flow: name: { path, test }),回退全量'
108
+ }
109
+ if (hitCount < 0) {
110
+ return 'test_strategy: module 但 git 不可用/非 git 仓库,无法判定命中模块,回退全量'
111
+ }
112
+ if (hitCount === 0) {
113
+ return 'test_strategy: module 但本次 git diff 未命中任何已配置 modules,回退全量'
114
+ }
115
+ return null
116
+ }
117
+ // strategy === null(缺省 → 默认全量)
118
+ return 'local.yaml 未配置 test_strategy(默认全量 commands.test,未按变更范围收窄)'
119
+ }
120
+
121
+ /**
122
+ * 从 local.yaml 文本解析 modules 映射块。
123
+ * 设计约定(见 change 2026-07-10-tooling-followups design.md #2 方案 A):
124
+ *
125
+ * modules:
126
+ * backend: { path: "backend/", test: "cd backend && uv run pytest" }
127
+ * frontend: { path: "frontend/", test: "cd frontend && pnpm test" }
128
+ *
129
+ * 每个模块一行 inline flow mapping,含 path 与 test 两个键。
130
+ * 轻量行扫描(与 modules.js parseModuleMapSimple 同风格,不引 yaml 依赖)。
131
+ *
132
+ * @param {string} yamlText
133
+ * @returns {Record<string, {path:string, test:string}>|null}
134
+ * - 找不到 modules 块 → null(调用方 fallback commands.test)
135
+ * - 找到块但无有效条目 → null
136
+ */
137
+ export function extractModules(yamlText) {
138
+ if (!yamlText) return null
139
+ const lines = normalizeLineEndings(yamlText).split('\n')
140
+
141
+ // 定位 modules: 起始行(必须是顶层 key,行首无缩进或仅注释后顶层)
142
+ let startIdx = -1
143
+ for (let i = 0; i < lines.length; i++) {
144
+ const m = lines[i].match(/^modules:\s*(?:#.*)?$/)
145
+ if (m) { startIdx = i; break }
146
+ }
147
+ if (startIdx === -1) return null
148
+
149
+ const modules = {}
150
+ for (let i = startIdx + 1; i < lines.length; i++) {
151
+ const line = lines[i]
152
+ // 子条目:以 2 空格缩进 + key + ':' 开头
153
+ const entry = line.match(/^ ([A-Za-z0-9_.\-]+):\s*(.*)$/)
154
+ if (!entry) {
155
+ // 遇到新的顶层 key(行首非空格且非注释)→ modules 块结束
156
+ if (line.length > 0 && !line.startsWith(' ') && !line.startsWith('#') && line.trim() !== '') break
157
+ continue
158
+ }
159
+ const name = entry[1]
160
+ const rest = entry[2].trim()
161
+ if (rest === '' || rest.startsWith('#')) continue // 子块展开式(本实现只支持 inline flow)
162
+ // 解析 inline flow mapping: { path: "...", test: "..." }
163
+ const pathVal = parseFlowValue(rest, 'path')
164
+ const testVal = parseFlowValue(rest, 'test')
165
+ if (pathVal && testVal) {
166
+ modules[name] = { path: pathVal, test: testVal }
167
+ }
168
+ }
169
+
170
+ return Object.keys(modules).length > 0 ? modules : null
171
+ }
172
+
173
+ /**
174
+ * 从 inline flow mapping 文本(如 `{ path: "backend/", test: "cd ..." }`)
175
+ * 提取指定键的值。支持双引号/单引号/bare 值。
176
+ */
177
+ function parseFlowValue(flowText, key) {
178
+ // 键可能带引号也可能不带:path: "x" 或 "path": "x"
179
+ const re = new RegExp(String.raw`(?:^|[{,]\s*)"?${key}"?\s*:\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|(?:[^,}]+?))\s*(?=[,}]|$)`)
180
+ const m = flowText.match(re)
181
+ if (!m) return null
182
+ let v = m[1].trim()
183
+ if (v.startsWith('"') && v.endsWith('"')) {
184
+ // 双引号值剥壳后解开转义(坑 verify-modules-crlf-blanket-fallback 次生发现):modules 的
185
+ // test 命令常含嵌套引号(node -e "…" / pytest "…"),yaml 源里写作 \";此前只剥外层引号
186
+ // 不解 \\ 与 \",解析结果残留字面反斜杠 → 命令直接坏。其余冷门转义(\n 等)按 YAML 规范
187
+ // 应真转义,但保守留字面(可见优于静默变换,测试命令不含它们)
188
+ v = v.slice(1, -1).replace(/\\(["\\])/g, '$1')
189
+ } else if (v.startsWith("'") && v.endsWith("'")) {
190
+ // 单引号值的 YAML 转义是 '' → '
191
+ v = v.slice(1, -1).replace(/''/g, "'")
192
+ }
193
+ return v.length > 0 ? v : null
194
+ }
195
+
196
+ /**
197
+ * 根据变更文件列表 + modules 映射,算出被命中的模块(去重保序)。
198
+ * 文件路径以 module.path 为前缀(含子目录)即视为命中。
199
+ *
200
+ * @param {string[]} changedFiles - git diff 产出的相对路径列表
201
+ * @param {Record<string, {path:string, test:string}>} modules - extractModules 解析结果
202
+ * @returns {Array<{name:string, path:string, test:string}>} - 命中的模块(按 modules 声明顺序去重)
203
+ */
204
+ export function pickHitModules(changedFiles, modules) {
205
+ if (!Array.isArray(changedFiles) || changedFiles.length === 0) return []
206
+ if (!modules || typeof modules !== 'object') return []
207
+
208
+ const files = changedFiles.map(f => String(f).replace(/\\/g, '/'))
209
+ const hits = []
210
+ for (const [name, mod] of Object.entries(modules)) {
211
+ if (!mod || !mod.path) continue
212
+ const modPath = String(mod.path).replace(/\\/g, '/')
213
+ const prefix = modPath.endsWith('/') ? modPath : modPath + '/'
214
+ // path 本身被改 或 path/ 下任意文件被改
215
+ const hit = files.some(f => f === modPath || f.startsWith(prefix))
216
+ if (hit) hits.push({ name, path: modPath, test: mod.test })
217
+ }
218
+ return hits
219
+ }
220
+
221
+ /**
222
+ * 聚合多个模块测试结果为单一 status。
223
+ * - 全 passed → 'passed'
224
+ * - 任一 failed → 'failed'
225
+ * - 空 → null(调用方按 fallback 处理)
226
+ *
227
+ * @param {Array<{status:'passed'|'failed'}>} results
228
+ * @returns {'passed'|'failed'|null}
229
+ */
230
+ export function aggregateStatus(results) {
231
+ if (!Array.isArray(results) || results.length === 0) return null
232
+ if (results.every(r => r && r.status === 'passed')) return 'passed'
233
+ return 'failed'
234
+ }
235
+
236
+ /**
237
+ * 从 local.yaml 提取 known_failures 声明(预存失败豁免清单,坑 verify-worktree-... 修复方向 2)。
238
+ * 支持块式与流式两种写法:
239
+ * known_failures:
240
+ * - "tests/test_ppm.py::test_legacy"
241
+ * - app/modules/plan/test_old
242
+ * 或 known_failures: [a, b]
243
+ * 每条作为子串(大小写不敏感)匹配测试输出中的失败行。
244
+ *
245
+ * @param {string} yamlText
246
+ * @returns {string[]} 模式列表;无声明返回 []
247
+ */
248
+ export function extractKnownFailures(yamlText) {
249
+ if (!yamlText) return []
250
+ // CRLF 归一(坑 verify-modules-crlf-blanket-fallback):块式正则的 `.+`/`\n?` 在 CRLF 行
251
+ // 间失配,只捕获到第一条豁免项就停——归一后整块捕获恢复
252
+ const yaml = normalizeLineEndings(yamlText)
253
+ const inline = yaml.match(/^known_failures:\s*\[([^\]]*)\]\s*(?:#.*)?$/m)
254
+ if (inline) {
255
+ return inline[1].split(',').map(s => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean)
256
+ }
257
+ const block = yaml.match(/^known_failures:\s*\n((?:[ \t]+-[ \t].+\n?)+)/m)
258
+ if (block) {
259
+ return (block[1].match(/^[ \t]+-[ \t]+(.+)/gm) || [])
260
+ .map(s => s.replace(/^[ \t]+-[ \t]+/, '').trim().replace(/^['"]|['"]$/g, '').replace(/#.*$/, '').trim())
261
+ .filter(Boolean)
262
+ }
263
+ return []
264
+ }
265
+
266
+ // 单条失败行标记(跨 pytest/jest/vitest/go/generic)。大小写不敏感。
267
+ // 刻意用 FAIL/FAILED + 配合 SUMMARY_LINE_RE 排除汇总行:否则 pytest/jest 的
268
+ // "N failed" 汇总会被误判为「需豁免的失败行」→ 永远 remaining>0 → known_failures 失效。
269
+ const PER_TEST_FAIL_RE = /(FAILED|\bFAIL\b|✕|✗|✘|panic\s*:|assertionerror|traceback|---\s*fail|error:|exception)/i
270
+ // 汇总/计数行(非单条失败):pytest === 框、jest "Tests:"、裸 "N failed/passed"、go "FAILED in Ns" 等。
271
+ const SUMMARY_LINE_RE = /(={2,}.*={2,}|^\s*\d+\s+(failed|passed|skipped|pending)\b|tests?\s*:|test\s+suites?\s*:|failed\s+in\s+\d)/i
272
+
273
+ /**
274
+ * 把测试输出按行筛出「失败行」,再按 known_failures 模式分为已豁免 / 未豁免。
275
+ * @param {string} output
276
+ * @param {string[]} knownFailures 子串模式列表(大小写不敏感)
277
+ * @returns {{ failureLines: string[], exempted: string[], remaining: string[] }}
278
+ */
279
+ export function partitionFailures(output, knownFailures) {
280
+ const lines = String(output || '').split(/\r?\n/)
281
+ const failureLines = lines.filter(l => PER_TEST_FAIL_RE.test(l) && !SUMMARY_LINE_RE.test(l))
282
+ const pats = (knownFailures || []).map(p => String(p).toLowerCase()).filter(Boolean)
283
+ const exempted = []
284
+ const remaining = []
285
+ for (const l of failureLines) {
286
+ const ll = l.toLowerCase()
287
+ if (pats.some(p => ll.includes(p))) exempted.push(l)
288
+ else remaining.push(l)
289
+ }
290
+ return { failureLines, exempted, remaining }
291
+ }
292
+
293
+ /**
294
+ * 结合 known_failures 判定单次测试运行的状态(fail-safe)。
295
+ * - exitCode 0 → passed
296
+ * - exitCode≠0 且无 known_failures → failed(原行为)
297
+ * - exitCode≠0 且有 known_failures:
298
+ * 检测到失败行且全部命中豁免 → passed(披露:请人工复核清单是否过宽)
299
+ * 有未豁免失败行 / 检测不到失败行(保守)→ failed
300
+ * fail-safe:检测不到失败行绝不自动 pass(避免解析盲区导致假 PASS)。
301
+ *
302
+ * @returns {{ status: 'passed'|'failed', reason: string|null, exemptedCount: number }}
303
+ */
304
+ export function judgeWithKnownFailures(exitCode, output, baseReason, knownFailures) {
305
+ if (exitCode === 0) return { status: 'passed', reason: baseReason, exemptedCount: 0 }
306
+ if (!knownFailures || knownFailures.length === 0) {
307
+ return { status: 'failed', reason: baseReason, exemptedCount: 0 }
308
+ }
309
+ const { failureLines, exempted, remaining } = partitionFailures(output, knownFailures)
310
+ if (failureLines.length > 0 && remaining.length === 0) {
311
+ return {
312
+ status: 'passed',
313
+ reason: `全部 ${failureLines.length} 个失败行命中 known_failures 已豁免(${exempted.length} 条)— 请人工复核豁免清单是否过宽`,
314
+ exemptedCount: exempted.length,
315
+ }
316
+ }
317
+ // 剩余未豁免失败行:列出具体行 + 预存债指引(坑 verify-known-failures-stale-list)。
318
+ // known_failures 清单常滞后于新预存测试 → 同源预存债漏入清单,agent 跑完才发现要手动补。
319
+ // 这里点出具体未命中行,让 agent 一眼分辨"补清单 vs 修代码",不替它判断(确定性:列已算出的 remaining)。
320
+ let detail
321
+ if (remaining.length > 0) {
322
+ const sample = remaining.slice(0, 5).map(l => {
323
+ const t = String(l).trim()
324
+ return t.length > 120 ? t.slice(0, 120) + '…' : t
325
+ })
326
+ const more = remaining.length > 5 ? `\n …(其余 ${remaining.length - 5} 行见上方测试输出)` : ''
327
+ detail = `${remaining.length} 个失败行未命中 known_failures 清单:\n - ${sample.join('\n - ')}${more}\n → 若是预存债(变更前就失败),加入 local.yaml 的 known_failures 清单;若是本次变更引入的真实失败,请修复`
328
+ } else {
329
+ detail = '失败输出未检测到可豁免的失败行(保守判 fail)'
330
+ }
331
+ return {
332
+ status: 'failed',
333
+ reason: baseReason ? `${baseReason}(${detail})` : detail,
334
+ exemptedCount: exempted.length,
335
+ }
336
+ }
337
+
338
+ /**
339
+ * 决定 verify 实测的执行动作(纯函数,便于测试;坑 verify-worktree-... 修复方向 3)。
340
+ * - module + 命中模块 → 'module-subset'
341
+ * - module + 0 命中 → 'module-zero-hit-skip'(不静默回退注定超时/预存失败的全量)
342
+ * - 其余(full / module 无块 / module git 不可用 hitCount=-1)→ 'full'
343
+ * @returns {'module-subset'|'module-zero-hit-skip'|'full'}
344
+ */
345
+ export function decideVerifyTestAction({ strategy, modulesPresent, hitCount }) {
346
+ if (strategy === 'module' && modulesPresent) {
347
+ if (hitCount > 0) return 'module-subset'
348
+ if (hitCount === 0) return 'module-zero-hit-skip'
349
+ return 'full' // hitCount === -1(git 不可用)→ 落全量兜底
350
+ }
351
+ return 'full'
352
+ }
353
+
354
+ /**
355
+ * 跑单个模块的 test 命令(串行调用方逐个调用)。
356
+ * @returns {{name, status:'passed'|'failed', command, exitCode, durationMs, outputTail, reason}}
357
+ */
358
+ function runOneModule(name, testCommand, cwd, knownFailures = []) {
359
+ const startedAt = Date.now()
360
+ let exitCode = 0
361
+ let output = ''
362
+ let reason = null
363
+ try {
364
+ output = execSync(testCommand, {
365
+ cwd,
366
+ encoding: 'utf8',
367
+ timeout: TEST_TIMEOUT_MS,
368
+ maxBuffer: 32 * 1024 * 1024,
369
+ stdio: ['ignore', 'pipe', 'pipe'],
370
+ })
371
+ } catch (e) {
372
+ exitCode = typeof e.status === 'number' ? e.status : 1
373
+ output = [e.stdout, e.stderr].filter(Boolean).join('\n') || e.message
374
+ reason = e.signal === 'SIGTERM' && Date.now() - startedAt >= TEST_TIMEOUT_MS
375
+ ? `模块 ${name} 测试超时(>${TEST_TIMEOUT_MS / 1000}s)`
376
+ : `模块 ${name} 测试退出码 ${exitCode}`
377
+ }
378
+ const durationMs = Date.now() - startedAt
379
+ const outputTail = output.length > OUTPUT_TAIL_CHARS ? '…' + output.slice(-OUTPUT_TAIL_CHARS) : output
380
+ const judged = judgeWithKnownFailures(exitCode, output, reason, knownFailures)
381
+ return {
382
+ name,
383
+ status: judged.status,
384
+ command: testCommand,
385
+ exitCode,
386
+ durationMs,
387
+ outputTail,
388
+ reason: judged.reason,
389
+ exemptedCount: judged.exemptedCount,
390
+ }
391
+ }
392
+
393
+ // refSpec 来源 meta.json(agent 可写),仅放行 git ref/range 安全字符(含 HEAD~1..HEAD 类区间),
394
+ // 防经 shell 的命令/参数注入。剥空白与引号/分号/反引号/$ 等 shell 元字符。
395
+ // 注:允许 ".."/"../.."(相对路径 ref 语法上合法)不影响安全——execFileSync 数组形式下它只是
396
+ // 一个 git rev 参数,git 自会报 not a valid ref,无 shell 解释面。
397
+ function assertSafeRefSpec(refSpec) {
398
+ if (typeof refSpec !== 'string') return null
399
+ if (!/^[A-Za-z0-9._~/^-]+$/.test(refSpec)) return null
400
+ if (/~~/.test(refSpec)) return null // 连续 ~(垃圾串)
401
+ return refSpec
402
+ }
403
+
404
+ /**
405
+ * 在指定 cwd 跑 `git diff --name-only <refSpec>`,返回相对仓库根的文件列表。
406
+ * git 不可用 / 非仓库 / ref 无效 → 返回 null(调用方 fallback)。
407
+ * QUAL-01 收口:本地 execFileSync 裸调 → git-helper gitQuiet(统一 safe.directory),timeout 30s 保留。
408
+ */
409
+ function runGitDiffNameOnly(cwd, refSpec) {
410
+ const ref = refSpec ? assertSafeRefSpec(refSpec) : null
411
+ if (refSpec && !ref) return null
412
+ const args = ['diff', '--name-only']
413
+ if (ref) args.push(ref)
414
+ const out = gitQuiet(cwd, args, { timeout: 30 * 1000, trim: false })
415
+ if (out === null) return null
416
+ return out.split('\n').map(l => l.trim()).filter(Boolean)
417
+ }
418
+
419
+ /**
420
+ * 在指定 cwd 跑 `git diff --name-status <refSpec>`,返回原始文本(调用方按行解析,
421
+ * 保留状态字母 D/R/C 供删除探针识别删除/重命名)。git 不可用 / 非仓库 / ref 无效 → 返回 null。
422
+ * QUAL-01 收口:同上走 gitQuiet(trim:false 保留原始文本)。
423
+ */
424
+ function runGitDiffNameStatus(cwd, refSpec) {
425
+ const ref = refSpec ? assertSafeRefSpec(refSpec) : null
426
+ if (refSpec && !ref) return null
427
+ const args = ['diff', '--name-status']
428
+ if (ref) args.push(ref)
429
+ return gitQuiet(cwd, args, { timeout: 30 * 1000, trim: false })
430
+ }
431
+
432
+ /**
433
+ * 取主工作区 git 变更文件列表(unstaged + staged,相对仓库根)。
434
+ * `git diff --name-only HEAD` 同时覆盖已暂存与未暂存改动(相对 HEAD),
435
+ * 最适合 brownfield(apply 后未 commit / in-place 改动)场景。
436
+ * git 不可用 / 非仓库 → 返回 null(调用方 fallback)。
437
+ *
438
+ * 注意:worktree 隔离模式下主仓只剩 .sillyspec/ 文档改动、代码在 worktree,
439
+ * 本函数看不到——runVerifyTestCheck 用 resolveVerifyChangedFiles 统一处理。
440
+ */
441
+ function gitChangedFiles(cwd) {
442
+ const head = runGitDiffNameOnly(cwd, 'HEAD')
443
+ if (head !== null) return head
444
+ // HEAD 不存在(空仓库)或 git 不可用 → 尝试纯 unstaged
445
+ return runGitDiffNameOnly(cwd, '')
446
+ }
447
+
448
+ /**
449
+ * 解析 verify 对账用的变更文件集(worktree-aware)。
450
+ *
451
+ * worktree 隔离模式下 execute 的代码改动落在 worktree,主仓工作区只剩
452
+ * .sillyspec/ 文档改动。若仍用主仓 `git diff --name-only HEAD`,hitCount=0
453
+ * → 回退注定超时且含预存失败的全量 commands.test → verify 完成被阻断
454
+ * (坑 verify-worktree-mode-test-reconciliation-fallback-full)。
455
+ *
456
+ * 判定(与 checkExecuteCodeEvidence / task-review 同源,meta.json 为权威):
457
+ * 1. change 有 worktree meta 且 baseHash 存在 → 在 worktree(或 in-place 的 cwd)
458
+ * 跑 `git diff --name-only <baseHash>..HEAD` 取真实代码改动集
459
+ * ⚠️ baseline checkpoint 修复:优先用 baselineCommit/actualBaseHash(baseline overlay
460
+ * 之后),否则 baseHash(pre-baseline)会把 baseline 同步的跨模块文件算进 verify diff
461
+ * → 命中无关模块(如 ppm 变更误测 daemon/frontend)。与 task-review.js 同源。
462
+ * 2. 无 worktree meta / diff 异常 → 主仓 `git diff --name-only HEAD`(brownfield 原行为)
463
+ *
464
+ * 跨仓支持(task-06 / D-004 / design §6 A6):ctx 参数可选,缺省走单仓原逻辑(零回归,
465
+ * GOAL-2)。ctx 非空且含跨仓 entry 时,主仓 diff 走原逻辑,再 per-repo 在各跨仓仓
466
+ * gitDir 跑 `git diff --name-only HEAD` 合并入结果(design §6 行 136 「per-repo 取 diff
467
+ * 合并」字面契约)。跨仓仓 diff 路径相对各自仓根。
468
+ *
469
+ * 注:runVerifyTestCheck 的 module 子集策略只消费主仓 diff(跨仓仓不参与 module 子集,
470
+ * 跨仓仓无 module 映射,design §6 + §5.4),故本函数的跨仓合并 diff 在 module 子集
471
+ * 路径无副作用——本函数仅供「per-repo diff 合并」语义契约 + 未来 consumer 复用。
472
+ *
473
+ * @param {string} cwd - 项目根目录(主仓)
474
+ * @param {string|null} changeName
475
+ * @param {object|null} [ctx] - MultiRepoContext 实例(可选,缺省/null 走单仓原逻辑)
476
+ * @returns {string[]|null} 变更文件列表;git 不可用返回 null(调用方按 hitCount=-1 处理)
477
+ */
478
+ export function resolveVerifyChangedFiles(cwd, changeName, ctx = null) {
479
+ // 主仓 diff(原逻辑不动,单仓零回归)
480
+ const mainFiles = resolveMainChangedFiles(cwd, changeName)
481
+
482
+ // 无 ctx / ctx 无跨仓 entry → 主仓 diff 即结果(零回归)
483
+ if (!ctx || typeof ctx.repos !== 'object' || ctx.repos === null) return mainFiles
484
+ const crossEntries = []
485
+ for (const entry of ctx.repos.values()) {
486
+ if (entry && entry.isMain === false) crossEntries.push(entry)
487
+ }
488
+ if (crossEntries.length === 0) return mainFiles
489
+
490
+ // 主仓 git 不可用(null)→ 不强制兜底,保留 null 语义让调用方按 hitCount=-1 处理。
491
+ // 跨仓仓 diff 各自取,任一可用即合并;全不可用且主仓 null → 返 null。
492
+ // 跨仓仓 diff 锚点:HEAD~1..HEAD(跨仓 task 子代理 commit 到主干,verify 时最近一笔 commit
493
+ // 即本次 task 改动;多 task 同仓时仅反映最近一笔,精确范围由 task 卡 base/head 锡点锚定,
494
+ // 那是 task-04 的 scope,本函数不消费锡点——跨仓合并 diff 在 verify-postcheck 内仅供
495
+ // 「per-repo diff 合并」语义契约 + 未来 consumer,module 子集只用主仓 diff)。
496
+ const merged = mainFiles ? mainFiles.slice() : []
497
+ let anyAvailable = mainFiles !== null
498
+ for (const entry of crossEntries) {
499
+ // 跨仓仓 gitDir = 跨仓仓根(MultiRepoContext._buildCrossRepoEntry 已 fail-closed 保证可达)
500
+ const files = runGitDiffNameOnly(entry.gitDir, 'HEAD~1..HEAD')
501
+ if (files !== null) {
502
+ anyAvailable = true
503
+ for (const f of files) {
504
+ if (!merged.includes(f)) merged.push(f)
505
+ }
506
+ }
507
+ }
508
+ return anyAvailable ? merged : null
509
+ }
510
+
511
+ /**
512
+ * 主仓变更文件解析(原 resolveVerifyChangedFiles 逻辑,单仓零回归基线)。
513
+ * 抽出供 resolveVerifyChangedFiles 复用,跨仓合并时主仓部分走此函数(不动)。
514
+ *
515
+ * @param {string} cwd - 主仓根
516
+ * @param {string|null} changeName
517
+ * @returns {string[]|null}
518
+ */
519
+ function resolveMainChangedFiles(cwd, changeName) {
520
+ if (changeName) {
521
+ const metaPath = join(cwd, '.sillyspec', '.runtime', 'worktrees', changeName, 'meta.json')
522
+ if (existsSync(metaPath)) {
523
+ let meta = null
524
+ try { meta = JSON.parse(readFileSync(metaPath, 'utf8')) } catch {}
525
+ // 优先 baselineCommit/actualBaseHash(baseline checkpoint 之后),回退 baseHash
526
+ const diffBase = meta?.baselineCommit || meta?.actualBaseHash || meta?.baseHash
527
+ if (diffBase) {
528
+ const gitDir = (meta.worktreePath && meta.mode !== 'in-place-fallback' && existsSync(meta.worktreePath))
529
+ ? meta.worktreePath
530
+ : cwd
531
+ const files = runGitDiffNameOnly(gitDir, `${diffBase}..HEAD`)
532
+ if (files !== null) return files
533
+ // worktree diff 异常 → 落主仓兜底(保持与原 gitChangedFiles 相同的 null 语义)
534
+ }
535
+ }
536
+ }
537
+ return gitChangedFiles(cwd)
538
+ }
539
+
540
+ /**
541
+ * 执行 verify 实测:读取 local.yaml 配置,按 test_strategy 决定全量或模块子集。
542
+ *
543
+ * 跨仓支持(task-06 / D-004 / design §5.4 + §6 A6 + §9):opts.ctx 可选,缺省走单仓
544
+ * 原逻辑(零回归,GOAL-2)。ctx 非空且含跨仓 entry 时,主仓跑原 module 子集 / full npm
545
+ * test(行为不变),再 per-repo cwd 在各跨仓仓根跑 full npm test(跨仓仓不参与 module
546
+ * 子集策略——跨仓仓无主仓的 module 映射,design §6 + §5.4);跨仓仓无 package.json 则
547
+ * 跳过 + warn 不阻断 verify(design §9 兼容策略「跨仓仓无 package.json 跳过 warn」)。
548
+ * 任一仓 fail → 整体 fail(fail-fast 语义,跨仓仓的真实失败不能被主仓 PASS 掩盖)。
549
+ *
550
+ * @param {object} opts
551
+ * @param {string} opts.cwd - 项目根目录(主仓,测试执行目录)
552
+ * @param {string} opts.specBase - .sillyspec(或平台 specRoot)目录
553
+ * @param {string|null} [opts.changeName]
554
+ * @param {object|null} [opts.ctx] - MultiRepoContext 实例(可选,缺省/null 走单仓原逻辑)
555
+ * @returns {{
556
+ * status: 'passed'|'failed'|'skipped',
557
+ * command: string|null,
558
+ * exitCode: number|null,
559
+ * durationMs: number|null,
560
+ * outputTail: string|null,
561
+ * reason: string|null,
562
+ * resultPath: string|null,
563
+ * }}
564
+ */
565
+ export function runVerifyTestCheck({ cwd, specBase, changeName = null, ctx = null }) {
566
+ // 信任边界声明(体检 SEC-02 核实):本函数三处 execSync(command) 的命令只来源于
567
+ // ① 主仓 specBase(resolveSpecDir → 主仓 .sillyspec/local.yaml)② 跨仓仓根
568
+ // <repo>/.sillyspec/local.yaml——均为仓库自有配置(与 `npm test` 同信任级:跑测试
569
+ // 本就是执行项目代码)。永不读取 agent 可写的 worktree 副本(对照 worktree-deps.js
570
+ // SEC-01 的源级分流);修改 yaml 来源时必须维持此边界。
571
+ const localYamlPath = join(specBase, 'local.yaml')
572
+ const yamlText = existsSync(localYamlPath) ? readFileSync(localYamlPath, 'utf8') : null
573
+
574
+ const strategy = extractTestStrategy(yamlText)
575
+ const knownFailures = extractKnownFailures(yamlText)
576
+
577
+ // —— 模块子集路径(test_strategy: module):算 modulesPresent / hitCount / hits ——
578
+ // resolveVerifyChangedFiles 返回 null 表示 git 不可用 → hitCount=-1(与 0 命中区分)。
579
+ // 注:module 子集策略只用主仓 diff(跨仓仓不参与 module 子集,design §6 + §5.4),
580
+ // 故此处不传 ctx(避免跨仓路径误命中主仓 module 映射)。
581
+ let modulesPresent = false
582
+ let hitCount = 0
583
+ let hits = []
584
+ if (strategy === 'module') {
585
+ const modules = extractModules(yamlText)
586
+ if (modules) {
587
+ modulesPresent = true
588
+ const changedFiles = resolveVerifyChangedFiles(cwd, changeName)
589
+ if (changedFiles === null) {
590
+ hitCount = -1 // git 不可用 / 非仓库
591
+ } else {
592
+ hits = pickHitModules(changedFiles, modules)
593
+ hitCount = hits.length
594
+ }
595
+ }
596
+ }
597
+
598
+ const action = decideVerifyTestAction({ strategy, modulesPresent, hitCount })
599
+ let mainResult
600
+ if (action === 'module-subset') {
601
+ mainResult = runModuleSubset({ cwd, specBase, changeName, hits, knownFailures })
602
+ } else if (action === 'module-zero-hit-skip') {
603
+ // module 模式 0 命中:不静默回退注定超时/含预存失败的全量(坑 verify-worktree-... 修复方向 3)。
604
+ // 据 verify-result.md 自报告判定;想跑全量请显式设 test_strategy: full。
605
+ mainResult = {
606
+ status: 'skipped',
607
+ command: null,
608
+ exitCode: null,
609
+ durationMs: null,
610
+ outputTail: null,
611
+ reason: 'test_strategy: module 但本次变更未命中任何已配置 modules(0 命中)。为避免回退到注定超时/含预存失败的全量 commands.test,CLI 未自动跑全量——据 verify-result.md 自报告判定测试。若需全量覆盖,显式设 test_strategy: full。',
612
+ resultPath: null,
613
+ mode: 'module-zero-hit',
614
+ fallbackReason: null,
615
+ }
616
+ } else {
617
+ // —— 全量路径(full / module 无块 / module git 不可用)——
618
+ // fallbackReason 非 null 表示本次全量是"非显式"的(缺省/配置不全/未命中),需明示。
619
+ const fallbackReason = computeFullFallbackReason({ strategy, modulesPresent, hitCount })
620
+ mainResult = runFullCommand({ yamlText, localYamlPath, cwd, specBase, changeName, fallbackReason, knownFailures })
621
+ }
622
+
623
+ // —— 跨仓仓 per-repo cwd 跑 full npm test(task-06 / D-004 / design §5.4 + §6 A6)——
624
+ // ctx 为空或无跨仓 entry → 直接返主仓结果(单仓零回归,GOAL-2)。
625
+ // 跨仓仓不参与 module 子集策略,只跑 full npm test(design §6 + §5.4);
626
+ // 跨仓仓无 package.json → 跳过 + warn 不阻断(design §9 兼容策略)。
627
+ // 任一跨仓仓 fail → 整体 fail(合并语义)。
628
+ return mergeCrossRepoResults(mainResult, ctx)
629
+ }
630
+
631
+ /**
632
+ * per-repo cwd 跑跨仓仓 full npm test,合并进主仓结果。
633
+ *
634
+ * design §6 A6 + §5.4 + §9 兼容策略:
635
+ * - 跨仓仓有 package.json → 在该仓 projectRoot cwd 跑 full npm test(跨仓仓 own local.yaml
636
+ * 若有 commands.test 用之,否则 fallback `npm test`)
637
+ * - 跨仓仓无 package.json → 跳过 + console.warn(不阻断 verify)
638
+ * - 跨仓仓只跑 full npm test,不参与 module 子集策略(module 映射主仓强相关)
639
+ * - 任一仓 fail → 整体 fail;主仓 skipped + 跨仓仓 passed → 整体 passed(跨仓仓有测试即有效)
640
+ *
641
+ * 单仓 ctx(无跨仓 entry)→ 直接返主仓结果,零行为变化(GOAL-2)。
642
+ *
643
+ * @param {object} mainResult - 主仓 runVerifyTestCheck 结果
644
+ * @param {object|null} ctx - MultiRepoContext 实例
645
+ * @returns {object} 合并后结果(shape 同 mainResult)
646
+ */
647
+ function mergeCrossRepoResults(mainResult, ctx) {
648
+ if (!ctx || typeof ctx.repos !== 'object' || ctx.repos === null) return mainResult
649
+ const crossEntries = []
650
+ for (const entry of ctx.repos.values()) {
651
+ if (entry && entry.isMain === false) crossEntries.push(entry)
652
+ }
653
+ if (crossEntries.length === 0) return mainResult
654
+
655
+ const crossResults = []
656
+ for (const entry of crossEntries) {
657
+ const crossResult = runCrossRepoFullTest(entry)
658
+ crossResults.push({ repoKey: entry.repoKey, projectRoot: entry.projectRoot, result: crossResult })
659
+ }
660
+
661
+ // 合并:任一 fail → fail;否则取主仓 status(passed/skipped 与跨仓 passed 合并)
662
+ const failedRepos = crossResults.filter(r => r.result.status === 'failed')
663
+ if (failedRepos.length > 0) {
664
+ return mergeResultStatus({
665
+ status: 'failed',
666
+ mainResult,
667
+ crossResults,
668
+ reason: `跨仓仓测试失败:${failedRepos.map(r => r.repoKey).join(', ')}`,
669
+ })
670
+ }
671
+ // 跨仓仓全 passed 或 skipped(无 package.json)→ 主仓 status 不变(合并跨仓信息到 outputTail)
672
+ return mergeResultInfo(mainResult, crossResults)
673
+ }
674
+
675
+ /**
676
+ * 在单个跨仓仓根跑 full npm test(跨仓仓不参与 module 子集,只跑 full)。
677
+ * 跨仓仓 own local.yaml 若存在且配 commands.test → 用之;否则 fallback `npm test`。
678
+ * 跨仓仓无 package.json → 跳过 + warn。
679
+ *
680
+ * @param {object} entry - RepoEntry(isMain=false)
681
+ * @returns {object} 结果 shape 对齐 runFullCommand 返回
682
+ */
683
+ function runCrossRepoFullTest(entry) {
684
+ const projectRoot = entry.projectRoot
685
+ // 跨仓仓无 package.json → 跳过 + warn(design §9 兼容策略,不阻断 verify)
686
+ if (!existsSync(join(projectRoot, 'package.json'))) {
687
+ console.warn(`⚠️ 跨仓 repo "${entry.repoKey}"(${projectRoot})无 package.json,跳过该仓 npm test(design §9 兼容策略,不阻断 verify)。`)
688
+ return {
689
+ status: 'skipped',
690
+ command: null,
691
+ exitCode: null,
692
+ durationMs: null,
693
+ outputTail: null,
694
+ reason: `跨仓 repo "${entry.repoKey}" 无 package.json,跳过 npm test`,
695
+ resultPath: null,
696
+ mode: 'cross-repo-skip',
697
+ repoKey: entry.repoKey,
698
+ }
699
+ }
700
+
701
+ // 跨仓仓 own local.yaml(在跨仓仓 .sillyspec/ 下,若存在)配 commands.test → 用之;否则 `npm test`
702
+ // 注:跨仓仓按 NG-1 不建 .sillyspec/,但容错读取(用户可手动放 local.yaml 配跨仓仓特定测试命令)
703
+ const crossLocalYaml = join(projectRoot, '.sillyspec', 'local.yaml')
704
+ let command = 'npm test'
705
+ let crossKnownFailures = []
706
+ if (existsSync(crossLocalYaml)) {
707
+ try {
708
+ const crossYaml = readFileSync(crossLocalYaml, 'utf8')
709
+ const extracted = extractTestCommand(crossYaml)
710
+ if (extracted) command = extracted
711
+ crossKnownFailures = extractKnownFailures(crossYaml)
712
+ } catch { /* 读取失败 fallback npm test */ }
713
+ }
714
+
715
+ const startedAt = Date.now()
716
+ let exitCode = 0
717
+ let output = ''
718
+ let reason = null
719
+ try {
720
+ output = execSync(command, {
721
+ cwd: projectRoot,
722
+ encoding: 'utf8',
723
+ timeout: TEST_TIMEOUT_MS,
724
+ maxBuffer: 32 * 1024 * 1024,
725
+ stdio: ['ignore', 'pipe', 'pipe'],
726
+ })
727
+ } catch (e) {
728
+ exitCode = typeof e.status === 'number' ? e.status : 1
729
+ output = [e.stdout, e.stderr].filter(Boolean).join('\n') || e.message
730
+ reason = e.signal === 'SIGTERM' && Date.now() - startedAt >= TEST_TIMEOUT_MS
731
+ ? `跨仓 repo "${entry.repoKey}" 测试超时(>${TEST_TIMEOUT_MS / 1000}s)`
732
+ : `跨仓 repo "${entry.repoKey}" 测试退出码 ${exitCode}`
733
+ }
734
+ const durationMs = Date.now() - startedAt
735
+ const outputTail = output.length > OUTPUT_TAIL_CHARS ? '…' + output.slice(-OUTPUT_TAIL_CHARS) : output
736
+ const judged = judgeWithKnownFailures(exitCode, output, reason, crossKnownFailures)
737
+
738
+ return {
739
+ status: judged.status,
740
+ command,
741
+ exitCode,
742
+ durationMs,
743
+ outputTail,
744
+ reason: judged.reason,
745
+ resultPath: null,
746
+ mode: 'cross-repo-full',
747
+ repoKey: entry.repoKey,
748
+ exemptedCount: judged.exemptedCount,
749
+ }
750
+ }
751
+
752
+ /**
753
+ * 合并失败状态:整体 failed,保留主仓 + 各跨仓仓明细到 outputTail / reason。
754
+ */
755
+ function mergeResultStatus({ status, mainResult, crossResults, reason }) {
756
+ const parts = []
757
+ parts.push(`── main (${mainResult.status}) ──\n${mainResult.outputTail || mainResult.reason || ''}`)
758
+ for (const cr of crossResults) {
759
+ parts.push(`── cross-repo ${cr.repoKey} (${cr.result.status}) ──\n${cr.result.outputTail || cr.result.reason || ''}`)
760
+ }
761
+ const mergedTail = parts.join('\n')
762
+ return {
763
+ status,
764
+ command: mainResult.command ? `${mainResult.command} + cross-repo[${crossResults.map(r => r.repoKey).join(',')}]` : `cross-repo[${crossResults.map(r => r.repoKey).join(',')}]`,
765
+ exitCode: 1,
766
+ durationMs: (mainResult.durationMs || 0) + crossResults.reduce((n, r) => n + (r.result.durationMs || 0), 0),
767
+ outputTail: mergedTail.length > OUTPUT_TAIL_CHARS ? '…' + mergedTail.slice(-OUTPUT_TAIL_CHARS) : mergedTail,
768
+ reason,
769
+ resultPath: mainResult.resultPath,
770
+ mode: 'cross-repo-merged',
771
+ fallbackReason: mainResult.fallbackReason || null,
772
+ }
773
+ }
774
+
775
+ /**
776
+ * 合并信息(跨仓仓全 passed/skipped):主仓 status 保留,跨仓仓 PASSED 信息附入 outputTail。
777
+ */
778
+ function mergeResultInfo(mainResult, crossResults) {
779
+ const crossPassed = crossResults.filter(r => r.result.status === 'passed')
780
+ const crossSkipped = crossResults.filter(r => r.result.status === 'skipped')
781
+ if (crossPassed.length === 0 && crossSkipped.length === 0) return mainResult
782
+ const crossSummary = []
783
+ for (const cr of crossPassed) crossSummary.push(`cross-repo ${cr.repoKey}: PASS`)
784
+ for (const cr of crossSkipped) crossSummary.push(`cross-repo ${cr.repoKey}: SKIP(${cr.result.reason || 'no package.json'})`)
785
+ const crossLine = `\n── 跨仓仓 npm test ──\n${crossSummary.join('\n')}`
786
+ const mergedTail = (mainResult.outputTail || '') + crossLine
787
+ return {
788
+ ...mainResult,
789
+ outputTail: mergedTail.length > OUTPUT_TAIL_CHARS ? '…' + mergedTail.slice(-OUTPUT_TAIL_CHARS) : mergedTail,
790
+ mode: mainResult.mode ? `${mainResult.mode}+cross-repo` : 'cross-repo-merged',
791
+ }
792
+ }
793
+
794
+ /**
795
+ * 全量跑 commands.test(现有逻辑,brownfield 行为不变)。
796
+ */
797
+ function runFullCommand({ yamlText, localYamlPath, cwd, specBase, changeName, fallbackReason = null, knownFailures = [] }) {
798
+ const command = extractTestCommand(yamlText)
799
+
800
+ if (!command) {
801
+ return {
802
+ status: 'skipped',
803
+ command: null,
804
+ exitCode: null,
805
+ durationMs: null,
806
+ outputTail: null,
807
+ reason: yamlText
808
+ ? 'local.yaml 未配置 commands.test(或标记 unavailable)'
809
+ : `local.yaml 不存在(${localYamlPath})`,
810
+ resultPath: null,
811
+ mode: 'full',
812
+ fallbackReason,
813
+ }
814
+ }
815
+
816
+ const startedAt = Date.now()
817
+ let exitCode = 0
818
+ let output = ''
819
+ let reason = null
820
+ try {
821
+ output = execSync(command, {
822
+ cwd,
823
+ encoding: 'utf8',
824
+ timeout: TEST_TIMEOUT_MS,
825
+ maxBuffer: 32 * 1024 * 1024,
826
+ stdio: ['ignore', 'pipe', 'pipe'],
827
+ })
828
+ } catch (e) {
829
+ exitCode = typeof e.status === 'number' ? e.status : 1
830
+ output = [e.stdout, e.stderr].filter(Boolean).join('\n') || e.message
831
+ reason = e.signal === 'SIGTERM' && Date.now() - startedAt >= TEST_TIMEOUT_MS
832
+ ? `测试命令超时(>${TEST_TIMEOUT_MS / 1000}s)`
833
+ : `测试命令退出码 ${exitCode}`
834
+ }
835
+ const durationMs = Date.now() - startedAt
836
+ const outputTail = output.length > OUTPUT_TAIL_CHARS ? '…' + output.slice(-OUTPUT_TAIL_CHARS) : output
837
+
838
+ const judged = judgeWithKnownFailures(exitCode, output, reason, knownFailures)
839
+ const result = {
840
+ status: judged.status,
841
+ command,
842
+ exitCode,
843
+ durationMs,
844
+ outputTail,
845
+ reason: judged.reason,
846
+ resultPath: null,
847
+ mode: 'full',
848
+ fallbackReason,
849
+ exemptedCount: judged.exemptedCount,
850
+ }
851
+
852
+ writeRunResult({ specBase, changeName, result, extra: fallbackReason ? { fallback_reason: fallbackReason } : {} })
853
+ return result
854
+ }
855
+
856
+ /**
857
+ * 串行跑命中的模块子集,聚合结果。
858
+ * 返回 shape 与 runFullCommand 一致(status/command/exitCode/durationMs/outputTail/reason/resultPath)。
859
+ */
860
+ function runModuleSubset({ cwd, specBase, changeName, hits, knownFailures = [] }) {
861
+ const subsetStartedAt = Date.now()
862
+ const perModule = hits.map(h => runOneModule(h.name, h.test, cwd, knownFailures))
863
+ const status = aggregateStatus(perModule)
864
+
865
+ const command = `module[${hits.map(h => h.name).join(',')}]`
866
+ const exitCode = status === 'passed' ? 0 : 1
867
+ const durationMs = Date.now() - subsetStartedAt
868
+
869
+ // 合并各模块输出尾部(标注模块名)
870
+ const outputTail = perModule
871
+ .map(r => `── module ${r.name} (${r.status}) ──\n${r.outputTail || ''}`)
872
+ .join('\n')
873
+ const reason = status === 'passed'
874
+ ? null
875
+ : `模块子集测试失败:${perModule.filter(r => r.status === 'failed').map(r => r.name).join(', ')}`
876
+
877
+ const result = {
878
+ status,
879
+ command,
880
+ exitCode,
881
+ durationMs,
882
+ outputTail: outputTail.length > OUTPUT_TAIL_CHARS ? '…' + outputTail.slice(-OUTPUT_TAIL_CHARS) : outputTail,
883
+ reason,
884
+ resultPath: null,
885
+ mode: 'module-subset',
886
+ fallbackReason: null,
887
+ exemptedCount: perModule.reduce((n, r) => n + (r.exemptedCount || 0), 0),
888
+ }
889
+
890
+ writeRunResult({
891
+ specBase,
892
+ changeName,
893
+ result,
894
+ extra: {
895
+ modules: perModule.map(r => ({
896
+ name: r.name,
897
+ command: r.command,
898
+ exit_code: r.exitCode,
899
+ status: r.status,
900
+ duration_ms: r.durationMs,
901
+ output_tail: r.outputTail,
902
+ reason: r.reason,
903
+ })),
904
+ },
905
+ })
906
+ return result
907
+ }
908
+
909
+ /**
910
+ * 结果落盘到 .runtime/verify-runs/<ts>/test-result.json(供追溯与 SillyHub 消费)。
911
+ * 多模块时 extra.modules 描述各模块明细。
912
+ */
913
+ function writeRunResult({ specBase, changeName, result, extra = {} }) {
914
+ try {
915
+ const ts = new Date().toISOString().slice(0, 19).replace(/[-T:]/g, '')
916
+ const runDir = join(specBase, '.runtime', 'verify-runs', ts)
917
+ mkdirSync(runDir, { recursive: true })
918
+ const resultPath = join(runDir, 'test-result.json')
919
+ writeFileSync(resultPath, JSON.stringify({
920
+ change: changeName,
921
+ command: result.command,
922
+ exit_code: result.exitCode,
923
+ status: result.status,
924
+ duration_ms: result.durationMs,
925
+ output_tail: result.outputTail,
926
+ reason: result.reason,
927
+ ran_at: new Date().toISOString(),
928
+ ...extra,
929
+ }, null, 2) + '\n')
930
+ result.resultPath = resultPath
931
+ } catch (e) {
932
+ console.warn(`⚠️ verify 实测结果落盘失败: ${e.message}`)
933
+ }
934
+ }
935
+
936
+ /** 打印实测结果(人类/agent 可读) */
937
+ export function printVerifyTestCheck(result) {
938
+ if (result.status === 'skipped') {
939
+ console.warn(`\n⚠️ Verify 实测跳过:${result.reason}`)
940
+ console.warn(' 建议在 local.yaml 的 commands.test 配置真实测试命令,让 CLI 可客观对账。')
941
+ return
942
+ }
943
+ if (result.status === 'passed') {
944
+ if (result.exemptedCount > 0) {
945
+ console.log(`\n✅ Verify 实测通过(含 ${result.exemptedCount} 个 known_failures 豁免):\`${result.command}\` — ${result.reason}`)
946
+ console.warn(' ⚠️ 本次 PASS 依赖 known_failures 豁免清单——请人工复核清单是否过宽(避免误豁免本变更引入的真实失败)。')
947
+ } else {
948
+ console.log(`\n✅ Verify 实测通过:\`${result.command}\` 退出码 0(${(result.durationMs / 1000).toFixed(1)}s)`)
949
+ }
950
+ } else {
951
+ console.error(`\n❌ Verify 实测失败:\`${result.command}\` — ${result.reason}`)
952
+ if (result.outputTail) {
953
+ const tail = result.outputTail.split('\n').slice(-20).join('\n')
954
+ console.error(' 输出(末尾):')
955
+ for (const line of tail.split('\n')) console.error(` | ${line}`)
956
+ }
957
+ }
958
+ // —— 全量 fallback 明示(skipped 已提前 return,此处仅 passed/failed)——
959
+ // 让 agent 知道本次跑的是全量 commands.test、非变更范围子集;失败可能含未变更模块
960
+ // 的预存错误,需先核对用例归属再归因到本次变更(见 3.24 verify 坑1)。
961
+ if (result.mode === 'full' && result.fallbackReason) {
962
+ if (result.status === 'failed') {
963
+ console.warn(` ⚠️ 本次跑的是 commands.test 全量(${result.fallbackReason})。`)
964
+ console.warn(' 失败可能含与本变更无关的预存错误——先核对失败用例是否属于你的变更范围;')
965
+ console.warn(' 或在 local.yaml 配置 test_strategy: module + modules: 块以收窄到变更模块。')
966
+ } else {
967
+ console.warn(` ⚠️ 本次跑的是 commands.test 全量(${result.fallbackReason})。`)
968
+ console.warn(' 如耗时过长,可在 local.yaml 配置 test_strategy: module + modules: 块按模块收窄。')
969
+ }
970
+ }
971
+ if (result.resultPath) {
972
+ console.log(`📄 实测结果已写入: ${result.resultPath}`)
973
+ }
974
+ }
975
+
976
+ /**
977
+ * API parity 对账(advisory):前端调用 vs execute 提取的后端 endpoint artifact。
978
+ * 三态:skipped(无 provider artifact → 非全栈项目不打扰)/ warning(missingBackend>0)/ passed。
979
+ * 启发式正则、多假阳源 → advisory 不阻断 verify 完成(与 SillySpec 确定性校验定位一致)。
980
+ *
981
+ * @param {object} opts
982
+ * @param {string} opts.cwd - 扫描前端调用的根(主工作区,verify 时代码在此)
983
+ * @param {string} opts.specBase
984
+ * @param {string|null} [opts.changeName]
985
+ * @param {string|null} [opts.runtimeRoot]
986
+ * @returns {{ status: 'skipped'|'warning'|'passed', missingBackend: Array, unusedBackend: Array, summary: string, reason: string|null }}
987
+ */
988
+ export function runVerifyParityCheck({ cwd, specBase, changeName = null, runtimeRoot = null }) {
989
+ const r = verifyApiParity(specBase, cwd, runtimeRoot, changeName)
990
+ // 无 provider artifact(execute 未提取 / 非后端项目)→ 不打扰
991
+ if (r.backendCount === 0) {
992
+ return { status: 'skipped', missingBackend: [], unusedBackend: [], summary: r.summary, reason: '无后端契约 artifact(非全栈项目或 execute 未提取端点)' }
993
+ }
994
+ if (r.missingBackend.length > 0) {
995
+ return { status: 'warning', missingBackend: r.missingBackend, unusedBackend: r.unusedBackend, summary: r.summary, reason: null }
996
+ }
997
+ return { status: 'passed', missingBackend: [], unusedBackend: r.unusedBackend, summary: r.summary, reason: null }
998
+ }
999
+
1000
+ /** 打印 parity 对账结果(advisory,不阻断) */
1001
+ export function printVerifyParityCheck(result) {
1002
+ if (result.status === 'skipped') return // 静默,不打扰非全栈项目
1003
+ if (result.status === 'passed') {
1004
+ console.log(`\n✅ API parity 对账通过:${result.summary}`)
1005
+ return
1006
+ }
1007
+ // warning
1008
+ console.warn(`\n⚠️ API parity 对账发现 ${result.missingBackend.length} 个前端调用无对应后端端点(advisory,不阻断归档):`)
1009
+ for (const m of result.missingBackend.slice(0, 20)) {
1010
+ console.warn(` - ${m.method} ${m.path} ← ${m.consumerFile}:${m.consumerLine}`)
1011
+ }
1012
+ if (result.missingBackend.length > 20) console.warn(` …还有 ${result.missingBackend.length - 20} 个`)
1013
+ console.warn(' 提示:检查是否后端漏实现,或前端调用了尚未实现的端点。确认无误可在 design.md 标注豁免。')
1014
+ }
1015
+
1016
+ /**
1017
+ * 删除探针(advisory):用 git 事实客观对账本次变更删除的文件 vs design.md 声明的操作。
1018
+ *
1019
+ * 切斯特顿栅栏护栏——verify 对「agent 静默删除代码」本是盲区:agent 删一段它看不懂的
1020
+ * 旧代码,只要路径合规、不碰风险关键词,5 探针 + 风险分级 + 测试对账全都不会响。本探针
1021
+ * 不信任 agent 自报告,用 `git diff --name-status HEAD` 客观提取删除文件,对账 design
1022
+ * 清单声明的操作(声明「新增/修改」却整文件删除 = 高风险)。warning 不阻断 verify 完成
1023
+ * (advisory 起步)——「检测到删除」是确定性事实(做),「该不该删」是意图(只报不拦)。
1024
+ *
1025
+ * 信号源:apply(git apply --3way)不 commit,verify 时主仓 HEAD 仍是变更前 commit,
1026
+ * 删除的文件在工作树消失但仍在 HEAD → `git diff --name-status HEAD` 显示 D。
1027
+ *
1028
+ * @param {object} opts
1029
+ * @param {string} opts.cwd - 项目根(主仓,代码在此)
1030
+ * @param {string} opts.specBase - .sillyspec(或平台 specRoot)
1031
+ * @param {string|null} [opts.changeName]
1032
+ * @returns {{
1033
+ * status: 'skipped'|'warning'|'passed',
1034
+ * highRisk: Array<{path:string, declaredOp:string, reason:string}>,
1035
+ * mediumRisk: Array<{path:string, reason:string}>,
1036
+ * compliant: Array<{path:string, declaredOp:string}>,
1037
+ * summary: string,
1038
+ * reason: string|null,
1039
+ * }}
1040
+ */
1041
+ export function runVerifyDeletionCheck({ cwd, specBase, changeName = null }) {
1042
+ const statusRaw = runGitDiffNameStatus(cwd, 'HEAD')
1043
+ if (statusRaw === null) {
1044
+ return { status: 'skipped', highRisk: [], mediumRisk: [], compliant: [],
1045
+ summary: '', reason: 'git 不可用或非仓库,删除对账跳过' }
1046
+ }
1047
+
1048
+ // 解析 D(删除);R/C 的旧路径等价删除(防御 committed rename;标准 apply 流程
1049
+ // rename 表现为纯 D,故本探针不加 -M,D 统一处理)。
1050
+ const deletions = []
1051
+ for (const line of statusRaw.split('\n').filter(Boolean)) {
1052
+ const parts = line.split('\t')
1053
+ const st = parts[0]
1054
+ if (!st) continue
1055
+ if (st.startsWith('D')) {
1056
+ deletions.push({ path: parts[1], kind: 'D' })
1057
+ } else if ((st.startsWith('R') || st.startsWith('C')) && parts.length >= 3) {
1058
+ // rename/copy 旧路径(parts[1])等价删除,新路径 parts[2]
1059
+ deletions.push({ path: parts[1], kind: 'R-old', renamedTo: parts[2] })
1060
+ }
1061
+ }
1062
+
1063
+ // 排除交付物外文件(.sillyspec/ 变更包/运行时/quicklog + meta.json),避免污染删除信号。
1064
+ // 复用 worktree-apply.js 的 filterDeliverableFiles 去双写(坑3:保留 .sillyspec/docs/)。
1065
+ const deliverable = filterDeliverableFiles(deletions.map(d => d.path))
1066
+ .map(p => deletions.find(d => d.path === p))
1067
+
1068
+ if (deliverable.length === 0) {
1069
+ return { status: 'skipped', highRisk: [], mediumRisk: [], compliant: [],
1070
+ summary: '', reason: '本次变更无文件删除(或改动已被 commit,主仓 HEAD 已推进,删除对账无锚点)' }
1071
+ }
1072
+
1073
+ // 读 design 声明(operation)。无清单章节 → [],所有删除归「未声明」。
1074
+ const designPath = changeName
1075
+ ? join(specBase, 'changes', changeName, 'design.md') : null
1076
+ const designEntries = designPath && existsSync(designPath)
1077
+ ? parseFileChangeListDetailed(designPath) : []
1078
+
1079
+ const highRisk = []
1080
+ const mediumRisk = []
1081
+ const compliant = []
1082
+ for (const d of deliverable) {
1083
+ const hit = designEntries.find(e => pathMatches(d.path, e.path))
1084
+ if (!hit) {
1085
+ mediumRisk.push({ path: d.path, reason: d.kind === 'R-old'
1086
+ ? `重命名源文件未在 design 清单(→ ${d.renamedTo})`
1087
+ : 'design 清单未列出该删除文件' })
1088
+ continue
1089
+ }
1090
+ if (hit.operation === '新增' || hit.operation === '修改') {
1091
+ highRisk.push({ path: d.path, declaredOp: hit.operation,
1092
+ reason: `design 声明「${hit.operation}」但 git 显示整文件删除` })
1093
+ } else if (hit.operation === '删除') {
1094
+ compliant.push({ path: d.path, declaredOp: '删除' })
1095
+ } else {
1096
+ // operation=null(未声明操作)或 重命名:删除发生但声明不明确
1097
+ mediumRisk.push({ path: d.path,
1098
+ reason: `design 列出但操作为「${hit.operation || '未声明'}」,与删除不一致` })
1099
+ }
1100
+ }
1101
+
1102
+ if (highRisk.length > 0 || mediumRisk.length > 0) {
1103
+ return { status: 'warning', highRisk, mediumRisk, compliant,
1104
+ summary: `${highRisk.length} 个高风险删除 + ${mediumRisk.length} 个未声明删除`, reason: null }
1105
+ }
1106
+ return { status: 'passed', highRisk: [], mediumRisk: [], compliant,
1107
+ summary: `所有 ${compliant.length} 个删除均在 design 声明为「删除」`, reason: null }
1108
+ }
1109
+
1110
+ /** 打印删除对账结果(advisory,不阻断 verify 完成) */
1111
+ export function printVerifyDeletionCheck(result) {
1112
+ if (result.status === 'skipped') return // 静默:无删除 / git 不可用 / 改动已 commit
1113
+ if (result.status === 'passed') {
1114
+ console.log(`\n✅ 删除对账通过:${result.summary}`)
1115
+ return
1116
+ }
1117
+ // warning
1118
+ if (result.highRisk.length > 0) {
1119
+ console.warn(`\n⚠️ 删除对账发现 ${result.highRisk.length} 个高风险删除(design 声明新增/修改却被整文件删除,advisory 不阻断):`)
1120
+ for (const m of result.highRisk.slice(0, 20)) console.warn(` - ${m.path} (${m.reason})`)
1121
+ if (result.highRisk.length > 20) console.warn(` …还有 ${result.highRisk.length - 20} 个`)
1122
+ }
1123
+ if (result.mediumRisk.length > 0) {
1124
+ console.warn(`⚠️ ${result.mediumRisk.length} 个未声明删除(design 清单未列出 / 操作不一致):`)
1125
+ for (const m of result.mediumRisk.slice(0, 20)) console.warn(` - ${m.path} (${m.reason})`)
1126
+ if (result.mediumRisk.length > 20) console.warn(` …还有 ${result.mediumRisk.length - 20} 个`)
1127
+ }
1128
+ console.warn(' 提示:确认删除是否预期。预期删除请在 design.md 清单用「删除」操作显式声明;误删请恢复。')
1129
+ }
1130
+
1131
+ /**
1132
+ * required-evidence 对账(advisory,不阻断 verify 完成)。
1133
+ *
1134
+ * execute 阶段 Task Review Gate 把 cannot_verify 任务的 requiredEvidence 写入
1135
+ * changes/<change>/verify-required-evidence.json(schema: {generatedAt, schemaVersion, items:[{task, verdict, evidence:string[]}]})。
1136
+ * 历史"死链"(sss1.md 矛盾2):只写不读——verify agent 不在 verify-result.md 体现也不会被发现,
1137
+ * 且 verify.js prompt 让 agent 读 `requiredEvidence` 键(字段名错配,实际是 items[].evidence),照做必落空。
1138
+ * 本探针闭合该链:读 evidence 文件,对每个 cannot_verify 任务检查 verify-result.md 是否提及该任务 id;
1139
+ * 未提及 → warning(advisory)。CLI 只做"任务被提及"的机械存在性检查,evidence 是否真正满足
1140
+ * (satisfied/missing/partial)由 agent 在 verify-result.md 诚实自报告——不假装语义判定(与删除探针同 altitude)。
1141
+ *
1142
+ * @param {{cwd:string, specBase:string, changeName?:string}} args
1143
+ * @returns {{status:'skipped'|'passed'|'warning', items:Array, unacknowledged:Array, summary:string, reason:string|null}}
1144
+ */
1145
+ export function runVerifyRequiredEvidenceCheck({ cwd, specBase, changeName = null }) {
1146
+ if (!changeName) {
1147
+ return { status: 'skipped', items: [], unacknowledged: [], summary: '', reason: '无 changeName(quick 等无关联变更场景),evidence 对账跳过' }
1148
+ }
1149
+ const evidencePath = join(specBase, 'changes', changeName, 'verify-required-evidence.json')
1150
+ if (!existsSync(evidencePath)) {
1151
+ return { status: 'skipped', items: [], unacknowledged: [], summary: '', reason: '无 verify-required-evidence.json(execute 无 cannot_verify 任务),evidence 对账跳过' }
1152
+ }
1153
+
1154
+ let data
1155
+ try {
1156
+ data = JSON.parse(readFileSync(evidencePath, 'utf8'))
1157
+ } catch (e) {
1158
+ return { status: 'skipped', items: [], unacknowledged: [], summary: '', reason: `verify-required-evidence.json 解析失败(${e.message}),evidence 对账跳过` }
1159
+ }
1160
+ const items = Array.isArray(data.items) ? data.items : []
1161
+
1162
+ // 读 verify-result.md(不存在则所有 evidence 任务都"未体现")
1163
+ const verifyResultPath = join(specBase, 'changes', changeName, 'verify-result.md')
1164
+ const report = existsSync(verifyResultPath) ? readFileSync(verifyResultPath, 'utf8') : ''
1165
+
1166
+ const unacknowledged = []
1167
+ for (const item of items) {
1168
+ const task = item && item.task
1169
+ if (!task) continue
1170
+ // 机械存在性检查:verify-result.md 是否提及该 cannot_verify 任务 id。
1171
+ // evidence 数组的具体满足度(satisfied/missing/partial)由 agent 自报告,CLI 不判定。
1172
+ if (!report.includes(task)) {
1173
+ const evidenceCount = Array.isArray(item.evidence) ? item.evidence.length : 0
1174
+ unacknowledged.push({ task, verdict: item.verdict || 'cannot_verify', evidenceCount,
1175
+ reason: `cannot_verify 任务 ${task} 未在 verify-result.md 中体现(需逐条 evidence 给结论 satisfied/missing/partial)` })
1176
+ }
1177
+ }
1178
+
1179
+ if (unacknowledged.length > 0) {
1180
+ return { status: 'warning', items, unacknowledged,
1181
+ summary: `${items.length} 个 cannot_verify evidence 任务中 ${unacknowledged.length} 个未在 verify-result.md 体现`, reason: null }
1182
+ }
1183
+ return { status: 'passed', items, unacknowledged: [],
1184
+ summary: `${items.length} 个 cannot_verify evidence 任务均在 verify-result.md 体现(满足度由 agent 自报告)`, reason: null }
1185
+ }
1186
+
1187
+ /** 打印 required-evidence 对账结果(advisory,不阻断 verify 完成) */
1188
+ export function printVerifyRequiredEvidenceCheck(result) {
1189
+ if (result.status === 'skipped') return // 静默:无 evidence 文件 / 无 changeName / 解析失败
1190
+ if (result.status === 'passed') {
1191
+ console.log(`\n✅ required-evidence 对账通过:${result.summary}`)
1192
+ return
1193
+ }
1194
+ // warning
1195
+ console.warn(`\n⚠️ required-evidence 对账发现 ${result.unacknowledged.length} 个 cannot_verify 任务未在 verify-result.md 体现(advisory 不阻断):`)
1196
+ for (const u of result.unacknowledged.slice(0, 20)) console.warn(` - ${u.task} (${u.reason})`)
1197
+ if (result.unacknowledged.length > 20) console.warn(` …还有 ${result.unacknowledged.length - 20} 个`)
1198
+ console.warn(' 提示:execute 标记的 cannot_verify 任务需在 verify-result.md 逐条给 evidence 结论(satisfied/missing/partial)。CLI 仅查任务被提及,是否真满足由你诚实判定。')
1199
+ }