sillyspec 3.20.2 → 3.20.4

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 (133) hide show
  1. package/.claude/skills/sillyspec-archive/SKILL.md +21 -21
  2. package/.claude/skills/sillyspec-auto/SKILL.md +83 -83
  3. package/.claude/skills/sillyspec-brainstorm/SKILL.md +44 -44
  4. package/.claude/skills/sillyspec-commit/SKILL.md +106 -106
  5. package/.claude/skills/sillyspec-continue/SKILL.md +45 -45
  6. package/.claude/skills/sillyspec-doctor/SKILL.md +31 -31
  7. package/.claude/skills/sillyspec-execute/SKILL.md +30 -30
  8. package/.claude/skills/sillyspec-explore/SKILL.md +109 -109
  9. package/.claude/skills/sillyspec-knowledge/SKILL.md +269 -269
  10. package/.claude/skills/sillyspec-plan/SKILL.md +21 -21
  11. package/.claude/skills/sillyspec-propose/SKILL.md +21 -21
  12. package/.claude/skills/sillyspec-quick/SKILL.md +21 -21
  13. package/.claude/skills/sillyspec-resume/SKILL.md +68 -68
  14. package/.claude/skills/sillyspec-scan/SKILL.md +21 -21
  15. package/.claude/skills/sillyspec-state/SKILL.md +54 -54
  16. package/.claude/skills/sillyspec-status/SKILL.md +21 -21
  17. package/.claude/skills/sillyspec-verify/SKILL.md +21 -21
  18. package/.claude/skills/sillyspec-workspace/SKILL.md +157 -157
  19. package/.husky/pre-push +13 -13
  20. package/CLAUDE.md +18 -18
  21. package/README.md +198 -188
  22. package/SKILL.md +90 -91
  23. package/bin/sillyspec.js +2 -2
  24. package/docs/brainstorm-plan-contract.md +64 -64
  25. package/docs/plan-execute-contract.md +123 -123
  26. package/docs/platform-scan-protocol.md +298 -298
  27. package/docs/revision-mode.md +115 -115
  28. package/docs/sillyspec/file-lifecycle/known-implementation-gaps.md +99 -99
  29. package/docs/sillyspec/file-lifecycle/platform-workflows-sync.md +218 -218
  30. package/docs/sillyspec/file-lifecycle/stage-artifacts.md +167 -167
  31. package/docs/sillyspec/file-lifecycle/storage-and-state.md +148 -148
  32. package/docs/sillyspec/file-lifecycle/worktree-and-guard.md +211 -193
  33. package/docs/sillyspec/file-lifecycle.md +125 -125
  34. package/docs/workflow-contract-regression.md +106 -106
  35. package/docs/worktree-isolation.md +252 -252
  36. package/package.json +40 -40
  37. package/packages/dashboard/dist/assets/index-Bq_Z2hne.js +7446 -7446
  38. package/packages/dashboard/dist/assets/index-O2W5RV4z.css +1 -1
  39. package/packages/dashboard/dist/index.html +16 -16
  40. package/packages/dashboard/index.html +15 -15
  41. package/packages/dashboard/package-lock.json +2384 -2384
  42. package/packages/dashboard/package.json +25 -25
  43. package/packages/dashboard/server/executor.js +86 -86
  44. package/packages/dashboard/server/index.js +588 -588
  45. package/packages/dashboard/server/parser.js +526 -526
  46. package/packages/dashboard/server/watcher.js +344 -344
  47. package/packages/dashboard/src/App.vue +558 -558
  48. package/packages/dashboard/src/components/ActionBar.vue +93 -93
  49. package/packages/dashboard/src/components/CommandPalette.vue +96 -96
  50. package/packages/dashboard/src/components/DetailPanel.vue +137 -137
  51. package/packages/dashboard/src/components/LogStream.vue +65 -65
  52. package/packages/dashboard/src/components/PipelineStage.vue +95 -95
  53. package/packages/dashboard/src/components/PipelineView.vue +156 -156
  54. package/packages/dashboard/src/components/ProjectList.vue +210 -210
  55. package/packages/dashboard/src/components/StageBadge.vue +67 -67
  56. package/packages/dashboard/src/components/StepCard.vue +94 -94
  57. package/packages/dashboard/src/components/detail/DocsDetail.vue +48 -48
  58. package/packages/dashboard/src/components/detail/GitDetail.vue +61 -61
  59. package/packages/dashboard/src/components/detail/TechDetail.vue +43 -43
  60. package/packages/dashboard/src/composables/useDashboard.js +170 -170
  61. package/packages/dashboard/src/composables/useKeyboard.js +119 -119
  62. package/packages/dashboard/src/composables/useWebSocket.js +129 -129
  63. package/packages/dashboard/src/main.js +8 -8
  64. package/packages/dashboard/src/style.css +132 -132
  65. package/packages/dashboard/vite.config.js +18 -18
  66. package/src/brainstorm-postcheck.js +158 -158
  67. package/src/change-list.js +52 -52
  68. package/src/change-risk-profile.js +352 -352
  69. package/src/classify-change.js +73 -73
  70. package/src/constants.js +70 -70
  71. package/src/contract-matrix.js +278 -278
  72. package/src/db.js +201 -201
  73. package/src/endpoint-extractor.js +315 -315
  74. package/src/hooks/claude-pre-tool-use.cjs +125 -125
  75. package/src/hooks/worktree-guard.js +653 -653
  76. package/src/index.js +922 -900
  77. package/src/init.js +431 -431
  78. package/src/knowledge-match.js +130 -130
  79. package/src/migrate.js +117 -117
  80. package/src/modules.js +482 -482
  81. package/src/progress.js +1734 -1734
  82. package/src/run.js +3465 -3358
  83. package/src/scan-postcheck.js +387 -383
  84. package/src/setup.js +398 -398
  85. package/src/stage-contract.js +700 -700
  86. package/src/stages/archive.js +160 -160
  87. package/src/stages/brainstorm-auto.js +229 -229
  88. package/src/stages/brainstorm.js +645 -645
  89. package/src/stages/doctor.js +365 -365
  90. package/src/stages/execute.js +625 -625
  91. package/src/stages/explore.js +34 -34
  92. package/src/stages/index.js +29 -29
  93. package/src/stages/knowledge.js +498 -498
  94. package/src/stages/plan-postcheck.js +511 -513
  95. package/src/stages/plan.js +582 -582
  96. package/src/stages/propose.js +174 -174
  97. package/src/stages/quick.js +82 -82
  98. package/src/stages/scan.js +558 -558
  99. package/src/stages/status.js +65 -65
  100. package/src/stages/verify.js +322 -322
  101. package/src/sync.js +497 -497
  102. package/src/task-review.js +346 -346
  103. package/src/workflow.js +785 -785
  104. package/src/worktree-apply.js +549 -549
  105. package/src/worktree-deps.js +185 -0
  106. package/src/worktree.js +982 -932
  107. package/templates/workflows/archive-impact.yaml +79 -79
  108. package/templates/workflows/scan-docs.yaml +132 -132
  109. package/test/brainstorm-plan-contract.test.mjs +273 -273
  110. package/test/check-syntax.mjs +26 -26
  111. package/test/contract-artifacts.test.mjs +323 -323
  112. package/test/decision-supersede.test.mjs +277 -277
  113. package/test/knowledge-match.test.mjs +231 -231
  114. package/test/plan-execute-contract.test.mjs +330 -330
  115. package/test/plan-optimization.test.mjs +572 -572
  116. package/test/platform-artifacts.test.mjs +166 -166
  117. package/test/platform-failure-samples.test.mjs +199 -199
  118. package/test/platform-recovery-chain.test.mjs +167 -167
  119. package/test/platform-recovery.test.mjs +136 -136
  120. package/test/platform-scan-p0.test.mjs +168 -168
  121. package/test/revision-v1.test.mjs +1145 -1145
  122. package/test/run-scan-project-parse.test.mjs +200 -200
  123. package/test/run-tests.mjs +48 -48
  124. package/test/scan-knowledge.test.mjs +175 -175
  125. package/test/scan-paths.test.mjs +68 -68
  126. package/test/scan-postcheck.test.mjs +197 -197
  127. package/test/spec-dir.test.mjs +206 -206
  128. package/test/stage-contract.test.mjs +299 -299
  129. package/test/stage-definitions.test.mjs +39 -39
  130. package/test/wait-gates.test.mjs +496 -496
  131. package/test/worktree-deps-provision.test.mjs +148 -0
  132. package/test/worktree-guard.test.mjs +71 -71
  133. package/test/worktree-native-overlay.test.mjs +188 -188
@@ -1,383 +1,387 @@
1
- /**
2
- * scan-postcheck.js — CLI 层 scan 完成后强制校验
3
- *
4
- * 不依赖 AI agent 的自检报告,由 CLI 代码直接检查文件系统。
5
- * 平台模式下必须通过所有 check 才能 success,否则降级。
6
- */
7
-
8
- import { existsSync, readdirSync, readFileSync, mkdirSync, writeFileSync } from 'fs'
9
- import { join, basename } from 'path'
10
- import { SCAN_STATUS, CHECK_SEVERITY } from './constants.js'
11
-
12
- const REQUIRED_SCAN_DOCS = [
13
- 'ARCHITECTURE.md',
14
- 'CONVENTIONS.md',
15
- 'STRUCTURE.md',
16
- 'INTEGRATIONS.md',
17
- 'TESTING.md',
18
- 'CONCERNS.md',
19
- 'PROJECT.md',
20
- ]
21
-
22
- /**
23
- * @param {object} opts
24
- * @param {string} opts.cwd - 源码项目根目录 (source_root)
25
- * @param {string} opts.specDir - 规范目录 (spec-root),null 时为非平台模式
26
- * @param {string} [opts.outputText] - 最后一步(自检)的 AI 输出文本
27
- * @param {object} [opts.scanMeta] - scan 元数据(由 runCommand 传入)
28
- * @param {boolean} [opts.scanMeta.projectListParsed] - Step 2 项目列表是否成功解析
29
- * @param {boolean} [opts.scanMeta.manifestWritten] - manifest.json 是否写入成功
30
- * @param {number} [opts.scanMeta.projectCount] - 实际展开的项目数量
31
- * @returns {{ status: 'success'|'completed_with_warnings'|'failed_post_check', checks: Array<{name, severity, detail}> }}
32
- */
33
- export function runScanPostCheck({ cwd, specDir, outputText = '', scanMeta = {} } ) {
34
- const isPlatform = !!specDir
35
- const checks = []
36
-
37
- if (!isPlatform) {
38
- // 非平台模式:只做轻量检查
39
- const localSpec = join(cwd, '.sillyspec')
40
- const scanDir = join(localSpec, 'docs', basename(cwd), 'scan')
41
-
42
- // 检查 7 份文档是否存在
43
- const missing = REQUIRED_SCAN_DOCS.filter(f => !existsSync(join(scanDir, f)))
44
- if (missing.length > 0) {
45
- checks.push({ name: 'missing_docs', severity: CHECK_SEVERITY.WARNING, detail: `缺少 ${missing.length} 份 scan 文档: ${missing.join(', ')}` })
46
- }
47
-
48
- const hasWarning = checks.some(c => c.severity === 'warning')
49
- return { status: hasWarning ? 'completed_with_warnings' : 'success', checks }
50
- }
51
-
52
- // ── 平台模式:严格检查 ──
53
-
54
- const projectName = basename(cwd)
55
-
56
- // 1. source_root 污染检查(docs/projects/workflows/knowledge/manifest/local)
57
- const pollutePaths = ['docs', 'projects', 'workflows', 'knowledge']
58
- const polluteFiles = ['manifest.json', 'local.yaml']
59
- for (const sub of pollutePaths) {
60
- const localSub = join(cwd, '.sillyspec', sub)
61
- if (existsSync(localSub)) {
62
- try {
63
- const leaked = readdirSync(localSub, { recursive: true }).filter(e => String(e).endsWith('.md') || String(e).endsWith('.yaml') || String(e).endsWith('.json'))
64
- if (leaked.length > 0) {
65
- checks.push({
66
- name: sub === 'docs' ? 'source_root_docs_leak' : 'source_root_leak',
67
- severity: CHECK_SEVERITY.FAILED,
68
- detail: `source_root/.sillyspec/${sub}/ 下存在 ${leaked.length} 个文件(${localSub}/),agent 写入到了错误路径`
69
- })
70
- }
71
- } catch {}
72
- }
73
- }
74
- for (const file of polluteFiles) {
75
- const filePath = join(cwd, '.sillyspec', file)
76
- if (existsSync(filePath)) {
77
- checks.push({
78
- name: 'source_root_leak',
79
- severity: CHECK_SEVERITY.FAILED,
80
- detail: `source_root/.sillyspec/${file} 存在,agent 写入到了错误路径(${filePath})`
81
- })
82
- }
83
- }
84
-
85
- // 2. spec_root 检查 7 份必需文档
86
- const specScanDir = join(specDir, 'docs', projectName, 'scan')
87
- const missingDocs = REQUIRED_SCAN_DOCS.filter(f => !existsSync(join(specScanDir, f)))
88
- if (missingDocs.length > 0) {
89
- checks.push({
90
- name: missingDocs.length === REQUIRED_SCAN_DOCS.length ? 'all_docs_missing' : 'partial_docs_missing',
91
- severity: CHECK_SEVERITY.FAILED,
92
- detail: missingDocs.length === REQUIRED_SCAN_DOCS.length
93
- ? `spec_root 下无任何 scan 文档(${specScanDir}/),扫描可能未执行`
94
- : `spec_root 缺少必需文档: ${missingDocs.join(', ')}(7 份 scan 文档均为 required)`
95
- })
96
- }
97
-
98
- // 3. 检查文档 header(author / created_at)— 只看文件头部,避免正文出现同名词被误判
99
- const existingDocs = REQUIRED_SCAN_DOCS.filter(f => existsSync(join(specScanDir, f)))
100
- const docsMissingHeader = []
101
- for (const doc of existingDocs) {
102
- const content = readFileSync(join(specScanDir, doc), 'utf8')
103
- const headerSlice = content.slice(0, 512)
104
- if (!/author\s*:/.test(headerSlice) || !/created_at\s*:/.test(headerSlice)) {
105
- docsMissingHeader.push(doc)
106
- }
107
- }
108
- if (docsMissingHeader.length > 0) {
109
- checks.push({
110
- name: 'docs_missing_header',
111
- severity: CHECK_SEVERITY.WARNING,
112
- detail: `${docsMissingHeader.length} 份文档缺少 author/created_at: ${docsMissingHeader.join(', ')}`
113
- })
114
- }
115
-
116
- // 4. local.yaml 校验
117
- const localYamlPath = join(specDir, 'local.yaml')
118
- if (existsSync(localYamlPath)) {
119
- const yamlContent = readFileSync(localYamlPath, 'utf8')
120
- const packageJsonPath = join(cwd, 'package.json')
121
- const invalidCommands = []
122
-
123
- // 简单提取 local.yaml 中的 commands
124
- const commandMatch = yamlContent.match(/build:\s*"([^"]+)"/) ||
125
- yamlContent.match(/test:\s*"([^"]+)"/) ||
126
- yamlContent.match(/lint:\s*"([^"]+)"/)
127
-
128
- if (commandMatch) {
129
- // 提取所有 npm run <script> 形式的命令
130
- const npmRunCommands = yamlContent.match(/npm run (\S+)/g) || []
131
- if (npmRunCommands.length > 0 && existsSync(packageJsonPath)) {
132
- try {
133
- const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf8'))
134
- const scripts = pkg.scripts || {}
135
- for (const cmd of npmRunCommands) {
136
- const scriptName = cmd.replace('npm run ', '')
137
- if (!scripts[scriptName]) {
138
- invalidCommands.push(`${cmd} (package.json ${scriptName} script)`)
139
- }
140
- }
141
- } catch {}
142
- }
143
- }
144
-
145
- if (invalidCommands.length > 0) {
146
- checks.push({
147
- name: 'local_config_invalid',
148
- severity: CHECK_SEVERITY.WARNING,
149
- detail: `local.yaml 引用不存在的命令: ${invalidCommands.join('; ')}`
150
- })
151
- }
152
- }
153
-
154
- // 5. 检查 AI 输出中的真实错误标记
155
- // 注意:不对 agent 描述性文本做全文正则匹配,防止误报。
156
- // 只检测明显是 agent 运行时失败的信号(未被捕获的错误块),
157
- // 而非 agent 正常描述中提到这些词。
158
- if (outputText) {
159
- // 5a: 检测未被恢复的 API 错误(连续多次、非描述性提及)
160
- const apiErrorCount = (outputText.match(/API Error\b.*?\b529\b/gi) || []).length
161
- if (apiErrorCount >= 2) {
162
- checks.push({ name: 'api_error_529', severity: CHECK_SEVERITY.WARNING, detail: 'AI 输出中包含多次 API Error 529' })
163
- }
164
- const rateLimitCount = (outputText.match(/rate.?limit.*?exhausted/gi) || []).length
165
- if (rateLimitCount >= 2) {
166
- checks.push({ name: 'rate_limit_exhausted', severity: CHECK_SEVERITY.WARNING, detail: 'AI 输出中包含多次 rate_limit exhausted' })
167
- }
168
- // tool_use_error fallback 已移除:agent 描述性文本中正常提及这些词
169
- // 不应触发 warning。真正的问题会通过文档缺失、manifest 失败等其他检查捕获。
170
- }
171
-
172
- // 6. manifest 写入状态检查
173
- if (scanMeta.manifestWritten === false) {
174
- checks.push({
175
- name: 'manifest_write_failed',
176
- severity: CHECK_SEVERITY.FAILED,
177
- detail: 'manifest.json 写入失败,平台无法消费 scan 结果'
178
- })
179
- }
180
-
181
- // 7. 项目列表解析状态检查
182
- if (scanMeta.projectListParsed === false) {
183
- checks.push({
184
- name: 'project_list_parse_failed',
185
- severity: CHECK_SEVERITY.WARNING,
186
- detail: 'Step 2 项目列表解析失败,回退到注册项目列表,可能遗漏子项目'
187
- })
188
- }
189
-
190
- // 7.5 knowledge 产物校验
191
- const knowledgeDir = join(specDir, 'knowledge')
192
- if (existsSync(knowledgeDir)) {
193
- const indexPath = join(knowledgeDir, 'INDEX.md')
194
- if (!existsSync(indexPath)) {
195
- checks.push({
196
- name: 'knowledge_index_missing',
197
- severity: CHECK_SEVERITY.WARNING,
198
- detail: `knowledge/INDEX.md 不存在`
199
- })
200
- } else {
201
- // 检查 INDEX.md 引用的文件是否真实存在
202
- const indexContent = readFileSync(indexPath, 'utf8')
203
- const referencedFiles = [...indexContent.matchAll(/\(([^)]+\.md)/g)].map(m => m[1])
204
- const missingRefs = referencedFiles.filter(f => !existsSync(join(knowledgeDir, f)))
205
- if (missingRefs.length > 0) {
206
- checks.push({
207
- name: 'knowledge_broken_refs',
208
- severity: CHECK_SEVERITY.WARNING,
209
- detail: `INDEX.md 引用了不存在的文件: ${missingRefs.join(', ')}`
210
- })
211
- }
212
- }
213
- } else {
214
- checks.push({
215
- name: 'knowledge_dir_missing',
216
- severity: CHECK_SEVERITY.WARNING,
217
- detail: `knowledge/ 目录不存在`
218
- })
219
- }
220
-
221
- // 8. 计算 finalStatus
222
- const hasFailed = checks.some(c => c.severity === CHECK_SEVERITY.FAILED)
223
- const hasWarning = checks.some(c => c.severity === CHECK_SEVERITY.WARNING)
224
-
225
- let status
226
- if (hasFailed) {
227
- status = SCAN_STATUS.FAILED_POST_CHECK
228
- } else if (hasWarning) {
229
- status = SCAN_STATUS.COMPLETED_WITH_WARNINGS
230
- } else {
231
- status = SCAN_STATUS.SUCCESS
232
- }
233
-
234
- return { status, checks }
235
- }
236
-
237
- /**
238
- * postcheck 结果转换为结构化 JSON(SillyHub 可消费格式)
239
- *
240
- * failure_category 标准化:
241
- * - warning : 非致命问题,不阻塞流程
242
- * - error : 文档缺失/内容不完整,需要修复
243
- * - critical : 安全问题(source_root 泄漏/路径污染)
244
- *
245
- * 结构化字段:
246
- * - violations : 明确违反约束的条目(source_root 泄漏等)
247
- * - missing_outputs : 预期文件不存在
248
- * - path_pollution : 产物写入了错误路径
249
- * - bad_references : 引用了不存在的命令/资源
250
- * - quality_warnings: AI 输出中包含错误标记等质量信号
251
- *
252
- * @param {object} result - runScanPostCheck 返回值
253
- * @param {object} [meta] - 附带元数据(workspace_id, scan_run_id, timestamp 等)
254
- * @returns {object} 结构化 JSON
255
- */
256
- export function formatStructuredResult(result, meta = {}) {
257
- const structured = {
258
- schema_version: 1,
259
- generated_at: new Date().toISOString(),
260
- overall_status: result.status,
261
- // 路径溯源(供平台消费)
262
- ...(meta.workspace_id ? { workspace_id: meta.workspace_id } : {}),
263
- ...(meta.scan_run_id ? { scan_run_id: meta.scan_run_id } : {}),
264
- ...(meta.source_root ? { source_root: meta.source_root } : {}),
265
- ...(meta.spec_root ? { spec_root: meta.spec_root } : {}),
266
- ...(meta.runtime_root ? { runtime_root: meta.runtime_root } : {}),
267
- summary: {
268
- total_checks: result.checks.length,
269
- critical: 0,
270
- error: 0,
271
- warning: 0,
272
- },
273
- failure_categories: {
274
- violations: [],
275
- missing_outputs: [],
276
- path_pollution: [],
277
- bad_references: [],
278
- quality_warnings: [],
279
- },
280
- checks: result.checks.map(c => ({
281
- name: c.name,
282
- severity: c.severity === 'failed' ? 'critical' : c.severity,
283
- detail: c.detail,
284
- })),
285
- }
286
-
287
- // 分类到 failure_categories
288
- for (const check of result.checks) {
289
- const severity = check.severity === 'failed' ? 'critical' : check.severity
290
- const entry = { name: check.name, detail: check.detail, severity }
291
-
292
- // 路径污染类
293
- if (check.name === 'source_root_leak' || check.name === 'source_root_docs_leak') {
294
- structured.failure_categories.path_pollution.push(entry)
295
- structured.failure_categories.violations.push(entry)
296
- }
297
- // 文档缺失类
298
- else if (check.name === 'all_docs_missing' || check.name === 'partial_docs_missing' || check.name === 'missing_docs') {
299
- structured.failure_categories.missing_outputs.push(entry)
300
- }
301
- // 引用无效类
302
- else if (check.name === 'local_config_invalid') {
303
- structured.failure_categories.bad_references.push(entry)
304
- }
305
- // AI 输出质量类
306
- else if (['api_error_529', 'rate_limit_exhausted'].includes(check.name)) {
307
- structured.failure_categories.quality_warnings.push(entry)
308
- }
309
- // manifest/project 列表问题
310
- else if (check.name === 'manifest_write_failed' || check.name === 'project_list_parse_failed') {
311
- structured.failure_categories.violations.push(entry)
312
- }
313
- // 文档缺少 header
314
- else if (check.name === 'docs_missing_header') {
315
- structured.failure_categories.quality_warnings.push(entry)
316
- }
317
- // 兜底:归入 violations
318
- else {
319
- structured.failure_categories.violations.push(entry)
320
- }
321
- }
322
-
323
- // 汇总计数
324
- for (const check of result.checks) {
325
- if (check.severity === 'failed') structured.summary.critical++
326
- else structured.summary.warning++
327
- }
328
-
329
- return structured
330
- }
331
-
332
- /**
333
- * 将结构化结果写入 JSON 文件(平台模式供 SillyHub 消费)
334
- *
335
- * 本地模式:写入 specDir/.runtime/postcheck-result.json
336
- * 平台模式:写入 runtimeRoot/scan-runs/{scan_run_id}/postcheck-result.json
337
- *
338
- * @param {object} structured - formatStructuredResult 返回值
339
- * @param {string} specDir - 规范目录(本地模式使用)
340
- * @param {object} [opts] - 平台模式选项
341
- * @param {string} [opts.runtimeRoot] - 平台模式运行时根目录
342
- * @param {string} [opts.scanRunId] - scan run ID
343
- * @returns {string|null} 写入的文件路径,失败时返回 null
344
- */
345
- export function writeStructuredResult(structured, specDir, opts = {}) {
346
- if (!specDir && !opts.runtimeRoot) return null
347
- try {
348
- let outPath
349
- if (opts.runtimeRoot && opts.scanRunId) {
350
- const scanRunDir = join(opts.runtimeRoot, 'scan-runs', opts.scanRunId)
351
- mkdirSync(scanRunDir, { recursive: true })
352
- outPath = join(scanRunDir, 'postcheck-result.json')
353
- } else if (specDir) {
354
- const runtimeDir = join(specDir, '.runtime')
355
- mkdirSync(runtimeDir, { recursive: true })
356
- outPath = join(runtimeDir, 'postcheck-result.json')
357
- } else {
358
- return null
359
- }
360
-
361
- writeFileSync(outPath, JSON.stringify(structured, null, 2) + '\n')
362
- return outPath
363
- } catch (e) {
364
- console.warn(` ⚠️ postcheck-result.json 写入失败: ${e.message}`)
365
- return null
366
- }
367
- }
368
-
369
- /**
370
- * 打印 post-check 结果到 stdout
371
- */
372
- export function printScanPostCheckResult(result) {
373
- if (result.checks.length === 0) {
374
- console.log(' ✅ CLI post-check: 全部通过')
375
- return
376
- }
377
-
378
- for (const check of result.checks) {
379
- const icon = check.severity === 'failed' ? '❌' : '⚠️'
380
- console.log(` ${icon} CLI post-check [${check.name}]: ${check.detail}`)
381
- }
382
- console.log(` 📋 最终状态: ${result.status}`)
383
- }
1
+ /**
2
+ * scan-postcheck.js — CLI 层 scan 完成后强制校验
3
+ *
4
+ * 不依赖 AI agent 的自检报告,由 CLI 代码直接检查文件系统。
5
+ * 平台模式下必须通过所有 check 才能 success,否则降级。
6
+ */
7
+
8
+ import { existsSync, readdirSync, readFileSync, mkdirSync, writeFileSync } from 'fs'
9
+ import { join, basename } from 'path'
10
+ import { SCAN_STATUS, CHECK_SEVERITY } from './constants.js'
11
+
12
+ const REQUIRED_SCAN_DOCS = [
13
+ 'ARCHITECTURE.md',
14
+ 'CONVENTIONS.md',
15
+ 'STRUCTURE.md',
16
+ 'INTEGRATIONS.md',
17
+ 'TESTING.md',
18
+ 'CONCERNS.md',
19
+ 'PROJECT.md',
20
+ ]
21
+
22
+ /**
23
+ * @param {object} opts
24
+ * @param {string} opts.cwd - 源码项目根目录 (source_root)
25
+ * @param {string} opts.specDir - 规范目录 (spec-root),null 时为非平台模式
26
+ * @param {string} [opts.outputText] - 最后一步(自检)的 AI 输出文本
27
+ * @param {object} [opts.scanMeta] - scan 元数据(由 runCommand 传入)
28
+ * @param {boolean} [opts.scanMeta.projectListParsed] - Step 2 项目列表是否成功解析
29
+ * @param {boolean} [opts.scanMeta.manifestWritten] - manifest.json 是否写入成功
30
+ * @param {number} [opts.scanMeta.projectCount] - 实际展开的项目数量
31
+ * @returns {{ status: 'success'|'completed_with_warnings'|'failed_post_check', checks: Array<{name, severity, detail}> }}
32
+ */
33
+ export function runScanPostCheck({ cwd, specDir, outputText = '', scanMeta = {} } ) {
34
+ const isPlatform = !!specDir
35
+ const checks = []
36
+
37
+ if (!isPlatform) {
38
+ // 非平台模式:只做轻量检查
39
+ const localSpec = join(cwd, '.sillyspec')
40
+ const scanDir = join(localSpec, 'docs', basename(cwd), 'scan')
41
+
42
+ // 检查 7 份文档是否存在
43
+ const missing = REQUIRED_SCAN_DOCS.filter(f => !existsSync(join(scanDir, f)))
44
+ if (missing.length > 0) {
45
+ checks.push({ name: 'missing_docs', severity: CHECK_SEVERITY.WARNING, detail: `缺少 ${missing.length} 份 scan 文档: ${missing.join(', ')}` })
46
+ }
47
+
48
+ const hasWarning = checks.some(c => c.severity === 'warning')
49
+ return { status: hasWarning ? 'completed_with_warnings' : 'success', checks }
50
+ }
51
+
52
+ // ── 平台模式:严格检查 ──
53
+
54
+ const projectName = basename(cwd)
55
+
56
+ // 1. source_root 污染检查(docs/projects/workflows/knowledge/manifest/local)
57
+ const pollutePaths = ['docs', 'projects', 'workflows', 'knowledge']
58
+ const polluteFiles = ['manifest.json', 'local.yaml']
59
+ for (const sub of pollutePaths) {
60
+ const localSub = join(cwd, '.sillyspec', sub)
61
+ if (existsSync(localSub)) {
62
+ try {
63
+ const leaked = readdirSync(localSub, { recursive: true }).filter(e => String(e).endsWith('.md') || String(e).endsWith('.yaml') || String(e).endsWith('.json'))
64
+ if (leaked.length > 0) {
65
+ checks.push({
66
+ name: sub === 'docs' ? 'source_root_docs_leak' : 'source_root_leak',
67
+ severity: CHECK_SEVERITY.FAILED,
68
+ detail: `source_root/.sillyspec/${sub}/ 下存在 ${leaked.length} 个文件(${localSub}/),agent 写入到了错误路径`
69
+ })
70
+ }
71
+ } catch {}
72
+ }
73
+ }
74
+ for (const file of polluteFiles) {
75
+ const filePath = join(cwd, '.sillyspec', file)
76
+ if (existsSync(filePath)) {
77
+ checks.push({
78
+ name: 'source_root_leak',
79
+ severity: CHECK_SEVERITY.FAILED,
80
+ detail: `source_root/.sillyspec/${file} 存在,agent 写入到了错误路径(${filePath})`
81
+ })
82
+ }
83
+ }
84
+
85
+ // 2. spec_root 检查 7 份必需文档
86
+ const specScanDir = join(specDir, 'docs', projectName, 'scan')
87
+ const missingDocs = REQUIRED_SCAN_DOCS.filter(f => !existsSync(join(specScanDir, f)))
88
+ if (missingDocs.length > 0) {
89
+ checks.push({
90
+ name: missingDocs.length === REQUIRED_SCAN_DOCS.length ? 'all_docs_missing' : 'partial_docs_missing',
91
+ severity: CHECK_SEVERITY.FAILED,
92
+ detail: missingDocs.length === REQUIRED_SCAN_DOCS.length
93
+ ? `spec_root 下无任何 scan 文档(${specScanDir}/),扫描可能未执行`
94
+ : `spec_root 缺少必需文档: ${missingDocs.join(', ')}(7 份 scan 文档均为 required)`
95
+ })
96
+ }
97
+
98
+ // 3. 检查文档 header(author / created_at)— 只看文件头部,避免正文出现同名词被误判
99
+ const existingDocs = REQUIRED_SCAN_DOCS.filter(f => existsSync(join(specScanDir, f)))
100
+ const docsMissingHeader = []
101
+ for (const doc of existingDocs) {
102
+ const content = readFileSync(join(specScanDir, doc), 'utf8')
103
+ const headerSlice = content.slice(0, 512)
104
+ if (!/author\s*:/.test(headerSlice) || !/created_at\s*:/.test(headerSlice)) {
105
+ docsMissingHeader.push(doc)
106
+ }
107
+ }
108
+ if (docsMissingHeader.length > 0) {
109
+ checks.push({
110
+ name: 'docs_missing_header',
111
+ severity: CHECK_SEVERITY.WARNING,
112
+ detail: `${docsMissingHeader.length} 份文档缺少 author/created_at: ${docsMissingHeader.join(', ')}`
113
+ })
114
+ }
115
+
116
+ // 4. local.yaml 校验
117
+ const localYamlPath = join(specDir, 'local.yaml')
118
+ if (existsSync(localYamlPath)) {
119
+ const yamlContent = readFileSync(localYamlPath, 'utf8')
120
+ const packageJsonPath = join(cwd, 'package.json')
121
+ const invalidCommands = []
122
+
123
+ // 简单提取 local.yaml 中的 commands
124
+ // 注意(X-3, change 2026-06-28-worktree-deps-provision):仅校验 build/test/lint 这类
125
+ // `npm run <script>` 形式命令在 package.json scripts 中存在。install/typecheck 是直接
126
+ // 包管理器调用(pnpm install / npm ci / npx tsc),不是 npm script,不在此校验范围——
127
+ // 下方的 /npm run (\S+)/g 正则天然不会匹配它们,无需也不应对其做 scripts 校验。
128
+ const commandMatch = yamlContent.match(/build:\s*"([^"]+)"/) ||
129
+ yamlContent.match(/test:\s*"([^"]+)"/) ||
130
+ yamlContent.match(/lint:\s*"([^"]+)"/)
131
+
132
+ if (commandMatch) {
133
+ // 提取所有 npm run <script> 形式的命令
134
+ const npmRunCommands = yamlContent.match(/npm run (\S+)/g) || []
135
+ if (npmRunCommands.length > 0 && existsSync(packageJsonPath)) {
136
+ try {
137
+ const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf8'))
138
+ const scripts = pkg.scripts || {}
139
+ for (const cmd of npmRunCommands) {
140
+ const scriptName = cmd.replace('npm run ', '')
141
+ if (!scripts[scriptName]) {
142
+ invalidCommands.push(`${cmd} (package.json 无 ${scriptName} script)`)
143
+ }
144
+ }
145
+ } catch {}
146
+ }
147
+ }
148
+
149
+ if (invalidCommands.length > 0) {
150
+ checks.push({
151
+ name: 'local_config_invalid',
152
+ severity: CHECK_SEVERITY.WARNING,
153
+ detail: `local.yaml 引用不存在的命令: ${invalidCommands.join('; ')}`
154
+ })
155
+ }
156
+ }
157
+
158
+ // 5. 检查 AI 输出中的真实错误标记
159
+ // 注意:不对 agent 描述性文本做全文正则匹配,防止误报。
160
+ // 只检测明显是 agent 运行时失败的信号(未被捕获的错误块),
161
+ // 而非 agent 正常描述中提到这些词。
162
+ if (outputText) {
163
+ // 5a: 检测未被恢复的 API 错误(连续多次、非描述性提及)
164
+ const apiErrorCount = (outputText.match(/API Error\b.*?\b529\b/gi) || []).length
165
+ if (apiErrorCount >= 2) {
166
+ checks.push({ name: 'api_error_529', severity: CHECK_SEVERITY.WARNING, detail: 'AI 输出中包含多次 API Error 529' })
167
+ }
168
+ const rateLimitCount = (outputText.match(/rate.?limit.*?exhausted/gi) || []).length
169
+ if (rateLimitCount >= 2) {
170
+ checks.push({ name: 'rate_limit_exhausted', severity: CHECK_SEVERITY.WARNING, detail: 'AI 输出中包含多次 rate_limit exhausted' })
171
+ }
172
+ // tool_use_error fallback 已移除:agent 描述性文本中正常提及这些词
173
+ // 不应触发 warning。真正的问题会通过文档缺失、manifest 失败等其他检查捕获。
174
+ }
175
+
176
+ // 6. manifest 写入状态检查
177
+ if (scanMeta.manifestWritten === false) {
178
+ checks.push({
179
+ name: 'manifest_write_failed',
180
+ severity: CHECK_SEVERITY.FAILED,
181
+ detail: 'manifest.json 写入失败,平台无法消费 scan 结果'
182
+ })
183
+ }
184
+
185
+ // 7. 项目列表解析状态检查
186
+ if (scanMeta.projectListParsed === false) {
187
+ checks.push({
188
+ name: 'project_list_parse_failed',
189
+ severity: CHECK_SEVERITY.WARNING,
190
+ detail: 'Step 2 项目列表解析失败,回退到注册项目列表,可能遗漏子项目'
191
+ })
192
+ }
193
+
194
+ // 7.5 knowledge 产物校验
195
+ const knowledgeDir = join(specDir, 'knowledge')
196
+ if (existsSync(knowledgeDir)) {
197
+ const indexPath = join(knowledgeDir, 'INDEX.md')
198
+ if (!existsSync(indexPath)) {
199
+ checks.push({
200
+ name: 'knowledge_index_missing',
201
+ severity: CHECK_SEVERITY.WARNING,
202
+ detail: `knowledge/INDEX.md 不存在`
203
+ })
204
+ } else {
205
+ // 检查 INDEX.md 引用的文件是否真实存在
206
+ const indexContent = readFileSync(indexPath, 'utf8')
207
+ const referencedFiles = [...indexContent.matchAll(/\(([^)]+\.md)/g)].map(m => m[1])
208
+ const missingRefs = referencedFiles.filter(f => !existsSync(join(knowledgeDir, f)))
209
+ if (missingRefs.length > 0) {
210
+ checks.push({
211
+ name: 'knowledge_broken_refs',
212
+ severity: CHECK_SEVERITY.WARNING,
213
+ detail: `INDEX.md 引用了不存在的文件: ${missingRefs.join(', ')}`
214
+ })
215
+ }
216
+ }
217
+ } else {
218
+ checks.push({
219
+ name: 'knowledge_dir_missing',
220
+ severity: CHECK_SEVERITY.WARNING,
221
+ detail: `knowledge/ 目录不存在`
222
+ })
223
+ }
224
+
225
+ // 8. 计算 finalStatus
226
+ const hasFailed = checks.some(c => c.severity === CHECK_SEVERITY.FAILED)
227
+ const hasWarning = checks.some(c => c.severity === CHECK_SEVERITY.WARNING)
228
+
229
+ let status
230
+ if (hasFailed) {
231
+ status = SCAN_STATUS.FAILED_POST_CHECK
232
+ } else if (hasWarning) {
233
+ status = SCAN_STATUS.COMPLETED_WITH_WARNINGS
234
+ } else {
235
+ status = SCAN_STATUS.SUCCESS
236
+ }
237
+
238
+ return { status, checks }
239
+ }
240
+
241
+ /**
242
+ * postcheck 结果转换为结构化 JSON(SillyHub 可消费格式)
243
+ *
244
+ * failure_category 标准化:
245
+ * - warning : 非致命问题,不阻塞流程
246
+ * - error : 文档缺失/内容不完整,需要修复
247
+ * - critical : 安全问题(source_root 泄漏/路径污染)
248
+ *
249
+ * 结构化字段:
250
+ * - violations : 明确违反约束的条目(source_root 泄漏等)
251
+ * - missing_outputs : 预期文件不存在
252
+ * - path_pollution : 产物写入了错误路径
253
+ * - bad_references : 引用了不存在的命令/资源
254
+ * - quality_warnings: AI 输出中包含错误标记等质量信号
255
+ *
256
+ * @param {object} result - runScanPostCheck 返回值
257
+ * @param {object} [meta] - 附带元数据(workspace_id, scan_run_id, timestamp 等)
258
+ * @returns {object} 结构化 JSON
259
+ */
260
+ export function formatStructuredResult(result, meta = {}) {
261
+ const structured = {
262
+ schema_version: 1,
263
+ generated_at: new Date().toISOString(),
264
+ overall_status: result.status,
265
+ // 路径溯源(供平台消费)
266
+ ...(meta.workspace_id ? { workspace_id: meta.workspace_id } : {}),
267
+ ...(meta.scan_run_id ? { scan_run_id: meta.scan_run_id } : {}),
268
+ ...(meta.source_root ? { source_root: meta.source_root } : {}),
269
+ ...(meta.spec_root ? { spec_root: meta.spec_root } : {}),
270
+ ...(meta.runtime_root ? { runtime_root: meta.runtime_root } : {}),
271
+ summary: {
272
+ total_checks: result.checks.length,
273
+ critical: 0,
274
+ error: 0,
275
+ warning: 0,
276
+ },
277
+ failure_categories: {
278
+ violations: [],
279
+ missing_outputs: [],
280
+ path_pollution: [],
281
+ bad_references: [],
282
+ quality_warnings: [],
283
+ },
284
+ checks: result.checks.map(c => ({
285
+ name: c.name,
286
+ severity: c.severity === 'failed' ? 'critical' : c.severity,
287
+ detail: c.detail,
288
+ })),
289
+ }
290
+
291
+ // 分类到 failure_categories
292
+ for (const check of result.checks) {
293
+ const severity = check.severity === 'failed' ? 'critical' : check.severity
294
+ const entry = { name: check.name, detail: check.detail, severity }
295
+
296
+ // 路径污染类
297
+ if (check.name === 'source_root_leak' || check.name === 'source_root_docs_leak') {
298
+ structured.failure_categories.path_pollution.push(entry)
299
+ structured.failure_categories.violations.push(entry)
300
+ }
301
+ // 文档缺失类
302
+ else if (check.name === 'all_docs_missing' || check.name === 'partial_docs_missing' || check.name === 'missing_docs') {
303
+ structured.failure_categories.missing_outputs.push(entry)
304
+ }
305
+ // 引用无效类
306
+ else if (check.name === 'local_config_invalid') {
307
+ structured.failure_categories.bad_references.push(entry)
308
+ }
309
+ // AI 输出质量类
310
+ else if (['api_error_529', 'rate_limit_exhausted'].includes(check.name)) {
311
+ structured.failure_categories.quality_warnings.push(entry)
312
+ }
313
+ // manifest/project 列表问题
314
+ else if (check.name === 'manifest_write_failed' || check.name === 'project_list_parse_failed') {
315
+ structured.failure_categories.violations.push(entry)
316
+ }
317
+ // 文档缺少 header
318
+ else if (check.name === 'docs_missing_header') {
319
+ structured.failure_categories.quality_warnings.push(entry)
320
+ }
321
+ // 兜底:归入 violations
322
+ else {
323
+ structured.failure_categories.violations.push(entry)
324
+ }
325
+ }
326
+
327
+ // 汇总计数
328
+ for (const check of result.checks) {
329
+ if (check.severity === 'failed') structured.summary.critical++
330
+ else structured.summary.warning++
331
+ }
332
+
333
+ return structured
334
+ }
335
+
336
+ /**
337
+ * 将结构化结果写入 JSON 文件(平台模式供 SillyHub 消费)
338
+ *
339
+ * 本地模式:写入 specDir/.runtime/postcheck-result.json
340
+ * 平台模式:写入 runtimeRoot/scan-runs/{scan_run_id}/postcheck-result.json
341
+ *
342
+ * @param {object} structured - formatStructuredResult 返回值
343
+ * @param {string} specDir - 规范目录(本地模式使用)
344
+ * @param {object} [opts] - 平台模式选项
345
+ * @param {string} [opts.runtimeRoot] - 平台模式运行时根目录
346
+ * @param {string} [opts.scanRunId] - scan run ID
347
+ * @returns {string|null} 写入的文件路径,失败时返回 null
348
+ */
349
+ export function writeStructuredResult(structured, specDir, opts = {}) {
350
+ if (!specDir && !opts.runtimeRoot) return null
351
+ try {
352
+ let outPath
353
+ if (opts.runtimeRoot && opts.scanRunId) {
354
+ const scanRunDir = join(opts.runtimeRoot, 'scan-runs', opts.scanRunId)
355
+ mkdirSync(scanRunDir, { recursive: true })
356
+ outPath = join(scanRunDir, 'postcheck-result.json')
357
+ } else if (specDir) {
358
+ const runtimeDir = join(specDir, '.runtime')
359
+ mkdirSync(runtimeDir, { recursive: true })
360
+ outPath = join(runtimeDir, 'postcheck-result.json')
361
+ } else {
362
+ return null
363
+ }
364
+
365
+ writeFileSync(outPath, JSON.stringify(structured, null, 2) + '\n')
366
+ return outPath
367
+ } catch (e) {
368
+ console.warn(` ⚠️ postcheck-result.json 写入失败: ${e.message}`)
369
+ return null
370
+ }
371
+ }
372
+
373
+ /**
374
+ * 打印 post-check 结果到 stdout
375
+ */
376
+ export function printScanPostCheckResult(result) {
377
+ if (result.checks.length === 0) {
378
+ console.log(' CLI post-check: 全部通过')
379
+ return
380
+ }
381
+
382
+ for (const check of result.checks) {
383
+ const icon = check.severity === 'failed' ? '❌' : '⚠️'
384
+ console.log(` ${icon} CLI post-check [${check.name}]: ${check.detail}`)
385
+ }
386
+ console.log(` 📋 最终状态: ${result.status}`)
387
+ }