sillyspec 3.20.3 → 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 (224) hide show
  1. package/.claude/skills/sillyspec-archive/SKILL.md +21 -17
  2. package/.claude/skills/sillyspec-auto/SKILL.md +83 -77
  3. package/.claude/skills/sillyspec-brainstorm/SKILL.md +44 -17
  4. package/.claude/skills/sillyspec-commit/SKILL.md +106 -105
  5. package/.claude/skills/sillyspec-continue/SKILL.md +45 -44
  6. package/.claude/skills/sillyspec-doctor/SKILL.md +31 -22
  7. package/.claude/skills/sillyspec-execute/SKILL.md +30 -17
  8. package/.claude/skills/sillyspec-explore/SKILL.md +109 -96
  9. package/.claude/skills/sillyspec-knowledge/SKILL.md +270 -0
  10. package/.claude/skills/sillyspec-plan/SKILL.md +21 -52
  11. package/.claude/skills/sillyspec-propose/SKILL.md +21 -17
  12. package/.claude/skills/sillyspec-quick/SKILL.md +21 -17
  13. package/.claude/skills/sillyspec-resume/SKILL.md +68 -111
  14. package/.claude/skills/sillyspec-scan/SKILL.md +21 -17
  15. package/.claude/skills/sillyspec-state/SKILL.md +54 -54
  16. package/.claude/skills/sillyspec-status/SKILL.md +21 -17
  17. package/.claude/skills/sillyspec-verify/SKILL.md +21 -17
  18. package/.claude/skills/sillyspec-workspace/SKILL.md +157 -149
  19. package/.husky/pre-push +13 -0
  20. package/CLAUDE.md +18 -0
  21. package/README.md +198 -186
  22. package/SKILL.md +90 -87
  23. package/bin/sillyspec.js +2 -2
  24. package/docs/brainstorm-plan-contract.md +64 -0
  25. package/docs/plan-execute-contract.md +123 -0
  26. package/docs/platform-scan-protocol.md +298 -0
  27. package/docs/revision-mode.md +115 -0
  28. package/docs/sillyspec/file-lifecycle/known-implementation-gaps.md +99 -0
  29. package/docs/sillyspec/file-lifecycle/platform-workflows-sync.md +218 -0
  30. package/docs/sillyspec/file-lifecycle/stage-artifacts.md +167 -0
  31. package/docs/sillyspec/file-lifecycle/storage-and-state.md +148 -0
  32. package/docs/sillyspec/file-lifecycle/worktree-and-guard.md +211 -0
  33. package/docs/sillyspec/file-lifecycle.md +125 -0
  34. package/docs/workflow-contract-regression.md +106 -0
  35. package/docs/worktree-isolation.md +252 -0
  36. package/package.json +40 -34
  37. package/packages/dashboard/dist/assets/{index-D1EVTLmc.js → index-Bq_Z2hne.js} +7446 -7446
  38. package/packages/dashboard/dist/assets/index-O2W5RV4z.css +1 -0
  39. package/packages/dashboard/dist/index.html +16 -16
  40. package/packages/dashboard/dist/prototype-dashboard.html +836 -0
  41. package/packages/dashboard/dist/prototype-overview.html +256 -0
  42. package/packages/dashboard/index.html +15 -15
  43. package/packages/dashboard/package-lock.json +2384 -2384
  44. package/packages/dashboard/package.json +25 -25
  45. package/packages/dashboard/public/prototype-dashboard.html +836 -0
  46. package/packages/dashboard/public/prototype-overview.html +256 -0
  47. package/packages/dashboard/server/executor.js +86 -86
  48. package/packages/dashboard/server/index.js +588 -508
  49. package/packages/dashboard/server/parser.js +526 -458
  50. package/packages/dashboard/server/watcher.js +350 -342
  51. package/packages/dashboard/src/App.vue +558 -325
  52. package/packages/dashboard/src/components/ActionBar.vue +93 -84
  53. package/packages/dashboard/src/components/CommandPalette.vue +96 -92
  54. package/packages/dashboard/src/components/DetailPanel.vue +137 -137
  55. package/packages/dashboard/src/components/DocPreview.vue +105 -8
  56. package/packages/dashboard/src/components/DocTree.vue +75 -19
  57. package/packages/dashboard/src/components/HResizeHandle.vue +48 -0
  58. package/packages/dashboard/src/components/LogStream.vue +65 -65
  59. package/packages/dashboard/src/components/PipelineStage.vue +95 -75
  60. package/packages/dashboard/src/components/PipelineView.vue +156 -129
  61. package/packages/dashboard/src/components/ProjectCard.vue +187 -0
  62. package/packages/dashboard/src/components/ProjectList.vue +210 -210
  63. package/packages/dashboard/src/components/ProjectOverview.vue +113 -139
  64. package/packages/dashboard/src/components/StageBadge.vue +67 -53
  65. package/packages/dashboard/src/components/StepCard.vue +94 -89
  66. package/packages/dashboard/src/components/VResizeHandle.vue +61 -0
  67. package/packages/dashboard/src/components/detail/DocsDetail.vue +48 -48
  68. package/packages/dashboard/src/components/detail/GitDetail.vue +61 -61
  69. package/packages/dashboard/src/components/detail/TechDetail.vue +43 -43
  70. package/packages/dashboard/src/composables/useDashboard.js +192 -164
  71. package/packages/dashboard/src/composables/useKeyboard.js +119 -119
  72. package/packages/dashboard/src/composables/useLayout.js +131 -0
  73. package/packages/dashboard/src/composables/useWebSocket.js +129 -129
  74. package/packages/dashboard/src/main.js +8 -8
  75. package/packages/dashboard/src/style.css +132 -132
  76. package/packages/dashboard/vite.config.js +18 -18
  77. package/src/brainstorm-postcheck.js +158 -0
  78. package/src/change-list.js +52 -0
  79. package/src/change-risk-profile.js +352 -0
  80. package/src/classify-change.js +73 -0
  81. package/src/constants.js +70 -0
  82. package/src/contract-matrix.js +278 -0
  83. package/src/db.js +201 -0
  84. package/src/endpoint-extractor.js +315 -0
  85. package/src/hooks/claude-pre-tool-use.cjs +125 -0
  86. package/src/hooks/worktree-guard.js +761 -0
  87. package/src/index.js +922 -252
  88. package/src/init.js +431 -375
  89. package/src/knowledge-match.js +130 -0
  90. package/src/migrate.js +117 -117
  91. package/src/modules.js +482 -0
  92. package/src/progress.js +1734 -508
  93. package/src/run.js +3465 -652
  94. package/src/scan-postcheck.js +387 -0
  95. package/src/setup.js +398 -460
  96. package/src/stage-contract.js +700 -0
  97. package/src/stages/archive.js +160 -54
  98. package/src/stages/brainstorm-auto.js +229 -0
  99. package/src/stages/brainstorm.js +645 -239
  100. package/src/stages/doctor.js +365 -312
  101. package/src/stages/execute.js +625 -264
  102. package/src/stages/explore.js +34 -0
  103. package/src/stages/index.js +29 -35
  104. package/src/stages/knowledge.js +498 -0
  105. package/src/stages/plan-postcheck.js +511 -0
  106. package/src/stages/plan.js +582 -279
  107. package/src/stages/propose.js +174 -115
  108. package/src/stages/quick.js +102 -63
  109. package/src/stages/scan.js +558 -141
  110. package/src/stages/status.js +65 -65
  111. package/src/stages/verify.js +322 -135
  112. package/src/sync.js +497 -0
  113. package/src/task-review.js +346 -0
  114. package/src/workflow.js +785 -0
  115. package/src/worktree-apply.js +549 -0
  116. package/src/worktree-deps.js +185 -0
  117. package/src/worktree.js +982 -0
  118. package/templates/workflows/archive-impact.yaml +79 -0
  119. package/templates/workflows/scan-docs.yaml +132 -0
  120. package/test/brainstorm-plan-contract.test.mjs +273 -0
  121. package/test/check-syntax.mjs +26 -0
  122. package/test/cli-top-level-aliases.test.mjs +174 -0
  123. package/test/contract-artifacts.test.mjs +323 -0
  124. package/test/decision-supersede.test.mjs +277 -0
  125. package/test/knowledge-match.test.mjs +231 -0
  126. package/test/plan-execute-contract.test.mjs +330 -0
  127. package/test/plan-optimization.test.mjs +572 -0
  128. package/test/platform-artifacts.test.mjs +190 -0
  129. package/test/platform-failure-samples.test.mjs +199 -0
  130. package/test/platform-recovery-chain.test.mjs +179 -0
  131. package/test/platform-recovery.test.mjs +167 -0
  132. package/test/platform-scan-p0.test.mjs +175 -0
  133. package/test/revision-v1.test.mjs +1145 -0
  134. package/test/run-sanitize-project-name.test.mjs +51 -0
  135. package/test/run-scan-postcheck-fail.test.mjs +64 -0
  136. package/test/run-scan-project-parse.test.mjs +200 -0
  137. package/test/run-tests.mjs +48 -0
  138. package/test/scan-docs-yaml-placeholders.test.mjs +84 -0
  139. package/test/scan-knowledge.test.mjs +175 -0
  140. package/test/scan-paths.test.mjs +68 -0
  141. package/test/scan-postcheck-project-priority.test.mjs +85 -0
  142. package/test/scan-postcheck.test.mjs +197 -0
  143. package/test/scan-workflow-anyfailed-block.test.mjs +52 -0
  144. package/test/spec-dir.test.mjs +206 -0
  145. package/test/stage-contract-failed-post-check.test.mjs +102 -0
  146. package/test/stage-contract.test.mjs +299 -0
  147. package/test/stage-definitions.test.mjs +39 -0
  148. package/test/wait-gates.test.mjs +501 -0
  149. package/test/workflow-spec-base.test.mjs +142 -0
  150. package/test/worktree-deps-provision.test.mjs +148 -0
  151. package/test/worktree-guard.test.mjs +136 -0
  152. package/test/worktree-native-overlay.test.mjs +188 -0
  153. package/.sillyspec/changes/archive/2026-04-08-derive-state/design.md +0 -97
  154. package/.sillyspec/changes/archive/2026-04-08-derive-state/plan.md +0 -51
  155. package/.sillyspec/changes/archive/2026-04-08-derive-state/proposal.md +0 -29
  156. package/.sillyspec/changes/archive/2026-04-08-derive-state/requirements.md +0 -34
  157. package/.sillyspec/changes/archive/2026-04-08-derive-state/tasks.md +0 -13
  158. package/.sillyspec/changes/archive/2026-04-08-derive-state/verify-result.md +0 -43
  159. package/.sillyspec/changes/auto-mode/design.md +0 -50
  160. package/.sillyspec/changes/auto-mode/proposal.md +0 -19
  161. package/.sillyspec/changes/auto-mode/requirements.md +0 -21
  162. package/.sillyspec/changes/auto-mode/tasks.md +0 -7
  163. package/.sillyspec/changes/brainstorm-archive/2026-04-05-dashboard-design.md +0 -206
  164. package/.sillyspec/changes/brainstorm-archive/2026-04-05-unified-docs-design.md +0 -199
  165. package/.sillyspec/changes/dashboard/design.md +0 -219
  166. package/.sillyspec/changes/dashboard/design.md.braindraft +0 -206
  167. package/.sillyspec/changes/run-command-design/design.md +0 -1230
  168. package/.sillyspec/changes/unified-docs-design/design.md +0 -199
  169. package/.sillyspec/docs/sillyspec/scan/.gitkeep +0 -0
  170. package/.sillyspec/knowledge/INDEX.md +0 -8
  171. package/.sillyspec/knowledge/uncategorized.md +0 -3
  172. package/.sillyspec/plans/2026-04-05-dashboard.md +0 -737
  173. package/.sillyspec/projects/sillyspec.yaml +0 -3
  174. package/dist/steps/brainstorm/01-load-context.md +0 -30
  175. package/dist/steps/brainstorm/02-reuse-check.md +0 -6
  176. package/dist/steps/brainstorm/03-prototype-analysis.md +0 -11
  177. package/dist/steps/brainstorm/04-module-split.md +0 -23
  178. package/dist/steps/brainstorm/05-dialog-explore.md +0 -8
  179. package/dist/steps/brainstorm/06-propose-approaches.md +0 -3
  180. package/dist/steps/brainstorm/07-present-design.md +0 -3
  181. package/dist/steps/brainstorm/08-write-design.md +0 -21
  182. package/dist/steps/brainstorm/09-self-review.md +0 -15
  183. package/dist/steps/brainstorm/10-user-confirm.md +0 -3
  184. package/dist/steps/brainstorm/11-output-spec.md +0 -7
  185. package/dist/steps/brainstorm/manifest.yaml +0 -26
  186. package/dist/steps/execute/01-load-context.md +0 -41
  187. package/dist/steps/execute/02-scan-conventions.md +0 -47
  188. package/dist/steps/execute/03-skill-mcp.md +0 -19
  189. package/dist/steps/execute/04-assign-task.md +0 -22
  190. package/dist/steps/execute/04b-prompt-template.md +0 -54
  191. package/dist/steps/execute/05-write-test.md +0 -7
  192. package/dist/steps/execute/06-write-code.md +0 -8
  193. package/dist/steps/execute/07-run-test.md +0 -26
  194. package/dist/steps/execute/08-fix-issues.md +0 -28
  195. package/dist/steps/execute/09-next-task.md +0 -33
  196. package/dist/steps/execute/manifest.yaml +0 -28
  197. package/dist/steps/plan/01-load-context.md +0 -22
  198. package/dist/steps/plan/02-anchor-confirm.md +0 -1
  199. package/dist/steps/plan/03-expand-tasks.md +0 -33
  200. package/dist/steps/plan/04-mark-order.md +0 -15
  201. package/dist/steps/plan/05-e2e-planning.md +0 -17
  202. package/dist/steps/plan/06-self-check.md +0 -16
  203. package/dist/steps/plan/07-save.md +0 -1
  204. package/dist/steps/plan/manifest.yaml +0 -18
  205. package/dist/steps/scan/01-env-detect.md +0 -51
  206. package/dist/steps/scan/02-tech-stack.md +0 -16
  207. package/dist/steps/scan/03-conventions.md +0 -16
  208. package/dist/steps/scan/04-structure.md +0 -19
  209. package/dist/steps/scan/05-quality.md +0 -18
  210. package/dist/steps/scan/06-complete.md +0 -49
  211. package/dist/steps/scan/manifest.yaml +0 -16
  212. package/dist/steps/verify/01-load-specs.md +0 -28
  213. package/dist/steps/verify/02-check-tasks.md +0 -1
  214. package/dist/steps/verify/03-check-design.md +0 -6
  215. package/dist/steps/verify/04-run-tests.md +0 -7
  216. package/dist/steps/verify/05-e2e-tests.md +0 -27
  217. package/dist/steps/verify/05b-e2e-fix.md +0 -33
  218. package/dist/steps/verify/06-code-quality.md +0 -25
  219. package/dist/steps/verify/07-lint-check.md +0 -27
  220. package/dist/steps/verify/08-output-report.md +0 -14
  221. package/dist/steps/verify/manifest.yaml +0 -22
  222. package/packages/dashboard/dist/assets/index-DGe8CqeP.css +0 -1
  223. package/src/derive.js +0 -147
  224. package/src/step.js +0 -543
package/src/run.js CHANGED
@@ -1,652 +1,3465 @@
1
- /**
2
- * sillyspec run 命令实现
3
- *
4
- * CLI 成为流程引擎,AI 变成步骤执行器。
5
- */
6
- import { basename, join } from 'path'
7
- import { existsSync, readdirSync, mkdirSync, writeFileSync, appendFileSync, readFileSync, statSync } from 'fs'
8
- import { ProgressManager } from './progress.js'
9
- import { stageRegistry, getNextStage, auxiliaryStages } from './stages/index.js'
10
- import { buildExecuteSteps } from './stages/execute.js'
11
- import { buildPlanSteps } from './stages/plan.js'
12
-
13
- /**
14
- * 获取阶段的步骤定义(execute 需要动态构建)
15
- */
16
- async function getStageSteps(stageName, cwd, progress) {
17
- if (stageName === 'execute') {
18
- const changesDir = join(cwd, '.sillyspec', 'changes')
19
- let planFile = null
20
- // 优先用 currentChange 指定的变更名
21
- if (progress.currentChange) {
22
- const target = join(changesDir, progress.currentChange, 'plan.md')
23
- if (existsSync(target)) planFile = target
24
- }
25
- // fallback:扫描 changes/ 非 archive 目录下的 plan.md
26
- if (!planFile && existsSync(changesDir)) {
27
- const candidates = []
28
- for (const entry of readdirSync(changesDir, { withFileTypes: true })) {
29
- if (!entry.isDirectory() || entry.name === 'archive') continue
30
- const p = join(changesDir, entry.name, 'plan.md')
31
- if (existsSync(p)) candidates.push({ name: entry.name, path: p })
32
- }
33
- if (candidates.length === 1) {
34
- planFile = candidates[0].path
35
- } else if (candidates.length > 1) {
36
- console.log('⚠️ 检测到多个变更,请选择:')
37
- candidates.forEach((c, i) => console.log(` ${i + 1}. ${c.name}`))
38
- const readline = await import('readline')
39
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
40
- const answer = await new Promise(resolve => {
41
- rl.question(`\n请输入编号(默认 1):`, input => {
42
- rl.close()
43
- const num = parseInt(input) || 1
44
- resolve(num >= 1 && num <= candidates.length ? num - 1 : 0)
45
- })
46
- })
47
- planFile = candidates[answer].path
48
- console.log(`✅ 已选择:${candidates[answer].name}\n`)
49
- }
50
- }
51
- return buildExecuteSteps(planFile)
52
- }
53
- if (stageName === 'plan') {
54
- const changesDir = join(cwd, '.sillyspec', 'changes')
55
- let changeDir = null
56
- if (progress.currentChange) {
57
- const target = join(changesDir, progress.currentChange)
58
- if (existsSync(target)) changeDir = target
59
- }
60
- if (!changeDir && existsSync(changesDir)) {
61
- const entries = readdirSync(changesDir, { withFileTypes: true }).filter(e => e.isDirectory() && e.name !== 'archive')
62
- if (entries.length === 1) changeDir = join(changesDir, entries[0].name)
63
- }
64
- return buildPlanSteps(changeDir)
65
- }
66
- const def = stageRegistry[stageName]
67
- return def ? def.steps : null
68
- }
69
-
70
- /**
71
- * 确保阶段的 steps 已初始化到 progress.json
72
- */
73
- async function ensureStageSteps(progress, stageName, cwd) {
74
- if (!progress.stages) progress.stages = {}
75
-
76
- const steps = await getStageSteps(stageName, cwd, progress)
77
- if (!steps) return false
78
-
79
- if (!progress.stages[stageName] || !progress.stages[stageName].steps || progress.stages[stageName].steps.length === 0) {
80
- progress.stages[stageName] = {
81
- status: 'in-progress',
82
- startedAt: new Date().toLocaleString('zh-CN',{hour12:false}),
83
- completedAt: null,
84
- steps: steps.map(s => ({ name: s.name, status: 'pending' }))
85
- }
86
- return true // 需要写入
87
- }
88
-
89
- // 检查步骤数量是否匹配(execute 动态步骤可能变化)
90
- if (progress.stages[stageName].steps.length !== steps.length) {
91
- // 保留已完成的状态,重新构建步骤列表
92
- const oldSteps = progress.stages[stageName].steps
93
- progress.stages[stageName].steps = steps.map((s, i) => {
94
- const old = oldSteps[i]
95
- if (old && old.name === s.name) return old
96
- return { name: s.name, status: 'pending' }
97
- })
98
- return true
99
- }
100
-
101
- return false
102
- }
103
-
104
- /**
105
- * 输出当前步骤的 prompt
106
- */
107
- function outputStep(stageName, stepIndex, steps, cwd) {
108
- const step = steps[stepIndex]
109
- const total = steps.length
110
- const projectName = basename(cwd)
111
-
112
- const personas = {
113
- brainstorm: `### 🎯 你的角色:资深架构师
114
- 你是一位有 15 年经验的系统架构师。先理解业务本质,再设计技术方案。决策附理由,方案列 trade-off。不确定就说不确定,不猜。`,
115
- plan: `### 📋 你的角色:技术项目经理
116
- 你是一位经验丰富的技术项目经理。任务拆解粒度均匀,依赖关系明确。每个任务有完成标准,Wave 间有依赖说明。条理清晰,不做模糊描述。`,
117
- execute: `### 💻 你的角色:高级工程师
118
- 你是一位严谨的高级工程师。先读规范再写代码,严格遵循 CONVENTIONS.md 和 plan.md。**你不是设计师,是执行者——按 plan 搬砖,禁止发散思维。** 发现 plan 不合理就停下来反馈,不要自己改方案。代码有清晰职责划分,边界处理完善。少说多做,遇到规范冲突优先问。`,
119
- verify: `### 🔍 你的角色:QA 专家
120
- 你是一位吹毛求疵的 QA 专家。假设所有代码都有 bug,用最坏情况测试。关注边界、异常、并发。有问题直说,用证据说话,不写"看起来没问题"。`,
121
- quick: `### 💻 你的角色:全栈老兵
122
- 你是一位实战经验丰富的全栈工程师。不纠结架构和流程,理解需求就直接干。不确定的地方先问清楚再动手,先读后写,改完就收。问题排查思路开阔,前端报错不一定是前端问题——可能是后端数据、浏览器兼容、甚至设备硬件。解决方案实用接地气,用户描述有误敢于直接指出。`
123
- }
124
-
125
- console.log(`---`)
126
- console.log(`stage: ${stageName}`)
127
- console.log(`step: ${stepIndex + 1}/${total}`)
128
- console.log(`stepName: ${step.name}`)
129
- console.log(`project: ${projectName}`)
130
- console.log(`---\n`)
131
- if (personas[stageName]) {
132
- console.log(personas[stageName])
133
- console.log('')
134
- }
135
- console.log(`## Step ${stepIndex + 1}/${total}: ${step.name}\n`)
136
- console.log(step.prompt)
137
- console.log(`\n### ⚠️ 铁律`)
138
- console.log('- **文档是核心资产,代码是文档的产物。** 没有文档就没有代码——文档是 AI 的记忆,是团队协作的基础,是后续维护的唯一依据。任何代码产出必须先有对应的设计/规范文档支撑。')
139
- console.log('- 只做本步骤描述的操作,不得自行扩展或跳过')
140
- console.log('- 不要回头修改已完成的步骤')
141
- console.log('- 不要编造不存在的 CLI 子命令')
142
- console.log('- 完成后立即执行 --done 命令,不得跳过')
143
- console.log('- 文档类型文件(.md/.yaml/.json 等)头部必须包含 author(git 用户名)和 created_at(精确到秒)')
144
- console.log('- 执行构建/测试前必须先读 local.yaml,优先使用其中配置的命令、路径和环境变量;未配置时才使用默认值')
145
- console.log(`\n### 完成后执行`)
146
- console.log(`sillyspec run ${stageName} --done --input "用户原始需求/反馈" --output "你的摘要"`)
147
- }
148
-
149
- /**
150
- * sillyspec run <stage> 主命令
151
- */
152
- export async function runCommand(args, cwd) {
153
- // 解析参数
154
- const stageName = args[0]
155
- const flags = args.slice(1)
156
-
157
- if (!stageName) {
158
- console.error('❌ 请指定阶段,例如: sillyspec run brainstorm')
159
- console.error(`可选: ${Object.keys(stageRegistry).join(', ')}, auto`)
160
- process.exit(1)
161
- }
162
-
163
- if (!stageRegistry[stageName] && stageName !== 'auto') {
164
- console.error(`❌ 未知阶段: ${stageName}`)
165
- console.error(`可选: ${Object.keys(stageRegistry).join(', ')}, auto`)
166
- process.exit(1)
167
- }
168
-
169
- const isDone = flags.includes('--done')
170
- const isSkip = flags.includes('--skip')
171
- const isStatus = flags.includes('--status')
172
- const isReset = flags.includes('--reset')
173
-
174
- // 解析 --output
175
- let outputText = null
176
- const outputIdx = flags.indexOf('--output')
177
- if (outputIdx !== -1 && flags[outputIdx + 1]) {
178
- outputText = flags[outputIdx + 1]
179
- }
180
-
181
- // 解析 --input
182
- let inputText = null
183
- const inputIdx = flags.indexOf('--input')
184
- if (inputIdx !== -1 && flags[inputIdx + 1]) {
185
- inputText = flags[inputIdx + 1]
186
- }
187
-
188
- // 解析 --change <name>
189
- let changeName = null
190
- const changeIdx = flags.indexOf('--change')
191
- if (changeIdx !== -1 && flags[changeIdx + 1]) {
192
- changeName = flags[changeIdx + 1]
193
- }
194
-
195
- const isAuxiliary = auxiliaryStages.includes(stageName)
196
-
197
- const pm = new ProgressManager()
198
- let progress = pm.read(cwd)
199
-
200
- if (!progress) {
201
- // 辅助命令可以在没有 progress.json 时工作(比如 scan)
202
- if (!isAuxiliary) {
203
- console.error('❌ 未找到 progress.json,请先运行 sillyspec init')
204
- process.exit(1)
205
- }
206
- progress = pm.init(cwd)
207
- }
208
-
209
- // -- auto 模式:自动推进所有流程阶段
210
- if (stageName === 'auto') {
211
- return await runAutoMode(pm, progress, cwd, flags)
212
- }
213
-
214
- // --change 设置当前变更名
215
- if (changeName) {
216
- progress.currentChange = changeName
217
- progress.lastActive = new Date().toLocaleString('zh-CN', { hour12: false })
218
- pm._write(cwd, progress)
219
- console.log(`✅ 当前变更设置为:${changeName}`)
220
- return
221
- }
222
-
223
- // --reset
224
- if (isReset) {
225
- return await resetStage(pm, progress, stageName, cwd)
226
- }
227
-
228
- // 确保步骤已初始化
229
- const changed = await ensureStageSteps(progress, stageName, cwd)
230
- if (changed) {
231
- pm._write(cwd, progress)
232
- progress = pm.read(cwd)
233
- }
234
-
235
- // --status
236
- if (isStatus) {
237
- return showStatus(progress, stageName)
238
- }
239
-
240
- // --skip
241
- if (isSkip) {
242
- return await skipStep(pm, progress, stageName, cwd)
243
- }
244
-
245
- // --done
246
- if (isDone) {
247
- return await completeStep(pm, progress, stageName, cwd, outputText, inputText)
248
- }
249
-
250
- // 默认:输出当前步骤
251
- return await runStage(pm, progress, stageName, cwd)
252
- }
253
-
254
- async function runStage(pm, progress, stageName, cwd) {
255
- const stageData = progress.stages[stageName]
256
- if (!stageData || !stageData.steps) {
257
- console.error(`❌ 阶段 ${stageName} 未初始化`)
258
- process.exit(1)
259
- }
260
-
261
- const steps = stageData.steps
262
- let currentIdx = steps.findIndex(s => s.status !== 'completed' && s.status !== 'skipped')
263
-
264
- if (currentIdx === -1) {
265
- // 阶段已完成
266
- console.log(`✅ ${stageName} 阶段已完成。`)
267
- console.log(` 继续执行将重新开始,可用 --reset 显式重置。\n`)
268
- // 自动重置,允许重复执行
269
- steps.forEach(s => { s.status = 'pending'; s.completedAt = null; s.output = null; s.startedAt = null })
270
- stageData.status = 'in_progress'
271
- stageData.completedAt = null
272
- pm._write(cwd, progress)
273
- currentIdx = 0
274
- } else if (currentIdx > 0) {
275
- // 有进行中的步骤,提示用户
276
- const completed = currentIdx
277
- const total = steps.length
278
- console.log(`⚠️ ${stageName} 已进行到第 ${currentIdx + 1}/${total} 步(前 ${completed} 步已完成)。`)
279
- console.log(` 继续执行将从中断处恢复,用 --reset 可重新开始。\n`)
280
- }
281
-
282
- const stageDef = stageRegistry[stageName]
283
- const defSteps = await getStageSteps(stageName, cwd, progress)
284
- if (defSteps && defSteps[currentIdx]) {
285
- outputStep(stageName, currentIdx, defSteps, cwd)
286
- }
287
- }
288
-
289
- function validateMetadata(cwd, stageName) {
290
- const changesDir = join(cwd, '.sillyspec', 'changes')
291
- if (!existsSync(changesDir)) return
292
-
293
- // 找最近 10 分钟内修改的 md/yaml 文件
294
- const cutoff = Date.now() - 10 * 60 * 1000
295
- const missing = []
296
-
297
- function walk(dir) {
298
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
299
- const full = join(dir, entry.name)
300
- try {
301
- if (entry.isDirectory()) { walk(full); continue }
302
- if (!/\.(md|yaml|yml)$/.test(entry.name)) continue
303
- const mtime = statSync(full).mtimeMs
304
- if (mtime < cutoff) continue
305
- const content = readFileSync(full, 'utf-8')
306
- if (!content.includes('author:') && !content.includes('author:')) missing.push(full)
307
- if (!content.includes('created_at:') && !content.includes('created_at:')) missing.push(full)
308
- } catch (e) { /* skip unreadable files */ }
309
- }
310
- }
311
-
312
- walk(changesDir)
313
- const unique = [...new Set(missing)]
314
- if (unique.length > 0) {
315
- console.log(`\n⚠️ 以下文件缺少 author created_at 元数据:`)
316
- unique.forEach(f => console.log(` - ${f.replace(cwd + '/', '')}`))
317
- console.log('请在文件头部添加 author(git 用户名)和 created_at(精确到秒)')
318
- }
319
- }
320
-
321
- async function completeStep(pm, progress, stageName, cwd, outputText, inputText = null) {
322
- const stageData = progress.stages[stageName]
323
- if (!stageData || !stageData.steps) {
324
- console.error(`❌ 阶段 ${stageName} 未初始化`)
325
- process.exit(1)
326
- }
327
-
328
- const steps = stageData.steps
329
- let currentIdx = steps.findIndex(s => s.status === 'pending')
330
-
331
- if (currentIdx === -1) {
332
- console.error('没有待完成的步骤')
333
- process.exit(1)
334
- }
335
-
336
- // plan 阶段 Step 4(展开任务)完成后,动态追加 task 蓝图步骤
337
- // 先处理动态插入,再标记完成,避免 currentIdx 失效
338
- if (stageName === 'plan' && currentIdx === 3 && progress.currentChange) {
339
- const planFile = join(cwd, '.sillyspec', 'changes', progress.currentChange, 'plan.md')
340
- if (existsSync(planFile)) {
341
- const planContent = readFileSync(planFile, 'utf8')
342
- const { buildPlanSteps } = await import('./stages/plan.js')
343
- const fullSteps = buildPlanSteps(join(cwd, '.sillyspec', 'changes', progress.currentChange), planContent)
344
- const taskSteps = fullSteps.slice(5, -2)
345
- if (taskSteps.length > 0) {
346
- const suffixSteps = fullSteps.slice(-2)
347
- for (const ts of taskSteps) {
348
- steps.push({ name: ts.name, status: 'pending', prompt: ts.prompt, outputHint: ts.outputHint, optional: false })
349
- }
350
- for (const ss of suffixSteps) {
351
- steps.push({ name: ss.name, status: 'pending', prompt: ss.prompt, outputHint: ss.outputHint, optional: false })
352
- }
353
- }
354
- }
355
- }
356
-
357
- // 标记完成(在动态插入之后,currentIdx 仍然指向正确的 pending 步骤)
358
- steps[currentIdx].status = 'completed'
359
- steps[currentIdx].completedAt = new Date().toLocaleString('zh-CN',{hour12:false})
360
- if (outputText) {
361
- const MAX_OUTPUT = 200
362
- if (outputText.length > MAX_OUTPUT) {
363
- steps[currentIdx].output = outputText.slice(0, MAX_OUTPUT) + '…'
364
- // Save full output to artifacts/
365
- const artifactsDir = join(cwd, '.sillyspec', '.runtime', 'artifacts')
366
- mkdirSync(artifactsDir, { recursive: true })
367
- const ts = new Date().toISOString().slice(0,19).replace(/[-T:]/g, '')
368
- writeFileSync(join(artifactsDir, `${stageName}-step${currentIdx + 1}-${ts}.txt`), outputText)
369
- } else {
370
- steps[currentIdx].output = outputText
371
- }
372
- }
373
-
374
- // 检查是否还有下一步
375
- const nextPendingIdx = steps.findIndex(s => s.status === 'pending')
376
-
377
- if (nextPendingIdx === -1) {
378
- // 全部完成
379
- stageData.status = 'completed'
380
- stageData.completedAt = new Date().toLocaleString('zh-CN',{hour12:false})
381
-
382
- const next = getNextStage(stageName)
383
- if (next) {
384
- progress.currentStage = next
385
- if (!progress.stages[next]) progress.stages[next] = { status: 'pending', steps: [], startedAt: null, completedAt: null }
386
- if (progress.stages[next].status === 'pending' || !progress.stages[next].status) {
387
- progress.stages[next].status = 'in-progress'
388
- progress.stages[next].startedAt = new Date().toLocaleString('zh-CN',{hour12:false})
389
- }
390
- }
391
-
392
- progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
393
- pm._write(cwd, progress)
394
-
395
- // deriveState 轻量校验
396
- try {
397
- const { deriveState } = await import('./derive.js')
398
- const result = deriveState(cwd, { mode: 'light', fix: true, pm, progress })
399
- if (result.fixed > 0) {
400
- console.log(`⚠️ 状态修复:${result.fixed} 个步骤已从 artifacts 恢复`)
401
- }
402
- } catch {}
403
-
404
- // Append to user-inputs.md
405
- if (outputText) {
406
- const inputsPath = join(cwd, '.sillyspec', '.runtime', 'user-inputs.md')
407
- const entry = `\n## ${new Date().toLocaleString('zh-CN',{hour12:false})} | ${stageName}: ${steps[currentIdx].name}\n${inputText ? "- 输入:" + inputText + "\n" : ""}- 输出:${outputText}\n`
408
- appendFileSync(inputsPath, entry)
409
- }
410
-
411
- // 验证:检查生成的文件是否包含 author 和 created_at
412
- validateMetadata(cwd, stageName)
413
-
414
- const total = steps.length
415
- console.log(`✅ ${stageName} 阶段已完成(${total}/${total} 步)`)
416
- if (next) {
417
- console.log(`\n下一步:sillyspec run ${next}`)
418
- console.log(`或:/sillyspec:${next}`)
419
- }
420
- return
421
- }
422
-
423
- progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
424
- pm._write(cwd, progress)
425
-
426
- // Append to user-inputs.md
427
- if (outputText) {
428
- const inputsPath = join(cwd, '.sillyspec', '.runtime', 'user-inputs.md')
429
- const entry = `\n## ${new Date().toLocaleString('zh-CN',{hour12:false})} | ${stageName}: ${steps[currentIdx].name}\n${inputText ? "- 输入:" + inputText + "\n" : ""}- 输出:${outputText}\n`
430
- appendFileSync(inputsPath, entry)
431
- }
432
-
433
- const defSteps = await getStageSteps(stageName, cwd, progress)
434
- console.log(`✅ Step ${currentIdx + 1}/${steps.length} 完成:${steps[currentIdx].name}\n`)
435
- outputStep(stageName, nextPendingIdx, defSteps, cwd)
436
- }
437
-
438
- async function skipStep(pm, progress, stageName, cwd) {
439
- const stageData = progress.stages[stageName]
440
- if (!stageData || !stageData.steps) {
441
- console.error(`❌ 阶段 ${stageName} 未初始化`)
442
- process.exit(1)
443
- }
444
-
445
- const steps = stageData.steps
446
- const currentIdx = steps.findIndex(s => s.status === 'pending')
447
-
448
- if (currentIdx === -1) {
449
- console.error('没有待跳过的步骤')
450
- process.exit(1)
451
- }
452
-
453
- const defSteps = await getStageSteps(stageName, cwd, progress)
454
- const stepDef = defSteps ? defSteps[currentIdx] : null
455
- if (stepDef && !stepDef.optional) {
456
- console.error(`❌ 步骤 "${steps[currentIdx].name}" 不可跳过`)
457
- process.exit(1)
458
- }
459
-
460
- steps[currentIdx].status = 'skipped'
461
- steps[currentIdx].skippedAt = new Date().toLocaleString('zh-CN',{hour12:false})
462
- progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
463
- pm._write(cwd, progress)
464
-
465
- console.log(`⏭️ Step ${currentIdx + 1}/${steps.length} 已跳过:${steps[currentIdx].name}`)
466
-
467
- // 输出下一步
468
- const nextPendingIdx = steps.findIndex(s => s.status === 'pending')
469
- if (nextPendingIdx !== -1 && defSteps) {
470
- console.log('')
471
- outputStep(stageName, nextPendingIdx, defSteps, cwd)
472
- }
473
- }
474
-
475
- function showStatus(progress, stageName) {
476
- const stageData = progress.stages[stageName]
477
- const stageDef = stageRegistry[stageName]
478
-
479
- if (!stageData || !stageData.steps || stageData.steps.length === 0) {
480
- console.log(`阶段:${stageName}(${stageDef.title})`)
481
- console.log(`进度:未初始化`)
482
- return
483
- }
484
-
485
- const steps = stageData.steps
486
- const completed = steps.filter(s => s.status === 'completed' || s.status === 'skipped').length
487
- const bar = '█'.repeat(completed) + '░'.repeat(steps.length - completed)
488
-
489
- console.log(`阶段:${stageName}(${stageDef.title})`)
490
- console.log(`进度:[${bar}] ${completed}/${steps.length}\n`)
491
-
492
- const firstPending = steps.findIndex(s => s.status === 'pending')
493
-
494
- // 批量进度
495
- if (progress.batchProgress) {
496
- const bp = progress.batchProgress
497
- const bpTotal = bp.total || 0
498
- const bpCompleted = bp.completed || 0
499
- const bpFailed = bp.failed || 0
500
- const bpSkipped = bp.skipped || 0
501
- const bpBarLen = 20
502
- const bpFilled = Math.round((bpCompleted / Math.max(bpTotal, 1)) * bpBarLen)
503
- const bpBar = '█'.repeat(bpFilled) + '░'.repeat(bpBarLen - bpFilled)
504
- const bpParts = []
505
- if (bpFailed > 0) bpParts.push(`${bpFailed} 失败`)
506
- if (bpSkipped > 0) bpParts.push(`${bpSkipped} 跳过`)
507
- const bpSuffix = bpParts.length ? ` (${bpParts.join(', ')})` : ''
508
- console.log(`\n📊 批量进度: ${bpBar} ${bpCompleted}/${bpTotal}${bpSuffix}\n`)
509
- }
510
-
511
- steps.forEach((step, i) => {
512
- const icon = step.status === 'completed' ? '✅' : step.status === 'skipped' ? '⏭️' : '⬜'
513
- const isCurrent = step.status === 'pending' && i === firstPending
514
- console.log(`${icon} Step ${i + 1}: ${step.name}${isCurrent ? ' ← 当前' : ''}`)
515
- })
516
- }
517
-
518
- async function resetStage(pm, progress, stageName, cwd) {
519
- const defSteps = await getStageSteps(stageName, cwd, progress)
520
- progress.stages[stageName] = {
521
- status: 'in-progress',
522
- startedAt: new Date().toLocaleString('zh-CN',{hour12:false}),
523
- completedAt: null,
524
- steps: defSteps ? defSteps.map(s => ({ name: s.name, status: 'pending' })) : []
525
- }
526
- progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
527
- pm._write(cwd, progress)
528
- console.log(`🔄 ${stageName} 阶段已重置`)
529
- }
530
-
531
- /**
532
- * auto 模式:自动推进 brainstorm plan → execute → verify
533
- */
534
- async function runAutoMode(pm, progress, cwd, flags) {
535
- const flowStages = ['brainstorm', 'plan', 'execute', 'verify']
536
- const isDone = flags.includes('--done')
537
- let outputText = null
538
- const outputIdx = flags.indexOf('--output')
539
- if (outputIdx !== -1 && flags[outputIdx + 1]) outputText = flags[outputIdx + 1]
540
- let inputText = null
541
- const inputIdx = flags.indexOf('--input')
542
- if (inputIdx !== -1 && flags[inputIdx + 1]) inputText = flags[inputIdx + 1]
543
-
544
- if (!isDone) {
545
- // 首次启动:显示当前状态和下一步
546
- const currentStage = progress.currentStage || flowStages[0]
547
- let effectiveStage = currentStage
548
- const stageIdx = flowStages.indexOf(currentStage)
549
- if (stageIdx === -1) {
550
- // 当前阶段不在 auto 流程中(如 scan/quick/archive),自动跳到第一个未完成的流程阶段
551
- effectiveStage = flowStages.find(s => {
552
- const sd = progress.stages[s]
553
- return !sd || sd.status !== 'completed'
554
- }) || flowStages[0]
555
- progress.currentStage = effectiveStage
556
- pm._write(cwd, progress)
557
- console.log(`ℹ️ 当前阶段 ${currentStage} 不在 auto 流程中,自动切换到 ${effectiveStage}`)
558
- }
559
- // 显示进度概览
560
- console.log('════════════════════════════════════════')
561
- console.log(' 🤖 SillySpec Auto Mode')
562
- console.log('════════════════════════════════════════')
563
- console.log(` 流程: ${flowStages.join(' → ')}`)
564
- console.log(` 当前: ${currentStage}`)
565
- for (let i = 0; i < flowStages.length; i++) {
566
- const s = flowStages[i]
567
- const stageData = progress.stages[s]
568
- const done = stageData?.status === 'completed'
569
- const active = s === currentStage
570
- const total = stageData?.steps?.length || '?'
571
- const completed = stageData?.steps?.filter(st => st.status === 'completed').length || 0
572
- const icon = done ? '✅' : active ? '🔵' : '⬜'
573
- console.log(` ${icon} ${s} (${completed}/${total})`)
574
- }
575
- console.log('')
576
- // 输出当前步骤 prompt
577
- const steps = await getStageSteps(currentStage, cwd, progress)
578
- if (!steps) {
579
- console.error(`❌ 无法获取 ${currentStage} 步骤`)
580
- process.exit(1)
581
- }
582
- const pendingIdx = steps.findIndex(s => s.status === 'pending')
583
- if (pendingIdx === -1) {
584
- // 阶段已完成,提示进入下一阶段
585
- const next = getNextStage(currentStage)
586
- if (next) {
587
- console.log(`✅ ${currentStage} 已完成,下一步:sillyspec run auto --done --output "${currentStage} 完成"`)
588
- } else {
589
- console.log('🎉 全部流程已完成!')
590
- }
591
- return
592
- }
593
- outputStepPrompt(steps, pendingIdx, currentStage, cwd, progress)
594
- return
595
- }
596
-
597
- // --done:完成当前步骤,如果阶段完成则自动推进
598
- if (!outputText) {
599
- console.error('❌ auto --done 需要 --output 参数')
600
- process.exit(1)
601
- }
602
-
603
- const currentStage = progress.currentStage
604
- const stageIdx = flowStages.indexOf(currentStage)
605
- if (stageIdx === -1) {
606
- // 非流程阶段,找到第一个未完成的流程阶段
607
- const effectiveStage = flowStages.find(s => {
608
- const sd = progress.stages[s]
609
- return !sd || sd.status !== 'completed'
610
- }) || flowStages[0]
611
- progress.currentStage = effectiveStage
612
- pm._write(cwd, progress)
613
- console.log(`ℹ️ 当前阶段 ${currentStage} 不在 auto 流程中,自动切换到 ${effectiveStage}`)
614
- // effectiveStage 继续
615
- const completed = await completeStep(pm, progress, effectiveStage, cwd, outputText, inputText)
616
- if (!completed) return
617
- } else {
618
-
619
- // 完成当前步骤
620
- const completed = await completeStep(pm, progress, currentStage, cwd, outputText, inputText)
621
- if (!completed) return
622
-
623
- // 检查阶段是否完成
624
- const nextPendingIdx = progress.stages[currentStage]?.steps?.findIndex(s => s.status === 'pending')
625
- if (nextPendingIdx === -1) {
626
- // 阶段已完成
627
- const next = getNextStage(currentStage)
628
- if (next) {
629
- console.log(`\n✅ ${currentStage} 阶段完成,自动进入 ${next}`)
630
- // 输出下一阶段第一步 prompt
631
- const nextSteps = await getStageSteps(next, cwd, progress)
632
- if (nextSteps) {
633
- const firstPending = nextSteps.findIndex(s => s.status === 'pending')
634
- if (firstPending !== -1) {
635
- outputStepPrompt(nextSteps, firstPending, next, cwd, progress)
636
- }
637
- }
638
- } else {
639
- console.log('\n🎉 全部流程已完成!建议运行 /sillyspec:commit 提交改动')
640
- }
641
- } else {
642
- // 阶段内下一步
643
- const steps = await getStageSteps(currentStage, cwd, progress)
644
- if (steps) {
645
- const firstPending = steps.findIndex(s => s.status === 'pending')
646
- if (firstPending !== -1) {
647
- outputStepPrompt(steps, firstPending, currentStage, cwd, progress)
648
- }
649
- }
650
- }
651
- } // else stageIdx !== -1
652
- }
1
+ /**
2
+ * sillyspec run 命令实现
3
+ *
4
+ * CLI 成为流程引擎,AI 变成步骤执行器。
5
+ * 支持多变更并行:每个变更状态存储在 sillyspec.db 中。
6
+ */
7
+ import { basename, join, resolve, dirname } from 'path'
8
+ import { existsSync, readdirSync, mkdirSync, writeFileSync, appendFileSync, readFileSync, rmSync, statSync } from 'fs'
9
+ import { createRequire } from 'module'
10
+ const require = createRequire(import.meta.url)
11
+ import { ProgressManager } from './progress.js'
12
+ import { SCAN_STATUS, POINTER_STATUS, isPointerCorrupted } from './constants.js'
13
+
14
+ /**
15
+ * 清洗项目名:只保留 ASCII 字母/数字/横线/下划线/点,过滤中文和特殊字符。
16
+ * - 必须含至少一个字母(拒绝纯数字 "0"/"7"/"07",避免 scan-projects.json 脏数据)
17
+ * - 长度必须 ≥ 2(拒绝单字符 "a"/"0")
18
+ * @param {string} name - 原始项目名候选
19
+ * @returns {string | null} 合法项目名或 null(拒绝)
20
+ */
21
+ export function sanitizeProjectName(name) {
22
+ if (!name) return null
23
+ const clean = String(name).replace(/[^a-zA-Z0-9_\-.]/g, '').trim()
24
+ if (!clean) return null
25
+ if (!/[a-zA-Z]/.test(clean)) return null // 纯数字/符号拒绝("0"/"7"/"07")
26
+ if (clean.length < 2) return null // 单字符拒绝("a"/"0")
27
+ return clean
28
+ }
29
+
30
+ /**
31
+ * 校验从 step 2 解析出的项目列表。
32
+ * 不通过则不落盘 projects/*.yaml、不展开 perProject 步骤。
33
+ *
34
+ * @param {Array<{id: string, path?: string}>} projects - 项目列表(含可选 path)
35
+ * @param {string} sourceRoot - 源码根目录,用于 path 安全校验
36
+ */
37
+ export function validateParsedProjects(projects, sourceRoot) {
38
+ const errors = []
39
+ if (!projects || projects.length === 0) {
40
+ return { ok: false, errors: ['项目列表为空'] }
41
+ }
42
+ if (projects.length > 10) {
43
+ return { ok: false, errors: [`项目数量 ${projects.length} 超过上限 10,疑似误解析`] }
44
+ }
45
+ const safeRoot = resolve(sourceRoot)
46
+ const seen = new Set()
47
+ for (const proj of projects) {
48
+ const id = proj.id || proj
49
+ if (seen.has(id)) {
50
+ errors.push(`重复项目名: ${id}`)
51
+ }
52
+ seen.add(id)
53
+ // slug 合法性:只允许 a-z 0-9 _ - .,长度 2-64
54
+ if (!/^[a-zA-Z][\w\-.]{1,63}$/.test(id)) {
55
+ errors.push(`项目名 "${id}" 不合法(需 slug 格式:字母开头,只含 a-zA-Z0-9_-., 长度 2-64)`)
56
+ }
57
+ // path 安全校验(如果提供了 path)
58
+ if (proj.path) {
59
+ if (proj.path.includes('..')) {
60
+ errors.push(`项目 "${id}" 的 path 包含 .. ,拒绝越界`)
61
+ } else {
62
+ const absPath = resolve(safeRoot, proj.path)
63
+ if (!absPath.startsWith(safeRoot + '/') && absPath !== safeRoot) {
64
+ errors.push(`项目 "${id}" 的 path "${proj.path}" 解析后超出 source_root`)
65
+ }
66
+ if (!existsSync(absPath)) {
67
+ errors.push(`项目 "${id}" path "${proj.path}" 不存在`)
68
+ }
69
+ }
70
+ }
71
+ }
72
+ if (errors.length > 0) return { ok: false, errors }
73
+ return { ok: true, errors: [] }
74
+ }
75
+
76
+ /**
77
+ * 在容器/Docker 环境下,git 可能因目录所有权不匹配报 dubious ownership。
78
+ * 使用 -c safe.directory= 临时参数,不污染全局 git config。
79
+ * @param {string} cwd - 仓库根目录
80
+ * @param {string[]} args - git 子命令及参数,如 ['rev-parse', 'HEAD']
81
+ * @returns {{ value: string, error: string|null }}
82
+ */
83
+ function safeGit(cwd, args) {
84
+ const { execSync } = require('child_process')
85
+ const fullArgs = ['-c', `safe.directory=${cwd}`, '-C', cwd, ...args]
86
+ try {
87
+ const value = execSync(['git', ...fullArgs].join(' '), { encoding: 'utf8', timeout: 5000 }).trim()
88
+ return { value, error: null }
89
+ } catch (e) {
90
+ return { value: null, error: e.message.split('\n')[0] }
91
+ }
92
+ }
93
+
94
+ // ── Wait State Constants ──
95
+ // 正则匹配:只识别独立一行的标记,避免误伤文档正文引用
96
+ const WAIT_MARKER_RE = /^\s*\[(WAIT_FOR_USER|NEEDS_CONFIRM|NEEDS_DECISION)\]\s*$/m
97
+ const WAIT_MARKERS = ['[WAIT_FOR_USER]', '[NEEDS_CONFIRM]', '[NEEDS_DECISION]']
98
+
99
+ /**
100
+ * 格式化 waitOptions 为人类可读字符串
101
+ */
102
+ function formatWaitOptions(raw) {
103
+ if (!raw) return null
104
+ try {
105
+ const parsed = JSON.parse(raw)
106
+ if (Array.isArray(parsed)) return parsed.join(', ')
107
+ return raw
108
+ } catch {
109
+ return raw
110
+ }
111
+ }
112
+
113
+ /**
114
+ * 格式化 repeatableWait 步骤的历史用户回答,注入到重新输出的 step prompt 前。
115
+ * @param {object} step - progress 中的 step 对象(含 waitAnswers 数组)
116
+ * @returns {string|null} 格式化的历史文本,或 null(无历史)
117
+ */
118
+ function formatWaitHistory(step) {
119
+ const answers = Array.isArray(step.waitAnswers) ? step.waitAnswers : []
120
+ if (answers.length === 0) return null
121
+ let text = `本步骤历史用户回答(共 ${answers.length} 轮):\n`
122
+ for (const item of answers) {
123
+ text += `\n${item.round}. ${item.answer}`
124
+ if (item.question) {
125
+ text += `\n 对应问题/摘要:${item.question}`
126
+ }
127
+ }
128
+ const maxRounds = step.maxWaitRounds || null
129
+ if (maxRounds && answers.length >= maxRounds) {
130
+ text += `\n\n已达到 maxWaitRounds=${maxRounds}。请基于以上回答总结需求;除非仍有阻塞问题,否则完成本步骤并进入方案讨论。`
131
+ } else {
132
+ text += `\n\n请判断信息是否足够:如果足够,完成本步骤;如果仍缺关键约束,再提出一个问题并 --wait。`
133
+ }
134
+ return text
135
+ }
136
+
137
+ /**
138
+ * 解析规范目录路径
139
+ * 向上查找含 .sillyspec 的祖先目录,类似 git 找 .git 的逻辑。
140
+ * @param {string} cwd - 项目根目录(或子目录)
141
+ * @param {object} [opts]
142
+ * @param {string} [opts.specDir] - 用户指定的 specDir(通过 --spec-dir 或 --spec-root)
143
+ * @returns {string} 规范目录的绝对路径
144
+ */
145
+ function resolveSpecDir(cwd, opts = {}) {
146
+ if (opts.specDir) return resolve(opts.specDir)
147
+ let dir = resolve(cwd)
148
+ while (true) {
149
+ const candidate = join(dir, '.sillyspec')
150
+ if (existsSync(candidate)) return candidate
151
+ const parent = dirname(dir)
152
+ if (parent === dir) break
153
+ dir = parent
154
+ }
155
+ return join(resolve(cwd), '.sillyspec')
156
+ }
157
+ import { stageRegistry, auxiliaryStages } from './stages/index.js'
158
+ import { checkTransition, runValidators } from './stage-contract.js'
159
+ import { buildExecuteSteps } from './stages/execute.js'
160
+ import { buildPlanSteps } from './stages/plan.js'
161
+ import { formatExecuteSummary } from './worktree-apply.js'
162
+ import { classifyChange } from './classify-change.js'
163
+ import { detectRiskProfile } from './change-risk-profile.js'
164
+ import { definition as brainstormAutoDef } from './stages/brainstorm-auto.js'
165
+
166
+ /**
167
+ * 从 _module-map.yaml 读取模块上下文索引
168
+ * 用于 brainstorm/plan/execute 阶段按任务命中模块精准注入上下文
169
+ *
170
+ * @param {string} specBase - 规范目录(.sillyspec 或 specRoot)
171
+ * @param {string} projectName - 项目名
172
+ * @returns {object|null} 解析后的模块索引,null 表示无索引
173
+ */
174
+ function loadModuleContextIndex(specBase, projectName) {
175
+ try {
176
+ const { existsSync, readFileSync } = require('fs')
177
+ const { join } = require('path')
178
+ const mapPath = join(specBase, 'docs', projectName, 'modules', '_module-map.yaml')
179
+ if (!existsSync(mapPath)) return null
180
+ const content = readFileSync(mapPath, 'utf8')
181
+ return parseModuleMapSimple(content)
182
+ } catch {
183
+ return null
184
+ }
185
+ }
186
+
187
+ /**
188
+ * 根据 AI 输出的任务描述,匹配相关模块并生成上下文注入文本
189
+ * 匹配策略:模块 id / role / doc 路径中的关键词
190
+ *
191
+ * @param {string} taskDescription - 任务描述(来自 plan.md / step prompt / outputText)
192
+ * @param {object} moduleIndex - loadModuleContextIndex 返回值
193
+ * @param {string} specBase - 规范目录
194
+ * @param {string} projectName - 项目名
195
+ * @returns {string} 上下文注入文本,空字符串表示无匹配模块
196
+ */
197
+ function buildModuleContextInjection(taskDescription, moduleIndex, specBase, projectName) {
198
+ if (!moduleIndex || !taskDescription) return ''
199
+ const { existsSync } = require('fs')
200
+ const { join } = require('path')
201
+
202
+ const taskLower = taskDescription.toLowerCase()
203
+ const matched = []
204
+
205
+ for (const [moduleId, data] of Object.entries(moduleIndex)) {
206
+ let score = 0
207
+ let matchReasons = []
208
+ // 模块 id 匹配
209
+ if (taskLower.includes(moduleId.toLowerCase())) { score += 3; matchReasons.push(`id:${moduleId}`) }
210
+ // role 描述匹配
211
+ if (data.role && taskLower.includes(data.role.toLowerCase())) { score += 2; matchReasons.push('role') }
212
+ // core_files 路径匹配
213
+ const coreFiles = data.paths || data.core_files || []
214
+ for (const p of coreFiles) {
215
+ if (taskLower.includes(p.toLowerCase())) { score += 1; matchReasons.push(`file:${p}`); break }
216
+ }
217
+ if (score > 0) matched.push({ moduleId, data, score, matchReasons })
218
+ }
219
+
220
+ if (matched.length === 0) return ''
221
+
222
+ matched.sort((a, b) => b.score - a.score)
223
+
224
+ let injection = '\n### 📦 模块上下文(按相关性排序,来自 Module Context Index)\n\n'
225
+ injection += `> 以下模块上下文由 scan 阶段生成的 _module-map.yaml 自动匹配。\n`
226
+ injection += `> Matched modules: ${matched.map(m => m.moduleId).join(', ')}\n`
227
+ injection += `> Reasons: ${matched.map(m => m.matchReasons.join(', ')).join('; ')}\n\n`
228
+
229
+ for (const { moduleId, data } of matched) {
230
+ injection += `#### ${moduleId}\n`
231
+ if (data.role) injection += `- **职责**: ${String(data.role).slice(0, 100)}\n`
232
+ const riskLevel = data.risk_level || 'medium'
233
+ injection += `- **风险等级**: ${riskLevel}\n`
234
+ const coreFiles = data.paths || data.core_files || []
235
+ if (coreFiles.length > 0) injection += `- **核心文件**: ${coreFiles.join(', ')}\n`
236
+ if (data.doc) {
237
+ const docPath = join(specBase, 'docs', projectName, data.doc)
238
+ const exists = existsSync(docPath)
239
+ injection += `- **模块文档**: ${data.doc}${exists ? ' ✅' : ' ⚠️ 不存在'}\n`
240
+ }
241
+ const deps = data.depends_on || []
242
+ if (deps.length > 0) injection += `- **依赖**: ${deps.join(', ')}\n`
243
+ const usedBy = data.used_by || []
244
+ if (usedBy.length > 0) injection += `- **被引用**: ${usedBy.join(', ')}\n`
245
+ injection += '\n'
246
+ }
247
+
248
+ return injection
249
+ }
250
+
251
+ // 复用 modules.js 的简单 YAML 解析(避免循环依赖)
252
+ function parseModuleMapSimple(content) {
253
+ const modules = {}
254
+ let currentModule = null
255
+ let currentKey = null
256
+ let currentArray = null
257
+
258
+ for (const line of content.split('\n')) {
259
+ const moduleMatch = line.match(/^ ([a-zA-Z0-9_-]+):$/)
260
+ if (moduleMatch) {
261
+ if (currentArray && currentModule && currentKey) {
262
+ modules[currentModule][currentKey] = currentArray
263
+ }
264
+ currentModule = moduleMatch[1]
265
+ modules[currentModule] = {}
266
+ currentKey = null
267
+ currentArray = null
268
+ continue
269
+ }
270
+ if (!currentModule) continue
271
+
272
+ const arrayFieldMatch = line.match(/^ (depends_on|used_by|paths|tags|aliases|entrypoints|main_symbols|review_reasons|core_files|test_files|related_docs|verify_commands):$/)
273
+ if (arrayFieldMatch) {
274
+ if (currentArray && currentKey) modules[currentModule][currentKey] = currentArray
275
+ currentKey = arrayFieldMatch[1]
276
+ currentArray = []
277
+ continue
278
+ }
279
+
280
+ const inlineArrayMatch = line.match(/^ (depends_on|used_by|paths|tags|aliases|entrypoints|main_symbols|review_reasons|core_files|test_files|related_docs|verify_commands): \[(.*)\]$/)
281
+ if (inlineArrayMatch) {
282
+ if (currentArray && currentKey) modules[currentModule][currentKey] = currentArray
283
+ const vals = inlineArrayMatch[2].split(',').map(v => v.trim()).filter(Boolean)
284
+ modules[currentModule][inlineArrayMatch[1]] = vals
285
+ currentKey = null
286
+ currentArray = null
287
+ continue
288
+ }
289
+
290
+ const scalarMatch = line.match(/^ (status|doc|needs_review|role|risk_level): (.+)$/)
291
+ if (scalarMatch) {
292
+ if (currentArray && currentKey) { modules[currentModule][currentKey] = currentArray; currentArray = null; currentKey = null }
293
+ modules[currentModule][scalarMatch[1]] = scalarMatch[2]
294
+ continue
295
+ }
296
+
297
+ const itemMatch = line.match(/^ - (.+)$/)
298
+ if (itemMatch && currentArray !== null) {
299
+ currentArray.push(itemMatch[1].trim())
300
+ continue
301
+ }
302
+ }
303
+ if (currentArray && currentModule && currentKey) {
304
+ modules[currentModule][currentKey] = currentArray
305
+ }
306
+ return modules
307
+ }
308
+
309
+ /**
310
+ * 同步触发辅助函数:_write 后 best-effort 同步到平台
311
+ */
312
+ /**
313
+ * quick 完成审计:对比 baseline 与实际变更
314
+ */
315
+ async function auditQuickCompletion(cwd, guard, options = {}) {
316
+ const { baselineFiles, allowedFiles = [], allowNew = false, forceBaseline = false } = guard
317
+ const { isConfirm } = options
318
+ const result = { status: 'safe', reasons: [], changedFiles: [], newFiles: [], deletedFiles: [], baselineHit: [] }
319
+
320
+ try {
321
+ const { execSync } = await import('child_process')
322
+ const gitStatus = execSync('git status --porcelain', { cwd, encoding: 'utf8', timeout: 10000 })
323
+ const currentEntries = gitStatus.trim().split('\n').filter(Boolean)
324
+
325
+ const normalizeGitPath = (p) => p.replace(/\\/g, '/')
326
+ const isQuickMetadata = (p) => {
327
+ const file = normalizeGitPath(p)
328
+ return file.startsWith('.sillyspec/quicklog/')
329
+ || file.startsWith('.sillyspec/.runtime/')
330
+ || file === '.sillyspec/knowledge/uncategorized.md'
331
+ || (/^\.sillyspec\/docs\/[^/]+\/modules\/[^/]+\.md$/.test(file))
332
+ || (/^\.sillyspec\/docs\/[^/]+\/modules\/_module-map\.yaml$/.test(file))
333
+ }
334
+ const DANGEROUS_PATTERNS = [
335
+ 'package.json',
336
+ 'package-lock.json',
337
+ 'yarn.lock',
338
+ 'pnpm-lock.yaml',
339
+ '.eslintrc',
340
+ 'tsconfig.json',
341
+ 'src/db.js',
342
+ 'src/progress.js',
343
+ 'src/run.js',
344
+ 'src/stage-contract.js',
345
+ 'src/worktree.js',
346
+ 'src/worktree-apply.js',
347
+ 'src/hooks/',
348
+ ]
349
+
350
+ for (const entry of currentEntries) {
351
+ const status = entry.slice(0, 2).trim()
352
+ const file = normalizeGitPath(entry.slice(3).trim())
353
+ if (!file || file.startsWith('??. ')) continue
354
+
355
+ result.changedFiles.push(file)
356
+ if (status === 'D' || status === ' D') result.deletedFiles.push(file)
357
+ if (status === '??') result.newFiles.push(file)
358
+
359
+ // 检查是否命中 baseline protected files
360
+ if (baselineFiles.includes(file)) {
361
+ result.baselineHit.push(file)
362
+ }
363
+
364
+ // 检查危险文件(除非 force-baseline)
365
+ if (file.startsWith('.sillyspec/') && !isQuickMetadata(file) && !forceBaseline) {
366
+ result.reasons.push(`危险文件变更: ${file}`)
367
+ }
368
+
369
+ if (DANGEROUS_PATTERNS.some(p => file === p || file.startsWith(p)) && !forceBaseline) {
370
+ result.reasons.push(`危险文件变更: ${file}`)
371
+ }
372
+ }
373
+
374
+ // 检查 deleted files
375
+ for (const f of result.deletedFiles) {
376
+ result.reasons.push(`删除文件: ${f}`)
377
+ }
378
+
379
+ // 检查 baseline hit(除非 force-baseline)
380
+ if (!forceBaseline) {
381
+ for (const f of result.baselineHit) {
382
+ result.reasons.push(`覆盖 baseline 文件: ${f}`)
383
+ }
384
+ }
385
+
386
+ // 检查 new files(除非 allow-new)
387
+ if (!allowNew) {
388
+ for (const f of result.newFiles) {
389
+ if (!isQuickMetadata(f)) {
390
+ result.reasons.push(`新增文件(需 --allow-new): ${f}`)
391
+ }
392
+ }
393
+ }
394
+
395
+ // 检查 allowedFiles 范围
396
+ if (allowedFiles.length > 0) {
397
+ for (const f of result.changedFiles) {
398
+ if (!allowedFiles.includes(f) && !isQuickMetadata(f)) {
399
+ result.reasons.push(`超出 allowedFiles: ${f}`)
400
+ }
401
+ }
402
+ }
403
+
404
+ // 判定结果
405
+ if (result.baselineHit.length > 0 || result.deletedFiles.length > 0 || result.reasons.some(r => r.startsWith('危险') || r.startsWith('删除'))) {
406
+ result.status = 'blocked'
407
+ } else if (result.newFiles.length > 0 || (allowedFiles.length > 0 && result.reasons.some(r => r.startsWith('超出')))) {
408
+ result.status = 'warning'
409
+ }
410
+
411
+ // quicklog 存在性检查
412
+ try {
413
+ const quicklogDir = join(cwd, '.sillyspec', 'quicklog')
414
+ if (existsSync(quicklogDir)) {
415
+ const qlFiles = readdirSync(quicklogDir).filter(f => f.endsWith('.md'))
416
+ if (qlFiles.length === 0) {
417
+ result.reasons.push('quicklog 目录为空(无任务记录)')
418
+ if (result.status === 'safe') result.status = 'warning'
419
+ }
420
+ } else {
421
+ result.reasons.push('quicklog 目录不存在(agent 未创建任务记录)')
422
+ if (result.status === 'safe') result.status = 'warning'
423
+ }
424
+ } catch {}
425
+
426
+ // --confirm 模式:展示 diff 并等待确认
427
+ if (isConfirm && (result.status === 'warning' || result.status === 'blocked')) {
428
+ console.log(`\n📋 quick 变更概览:`)
429
+ console.log(` 新增: ${result.newFiles.length}, 修改: ${result.changedFiles.length - result.newFiles.length - result.deletedFiles.length}, 删除: ${result.deletedFiles.length}`)
430
+ if (result.changedFiles.length > 0) {
431
+ console.log(`\n 变更文件:`)
432
+ for (const f of result.changedFiles) {
433
+ const isBaseline = baselineFiles.includes(f)
434
+ const isDangerous = DANGEROUS_PATTERNS.some(p => f.includes(p))
435
+ const marker = isBaseline ? '🔴' : isDangerous ? '⚠️' : ' '
436
+ console.log(` ${marker} ${f}`)
437
+ }
438
+ }
439
+ console.log(`\n 状态: ${result.status.toUpperCase()}`)
440
+ if (result.reasons.length > 0) {
441
+ console.log(` 原因:`)
442
+ for (const r of result.reasons) {
443
+ console.log(` - ${r}`)
444
+ }
445
+ }
446
+ console.log(`\n 如确认接受这些变更,重新运行:sillyspec run quick --done --confirm --output "..."`)
447
+ console.log(` 或使用 --force-baseline 允许覆盖 baseline 文件,--allow-new 允许新增文件`)
448
+ }
449
+ } catch (e) {
450
+ result.reasons.push(`审计失败: ${e.message}`)
451
+ result.status = 'warning'
452
+ }
453
+
454
+ return result
455
+ }
456
+
457
+ function printQuickAuditReview(review) {
458
+ if (review.status === 'blocked') {
459
+ console.error(`\n🚫 quick 变更边界审计 — BLOCKED:`)
460
+ for (const r of review.reasons) {
461
+ console.error(` - ${r}`)
462
+ }
463
+ console.error(`\n quick 已停止:请恢复/拆分这些变更,或重新运行 quick 并显式声明范围。`)
464
+ } else if (review.status === 'warning') {
465
+ console.warn(`\n⚠️ quick 变更边界审计 WARNING:`)
466
+ for (const r of review.reasons) {
467
+ console.warn(` - ${r}`)
468
+ }
469
+ } else {
470
+ console.log(`\n✅ quick 变更边界审计 — SAFE (变更 ${review.changedFiles.length} 个文件)`)
471
+ }
472
+ }
473
+
474
+ async function triggerSync(cwd, changeName, platformOpts = {}) {
475
+ // 平台模式(SillyHub)走自己的回传链路,不走 CLI 内置 sync
476
+ if (platformOpts?.specRoot || platformOpts?.runtimeRoot) return
477
+ try {
478
+ if (changeName && !existsSync(join(cwd, '.sillyspec', 'changes', changeName))) return
479
+ const syncMod = await import('./sync.js')
480
+ await syncMod.sync(changeName, cwd)
481
+ } catch (e) {
482
+ // sync.js 不存在或同步失败,静默跳过
483
+ console.warn('⚠️ 同步失败:', e.message)
484
+ }
485
+ }
486
+
487
+ /**
488
+ * 审批检查辅助函数:execute 阶段启动前检查
489
+ * @returns {{ status: string, reason?: string } | null}
490
+ */
491
+ async function checkApproval(cwd, changeName, platformOpts = {}) {
492
+ // 平台模式不需要 CLI 内置审批检查
493
+ if (platformOpts?.specRoot || platformOpts?.runtimeRoot) return null
494
+ try {
495
+ const syncMod = await import('./sync.js')
496
+ return await syncMod.checkApproval(changeName, cwd)
497
+ } catch (e) {
498
+ return null
499
+ }
500
+ }
501
+
502
+ /**
503
+ * 统一查找变更目录(与 progress.js 的变更检测逻辑一致)
504
+ */
505
+ function resolveChangeDir(cwd, progress, specDir = null) {
506
+ const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
507
+ if (!existsSync(changesDir)) return null
508
+
509
+ // 1. 优先用 currentChange
510
+ if (progress.currentChange) {
511
+ const target = join(changesDir, progress.currentChange)
512
+ if (existsSync(target)) return target
513
+ }
514
+
515
+ // 2. fallback:唯一非 archive 目录
516
+ const entries = readdirSync(changesDir, { withFileTypes: true })
517
+ .filter(e => e.isDirectory() && e.name !== 'archive')
518
+ if (entries.length === 1) return join(changesDir, entries[0].name)
519
+
520
+ return null
521
+ }
522
+
523
+ /**
524
+ * 自动探测并设置 currentChange(唯一变更目录时)
525
+ * @returns {boolean} 是否设置了 currentChange
526
+ */
527
+ function autoDetectChange(progress, cwd, specDir = null) {
528
+ if (progress.currentChange) return false
529
+ const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
530
+ if (!existsSync(changesDir)) return false
531
+ const entries = readdirSync(changesDir, { withFileTypes: true })
532
+ .filter(e => e.isDirectory() && e.name !== 'archive')
533
+ if (entries.length === 1) {
534
+ progress.currentChange = entries[0].name
535
+ return true
536
+ }
537
+ return false
538
+ }
539
+
540
+ /**
541
+ * progress 或变更目录推导变更名
542
+ */
543
+ function resolveChangeName(cwd, progress, specDir = null) {
544
+ if (progress.currentChange) return progress.currentChange
545
+ const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
546
+ if (!existsSync(changesDir)) return null
547
+ const entries = readdirSync(changesDir, { withFileTypes: true })
548
+ .filter(e => e.isDirectory() && e.name !== 'archive')
549
+ if (entries.length === 1) return entries[0].name
550
+ return null
551
+ }
552
+
553
+ /**
554
+ * 获取阶段的步骤定义(execute 需要动态构建)
555
+ */
556
+ async function getStageSteps(stageName, cwd, progress, specDir = null) {
557
+ if (stageName === 'execute') {
558
+ const changeDir = resolveChangeDir(cwd, progress, specDir)
559
+ let planFile = null
560
+ if (changeDir) {
561
+ const p = join(changeDir, 'plan.md')
562
+ if (existsSync(p)) planFile = p
563
+ }
564
+ return buildExecuteSteps(planFile)
565
+ }
566
+ if (stageName === 'plan') {
567
+ const changeDir = resolveChangeDir(cwd, progress, specDir)
568
+ return buildPlanSteps(changeDir)
569
+ }
570
+ const def = stageRegistry[stageName]
571
+ return def ? def.steps : null
572
+ }
573
+
574
+ /**
575
+ * 确保阶段的 steps 已初始化到 progress
576
+ */
577
+ async function ensureStageSteps(progress, stageName, cwd, specDir = null) {
578
+ if (!progress.stages) progress.stages = {}
579
+
580
+ const steps = await getStageSteps(stageName, cwd, progress, specDir)
581
+ if (!steps) return false
582
+
583
+ if (!progress.stages[stageName] || !progress.stages[stageName].steps || progress.stages[stageName].steps.length === 0) {
584
+ progress.stages[stageName] = {
585
+ status: 'in-progress',
586
+ startedAt: new Date().toLocaleString('zh-CN',{hour12:false}),
587
+ completedAt: null,
588
+ steps: steps.map(s => ({ name: s.name, status: 'pending' }))
589
+ }
590
+ return true // 需要写入
591
+ }
592
+
593
+ // 检查步骤数量是否匹配(execute 动态步骤可能变化)
594
+ if (progress.stages[stageName].steps.length !== steps.length) {
595
+ const oldSteps = progress.stages[stageName].steps
596
+ progress.stages[stageName].steps = steps.map(s => {
597
+ const old = oldSteps.find(step => step.name === s.name)
598
+ if (old) return old
599
+ return { name: s.name, status: 'pending' }
600
+ })
601
+ return true
602
+ }
603
+
604
+ return false
605
+ }
606
+
607
+ /**
608
+ * 输出当前步骤的 prompt
609
+ */
610
+ async function outputStep(stageName, stepIndex, steps, cwd, changeName, dbProjectName, platformOpts = {}, prevStepAnswer = null) {
611
+ const step = steps[stepIndex]
612
+ const total = steps.length
613
+ // ── 越界防御 ──
614
+ // steps/defSteps 来自 getStageSteps(如 buildPlanSteps),其长度可能与 progress.steps
615
+ // 不一致(例如平台模式下 changeDir 解析失败导致 buildPlanSteps(null) 只返回 2 fixedPrefix)。
616
+ // 此时 stepIndex 可能越界,访问 step.name 会 TypeError 崩溃。降级处理而非崩溃。
617
+ if (!step) {
618
+ console.error(`⚠️ 无法输出步骤 ${stepIndex + 1}/${total}:步骤定义缺失`)
619
+ console.error(` stage=${stageName} stepIndex=${stepIndex} defSteps.length=${steps.length}`)
620
+ console.error(` 可能原因:平台模式下 getStageSteps 未传 specRoot,或 plan/execute 步骤动态生成后 defSteps 未同步。`)
621
+ console.error(` 请检查 --change 指定的变更目录是否存在、specRoot 是否正确,然后重试。`)
622
+ return false
623
+ }
624
+ const projectName = dbProjectName || basename(cwd)
625
+
626
+ // ── Revision context injection ──
627
+ const revisionCtx = platformOpts?._revision
628
+ if (revisionCtx) {
629
+ console.log(`### 🔄 Revision Context`)
630
+ console.log(`本阶段处于修订模式(revision ${revisionCtx.revision}),不是首次执行。`)
631
+ console.log(`- 修订起始步骤:${revisionCtx.fromStep}`)
632
+ console.log(`- 当前步骤之前已完成的步骤仍然有效,不需要重做。`)
633
+ console.log(`- 当前步骤及之后的步骤需要重新生成或调整已有产物。`)
634
+ console.log(`- 已有产物文件(design.md、plan.md 等)被保留,审视并更新它们,而不是从零创建。`)
635
+ console.log(`- 不要绕过 CLI 进度追踪。\n`)
636
+ }
637
+
638
+ const personas = {
639
+ brainstorm: `### 🎯 你的角色:资深架构师
640
+ 你是一位有 15 年经验的系统架构师。先理解业务本质,再设计技术方案。决策附理由,方案列 trade-off。不确定就说不确定,不猜。`,
641
+ plan: `### 📋 你的角色:技术项目经理
642
+ 你是一位经验丰富的技术项目经理。任务拆解粒度均匀,依赖关系明确。每个任务有完成标准,Wave 间有依赖说明。条理清晰,不做模糊描述。`,
643
+ execute: `### 💻 你的角色:高级工程师
644
+ 你是一位严谨的高级工程师。先读规范再写代码,严格遵循 CONVENTIONS.md 和 plan.md。**你不是设计师,是执行者——按 plan 搬砖,禁止发散思维。** 发现 plan 不合理就停下来反馈,不要自己改方案。代码有清晰职责划分,边界处理完善。少说多做,遇到规范冲突优先问。`,
645
+ verify: `### 🔍 你的角色:QA 专家
646
+ 你是一位吹毛求疵的 QA 专家。假设所有代码都有 bug,用最坏情况测试。关注边界、异常、并发。有问题直说,用证据说话,不写"看起来没问题"。`,
647
+ quick: `### 💻 你的角色:全栈老兵
648
+ 你是一位实战经验丰富的全栈工程师。不纠结架构和流程,理解需求就直接干。不确定的地方先问清楚再动手,先读后写,改完就收。问题排查思路开阔,前端报错不一定是前端问题——可能是后端数据、浏览器兼容、甚至设备硬件。解决方案实用接地气,用户描述有误敢于直接指出。`,
649
+ explore: `### 🧭 你的角色:技术探索伙伴
650
+ 你帮助用户澄清问题、调查代码库、比较方案和暴露风险。探索阶段不写实现代码,不安装依赖,不把讨论强行推进成开发。`
651
+ }
652
+
653
+ console.log(`---`)
654
+ console.log(`stage: ${stageName}`)
655
+ console.log(`step: ${stepIndex + 1}/${total}`)
656
+ console.log(`stepName: ${step.name}`)
657
+ console.log(`project: ${projectName}`)
658
+ if (changeName) {
659
+ console.log(`change: ${changeName}`)
660
+ const isPlatform = platformOpts?.specRoot || platformOpts?.runtimeRoot
661
+ const changeDirBase = isPlatform ? platformOpts.specRoot : '.sillyspec'
662
+ const changeDir = join(changeDirBase, 'changes', changeName)
663
+ console.log(`changeDir: ${changeDir}`)
664
+ }
665
+ console.log(`---\n`)
666
+ if (personas[stageName]) {
667
+ console.log(personas[stageName])
668
+ console.log('')
669
+ }
670
+ // 注入全局护栏(如 _globalGuardrails)
671
+ const stageDef = stageRegistry[stageName]
672
+ const guardrails = stageDef && stageDef._globalGuardrails ? stageDef._globalGuardrails : ''
673
+
674
+ console.log(`## Step ${stepIndex + 1}/${total}: ${step.name}\n`)
675
+ if (guardrails) {
676
+ console.log(guardrails.trim())
677
+ console.log('')
678
+ }
679
+ let promptText = step.prompt
680
+ // 替换 prompt 中的占位符
681
+ if (projectName && promptText.includes('<project>')) {
682
+ promptText = promptText.replace(/<project>/g, projectName)
683
+ }
684
+ // 替换 <git-user> 占位符
685
+ if (promptText.includes('<git-user>')) {
686
+ const { execSync } = await import('child_process')
687
+ try {
688
+ const gitUser = safeGit(cwd, ['config', 'user.name']).value || 'unknown'
689
+ promptText = promptText.replace(/<git-user>/g, gitUser)
690
+ } catch {
691
+ promptText = promptText.replace(/<git-user>/g, 'unknown')
692
+ }
693
+ }
694
+ // 替换时间戳占位符
695
+ const now = new Date()
696
+ const nowDatetime = now.getFullYear() + '-' + String(now.getMonth()+1).padStart(2,'0') + '-' + String(now.getDate()).padStart(2,'0') + ' ' + String(now.getHours()).padStart(2,'0') + ':' + String(now.getMinutes()).padStart(2,'0') + ':' + String(now.getSeconds()).padStart(2,'0')
697
+ const nowTimestamp = now.getFullYear() + String(now.getMonth()+1).padStart(2,'0') + String(now.getDate()).padStart(2,'0') + '-' + String(now.getHours()).padStart(2,'0') + String(now.getMinutes()).padStart(2,'0') + String(now.getSeconds()).padStart(2,'0')
698
+ const nowDate = now.getFullYear() + '-' + String(now.getMonth()+1).padStart(2,'0') + '-' + String(now.getDate()).padStart(2,'0')
699
+ promptText = promptText.replace(/<now-datetime>/g, nowDatetime)
700
+ promptText = promptText.replace(/<now-timestamp>/g, nowTimestamp)
701
+ promptText = promptText.replace(/<now-date>/g, nowDate)
702
+ // 替换 <change-name> 占位符
703
+ if (changeName && promptText.includes('<change-name>')) {
704
+ promptText = promptText.replace(/<change-name>/g, changeName)
705
+ }
706
+ // 平台模式:注入路径覆盖指令
707
+ if (platformOpts?.specRoot || platformOpts?.runtimeRoot) {
708
+ const projectName = dbProjectName || basename(cwd)
709
+ // platformOpts.specRoot 现在指向 specDir 本身(可能是 cwd/.sillyspec 或外部路径)
710
+ const specSillyspec = platformOpts.specRoot || join(cwd, '.sillyspec')
711
+ const docsRoot = join(specSillyspec, 'docs', projectName)
712
+ const projectsRoot = join(specSillyspec, 'projects')
713
+ const changesRoot = join(specSillyspec, 'changes')
714
+ const workflowsRoot = join(specSillyspec, 'workflows')
715
+ const knowledgeRoot = join(specSillyspec, 'knowledge')
716
+
717
+ promptText = promptText.replace(/\{DOCS_ROOT\}/g, docsRoot)
718
+ promptText = promptText.replace(/\{PROJECTS_ROOT\}/g, projectsRoot)
719
+ promptText = promptText.replace(/\{WORKFLOWS_ROOT\}/g, workflowsRoot)
720
+ promptText = promptText.replace(/\{KNOWLEDGE_ROOT\}/g, knowledgeRoot)
721
+ promptText = promptText.replace(/\{SPEC_ROOT\}/g, specSillyspec)
722
+
723
+ const platformDirectives = []
724
+ platformDirectives.push(
725
+ `## ⚠️ 平台模式 — 写入路径约束(必须严格遵守)\n` +
726
+ `\n` +
727
+ `规范目录(specDir): \`${specSillyspec}\`\n` +
728
+ `- 文档根目录: \`${docsRoot}/\`\n` +
729
+ `- 项目注册表: \`${projectsRoot}/\`\n` +
730
+ `- 变更目录: \`${changesRoot}/\`\n` +
731
+ `- 工作流目录: \`${workflowsRoot}/\`\n` +
732
+ `- 术语目录: \`${knowledgeRoot}/\`\n` +
733
+ `\n` +
734
+ `### ⛔ 写入规则\n` +
735
+ `1. **所有文档、配置、产物只能写入上述路径**。严禁写入源码目录或相对路径 \`.sillyspec/\`。\n` +
736
+ `2. **不允许**从 cwd 推导文档路径,必须使用上面列出的绝对路径。\n` +
737
+ `3. **源码扫描范围**必须排除:.sillyspec/、.claude/、.git/、node_modules/、dist/、build/、__pycache__/\n` +
738
+ `4. **local.yaml 校验**:commands 中引用的命令必须在 package.json 的 scripts 中存在,不存在的标记为 unavailable,不能写 "配置良好"\n` +
739
+ `\n` +
740
+ `### ⛔ Write 工具规则\n` +
741
+ `1. 如果 Write 返回 \"File has not been read yet\",正确动作是:先 Read 目标文件 → 再 Write 覆盖。\n` +
742
+ `2. **不允许**用 cat >、tee、heredoc 等 Bash 方式绕过 Write 工具。\n` +
743
+ `3. 如果 Write 和 Read 均失败,记录失败并停止当前 step。\n` +
744
+ `\n` +
745
+ `### 📍 Workflow YAML 占位符映射(task-05)\n` +
746
+ `读取 \`{WORKFLOWS_ROOT}/scan-docs.yaml\` 时,yaml 内的占位符按以下映射替换为绝对路径:\n` +
747
+ `- \`{SPEC_ROOT}\` → \`${specSillyspec}\`(规范目录根)\n` +
748
+ `- \`<project>\` → 当前项目名(见下方 step 提示,等于 \`${projectName}\`)\n` +
749
+ `- 例:\`{SPEC_ROOT}/docs/<project>/scan/ARCHITECTURE.md\` → \`${docsRoot}/scan/ARCHITECTURE.md\`\n` +
750
+ `\n` +
751
+ `创建目录: \`mkdir -p ${docsRoot}/{scan,modules,flows} ${projectsRoot} ${changesRoot}\`\n`
752
+ )
753
+ if (platformOpts.runtimeRoot) {
754
+ const scanRunId = platformOpts.scanRunId || 'scan-' + new Date().toISOString().slice(0, 19).replace(/[T:]/g, '-')
755
+ platformDirectives.push(
756
+ `运行时产物写入: \`${platformOpts.runtimeRoot}/scan-runs/${scanRunId}/\`\n`
757
+ )
758
+ }
759
+ if (platformOpts.workspaceId) {
760
+ platformDirectives.push(`workspace_id: ${platformOpts.workspaceId}`)
761
+ }
762
+ promptText = platformDirectives.join('\n') + '\n\n' + promptText
763
+ }
764
+
765
+ // 注入 scanProfile 硬约束指令
766
+ if (stageName === 'scan' && platformOpts?.scanProfile) {
767
+ const sp = platformOpts.scanProfile
768
+ const profileDirectives = []
769
+ profileDirectives.push(`## 📊 Scan Profile: ${sp.mode} (${sp.reason})`)
770
+ if (sp.maxAgentCalls === 0) {
771
+ profileDirectives.push(`**⛔ 严禁使用子代理(Agent/Task 工具)。** 必须在本 turn 内完成所有工作。`)
772
+ } else if (sp.maxAgentCalls > 0) {
773
+ profileDirectives.push(`**子代理上限:${sp.maxAgentCalls} 个。** 不要超出。`)
774
+ }
775
+ if (sp.maxDocs < 99) {
776
+ profileDirectives.push(`**文档上限:${sp.maxDocs} 份。** 只生成核心文档,不要额外生成 flows/glossary/module-card。`)
777
+ }
778
+ profileDirectives.push(`--output 只需要列出文件名,不要写长篇总结。`)
779
+ promptText = profileDirectives.join('\n') + '\n\n' + promptText
780
+
781
+ // scanProfile 分支也要替换占位符(非 platform 模式也会走到这里)
782
+ const _pName = dbProjectName || basename(cwd)
783
+ const _specSS = platformOpts?.specRoot || join(cwd, '.sillyspec')
784
+ const _docsRoot = join(_specSS, 'docs', _pName)
785
+ promptText = promptText.replace(/\{DOCS_ROOT\}/g, _docsRoot)
786
+ promptText = promptText.replace(/\{PROJECTS_ROOT\}/g, join(_specSS, 'projects'))
787
+ promptText = promptText.replace(/\{WORKFLOWS_ROOT\}/g, join(_specSS, 'workflows'))
788
+ promptText = promptText.replace(/\{KNOWLEDGE_ROOT\}/g, join(_specSS, 'knowledge'))
789
+ promptText = promptText.replace(/\{SPEC_ROOT\}/g, _specSS)
790
+ } else {
791
+ // 非 platform 模式也要替换占位符
792
+ const projectName = dbProjectName || basename(cwd)
793
+ const specSillyspec = join(cwd, '.sillyspec')
794
+ const docsRoot = join(specSillyspec, 'docs', projectName)
795
+ const projectsRoot = join(specSillyspec, 'projects')
796
+ const workflowsRoot = join(specSillyspec, 'workflows')
797
+ const knowledgeRoot = join(specSillyspec, 'knowledge')
798
+ promptText = promptText.replace(/\{DOCS_ROOT\}/g, docsRoot)
799
+ promptText = promptText.replace(/\{PROJECTS_ROOT\}/g, projectsRoot)
800
+ promptText = promptText.replace(/\{WORKFLOWS_ROOT\}/g, workflowsRoot)
801
+ promptText = promptText.replace(/\{KNOWLEDGE_ROOT\}/g, knowledgeRoot)
802
+ promptText = promptText.replace(/\{SPEC_ROOT\}/g, specSillyspec)
803
+ }
804
+
805
+ // Knowledge hit report: execute 阶段注入匹配结果
806
+ if (stageName === 'execute' && promptText.includes('{KNOWLEDGE_HIT_REPORT}')) {
807
+ try {
808
+ const { matchKnowledge } = await import('./knowledge-match.js')
809
+ const effectiveSpecBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
810
+ const knowledgeDir = join(effectiveSpecBase, 'knowledge')
811
+ // taskContext: changeName + plan.md task names for better matching
812
+ let taskContext = changeName || ''
813
+ if (changeName) {
814
+ const planPath = join(effectiveSpecBase, 'changes', changeName, 'plan.md')
815
+ try {
816
+ const planContent = readFileSync(planPath, 'utf8')
817
+ // match both "- [ ] task-01: title" and "## task-01: title" formats
818
+ const taskLines = [...planContent.matchAll(/(?:^\- \[[ x]\] |^## )task-\d+[^:]*:?\s*(.+)/gm)]
819
+ if (taskLines.length > 0) {
820
+ taskContext += ' ' + taskLines.map(t => t[1]).join(' ')
821
+ }
822
+ } catch {}
823
+ }
824
+ const knowledgeResult = matchKnowledge(knowledgeDir, taskContext)
825
+ promptText = promptText.replace(/\{KNOWLEDGE_HIT_REPORT\}/g, knowledgeResult.report)
826
+ // 写入 runtime JSON
827
+ const runtimeDir = join(effectiveSpecBase, '.runtime')
828
+ mkdirSync(runtimeDir, { recursive: true })
829
+ writeFileSync(join(runtimeDir, 'knowledge-hit-report.json'), JSON.stringify(knowledgeResult.json, null, 2) + '\n')
830
+ } catch (e) {
831
+ promptText = promptText.replace(/\{KNOWLEDGE_HIT_REPORT\}/g, 'Status: no matches (error: ' + e.message + ')')
832
+ }
833
+ }
834
+
835
+ // Execute: 注入 currentExecuteRunId(从变更专属标记文件读取)
836
+ if (stageName === 'execute' && promptText.includes('{EXECUTE_RUN_ID}')) {
837
+ let runId = ''
838
+ const execSpecBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
839
+ const runIdFile = join(execSpecBase, '.runtime', `current-execute-run-id-${changeName}`)
840
+ try {
841
+ if (existsSync(runIdFile)) {
842
+ runId = readFileSync(runIdFile, 'utf8').trim()
843
+ }
844
+ } catch {}
845
+ if (!runId) {
846
+ const { generateExecuteRunId } = await import('./task-review.js')
847
+ runId = generateExecuteRunId()
848
+ }
849
+ promptText = promptText.replace(/\{EXECUTE_RUN_ID\}/g, runId)
850
+ }
851
+
852
+ // 注入模块上下文(brainstorm/plan/execute 阶段,基于 Module Context Index)
853
+ if (['brainstorm', 'plan', 'execute'].includes(stageName) && projectName) {
854
+ const effectiveSpecBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
855
+ const moduleIndex = loadModuleContextIndex(effectiveSpecBase, projectName)
856
+ if (moduleIndex && Object.keys(moduleIndex).length > 0) {
857
+ // 尝试从 step prompt / changeName 匹配模块
858
+ const taskDesc = step.prompt || changeName || ''
859
+ const injection = buildModuleContextInjection(taskDesc, moduleIndex, effectiveSpecBase, projectName)
860
+ if (injection) {
861
+ promptText = injection + '\n' + promptText
862
+ }
863
+ }
864
+ }
865
+
866
+ // 平台模式 prompt 自检:确保没有裸相对输出路径
867
+ // 只匹配正向写入指令中的裸路径,避免误杀「禁止写入 .sillyspec/」等安全说明
868
+ if ((platformOpts?.specRoot || platformOpts?.runtimeRoot) && stageName === 'scan') {
869
+ const writeCtx = /(?<!不要|禁止|严禁)(?:save[\s.]+to|write|create|mkdir|git add|写入|保存到|写入到)[^a-zA-Z]*\.sillyspec\/[a-z]/i
870
+ if (writeCtx.test(promptText)) {
871
+ console.error(`❌ [sillyspec] BUG: 平台模式 scan prompt 包含写入指令指向裸相对路径 .sillyspec/`)
872
+ console.error(` 这会导致 agent 写入源码目录而非 spec-root,属于源码污染 bug。`)
873
+ console.error(` 请将路径改为对应的 {DOCS_ROOT}/{PROJECTS_ROOT}/{WORKFLOWS_ROOT}/{KNOWLEDGE_ROOT}/{SPEC_ROOT} 占位符。`)
874
+ process.exit(1)
875
+ }
876
+ }
877
+
878
+ if (prevStepAnswer) {
879
+ console.log(`\n### 📩 上一步用户回答`)
880
+ console.log(prevStepAnswer)
881
+ }
882
+
883
+ console.log(promptText)
884
+ console.log(`\n### ⚠️ 铁律`)
885
+ console.log('- **文档是核心资产,代码是文档的产物。** 没有文档就没有代码——文档是 AI 的记忆,是团队协作的基础,是后续维护的唯一依据。任何代码产出必须先有对应的设计/规范文档支撑。')
886
+ console.log('- 只做本步骤描述的操作,不得自行扩展或跳过')
887
+ console.log('- 不要回头修改已完成的步骤')
888
+ console.log('- 不要编造不存在的 CLI 子命令')
889
+ console.log('- 完成后立即执行 --done 命令,不得跳过')
890
+ console.log('- 不要用 mv/rename 重命名变更目录,必须用 `sillyspec change-rename <旧名> <新名>`')
891
+ console.log('- 文档类型文件(.md/.yaml/.json 等)头部必须包含 author(git 用户名)和 created_at(精确到秒)')
892
+ console.log('- 执行构建/测试前必须先读 local.yaml,优先使用其中配置的命令、路径和环境变量;未配置时才使用默认值')
893
+ // 平台模式额外铁律
894
+ if (platformOpts?.specRoot || platformOpts?.runtimeRoot) {
895
+ const specSillyspec = platformOpts.specRoot || join(cwd, '.sillyspec')
896
+ console.log(`- **平台模式:所有文件只能写入 \`${specSillyspec}/\` 下的对应子目录,严禁写入源码目录。**`)
897
+ console.log('- **平台模式:Write 工具失败时,不允许用 cat > / tee / heredoc 等方式绕过。先 Read 再 Write,仍失败则记录并停止。**')
898
+ console.log('- **平台模式:local.yaml 中的 commands 必须在 package.json scripts 中真实存在,不存在的标记 unavailable。**')
899
+ }
900
+ // 路径安全规则:防止 AI 拼错变更目录
901
+ if (changeName) {
902
+ const isPlatform = platformOpts?.specRoot || platformOpts?.runtimeRoot
903
+ const changeDirBase = isPlatform ? platformOpts.specRoot : '.sillyspec'
904
+ const changeDir = join(changeDirBase, 'changes', changeName)
905
+ console.log(`- **文件路径规则:所有变更文件必须写入 \`${changeDir}/\` 目录下。不要自己拼接路径,直接使用 changeDir 值。示例:\`${changeDir}/proposal.md\`**`)
906
+ }
907
+ const changeFlag = changeName ? ` --change ${changeName}` : ''
908
+ // 检测当前 step prompt 是否包含 WAIT 指令(即可能需要等待用户)
909
+ const stepPrompt = promptText || ''
910
+ const requiresWait = step.requiresWait === true
911
+ const conditionalWait = step.conditionalWait === true
912
+ const mayNeedWait = WAIT_MARKER_RE.test(stepPrompt) || requiresWait || conditionalWait
913
+
914
+ console.log(`\n### 完成后执行`)
915
+ if (requiresWait) {
916
+ console.log(`本步骤必须等待用户输入,不能直接 --done:`)
917
+ console.log(`sillyspec run ${stageName} --wait --reason "${step.waitReason || '等待用户输入'}" --options "${(step.waitOptions || ['确认']).join(',')}"${changeFlag} --output "你的问题/方案摘要"`)
918
+ console.log(``)
919
+ console.log(`用户回答后执行:`)
920
+ console.log(`sillyspec run ${stageName} --continue --answer "用户回答"${changeFlag}`)
921
+ console.log(``)
922
+ console.log(`收到回答并完成本步骤总结后,再执行:`)
923
+ } else if (mayNeedWait) {
924
+ console.log(`如果需要用户决策(选择方案/确认设计等):`)
925
+ console.log(`sillyspec run ${stageName} --wait --reason "${step.waitReason || '等待原因'}" --options "${(step.waitOptions || ['选项1', '选项2']).join(',')}"${changeFlag} --output "你的摘要"`)
926
+ console.log(``)
927
+ console.log(`如果不需要用户决策,正常完成:`)
928
+ }
929
+ console.log(`sillyspec run ${stageName} --done${changeFlag} --input "用户原始需求/反馈" --output "你的摘要"`)
930
+ }
931
+
932
+ /**
933
+ * 根据 project 规模计算 scan profile
934
+ * quick: fileCount≤30 && sourceBytes≤80KB && projectCount≤3 → 3 步,0 子代理,5 份文档
935
+ * standard: fileCount≤200 && sourceBytes≤800KB → 压缩步骤,最多 1 子代理
936
+ * deep: 大项目或 --deep → 完整流程
937
+ */
938
+ function computeScanProfile(cwd, platformOpts) {
939
+ // --deep 标志强制 deep
940
+ const flags = process.argv.slice(2)
941
+ if (flags.includes('--deep')) {
942
+ return { mode: 'deep', reason: '用户指定 --deep', maxAgentCalls: 4, maxDocs: 99 }
943
+ }
944
+
945
+ const specDir = platformOpts?.specRoot || join(cwd, '.sillyspec')
946
+ const projectsDir = join(specDir, 'projects')
947
+ let projectCount = 1
948
+ try {
949
+ if (existsSync(projectsDir)) {
950
+ projectCount = readdirSync(projectsDir).filter(f => f.endsWith('.yaml')).length
951
+ }
952
+ } catch {}
953
+
954
+ // 快速估算源码规模
955
+ let fileCount = 0
956
+ let sourceBytes = 0
957
+ try {
958
+ const { execSync } = require('child_process')
959
+ const findCmd = `find "${cwd}" -type f \\( -name '*.js' -o -name '*.ts' -o -name '*.tsx' -o -name '*.py' -o -name '*.java' -o -name '*.go' -o -name '*.rs' -o -name '*.rb' -o -name '*.php' -o -name '*.c' -o -name '*.cpp' -o -name '*.h' -o -name '*.jsx' -o -name '*.vue' -o -name '*.svelte' \\) -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' -not -path '*/build/*' -not -path '*/__pycache__/*' -not -path '*/.sillyspec/*' -not -path '*/.claude/*' 2>/dev/null`
960
+ const files = execSync(findCmd, { encoding: 'utf8', timeout: 10000 }).trim().split('\n').filter(Boolean)
961
+ fileCount = files.length
962
+ for (const f of files) {
963
+ try { sourceBytes += statSync(f).size } catch {}
964
+ }
965
+ } catch {
966
+ // find 失败时假设中等规模
967
+ return { mode: 'standard', reason: '无法估算项目规模', maxAgentCalls: 1, maxDocs: 8 }
968
+ }
969
+
970
+ if (fileCount <= 30 && sourceBytes <= 80_000 && projectCount <= 3) {
971
+ return { mode: 'quick', reason: `${fileCount} 源文件, ${Math.round(sourceBytes / 1024)}KB`, maxAgentCalls: 0, maxDocs: 5, _fileCount: fileCount, _sourceBytes: sourceBytes, _projectCount: projectCount }
972
+ }
973
+ if (fileCount <= 200 && sourceBytes <= 800_000) {
974
+ return { mode: 'standard', reason: `${fileCount} 源文件, ${Math.round(sourceBytes / 1024)}KB`, maxAgentCalls: 1, maxDocs: 8, _fileCount: fileCount, _sourceBytes: sourceBytes, _projectCount: projectCount }
975
+ }
976
+ return { mode: 'deep', reason: `${fileCount} 源文件, ${Math.round(sourceBytes / 1024)}KB`, maxAgentCalls: 4, maxDocs: 99, _fileCount: fileCount, _sourceBytes: sourceBytes, _projectCount: projectCount }
977
+ }
978
+
979
+ /**
980
+ * 根据 scanProfile 裁剪步骤
981
+ * quick: 3 步 — CLI preflight / AI generate / CLI postcheck
982
+ * standard: 跳过续扫检测(4), 跳过可选步骤(9)
983
+ */
984
+ function applyScanProfileSteps(stageData, profile, cwd, platformOpts) {
985
+ const steps = stageData.steps
986
+ const mode = profile.mode
987
+
988
+ if (mode === 'quick') {
989
+ const specBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
990
+ const projectName = basename(cwd)
991
+ const docsRoot = join(specBase, 'docs', projectName)
992
+
993
+ // Step 1: CLI preflight(不调 AI,自动完成)
994
+ const step1 = {
995
+ name: '项目概览(自动探测)',
996
+ status: 'pending',
997
+ noAI: true,
998
+ _cliAction: 'scanPreflight',
999
+ prompt: '',
1000
+ outputHint: 'preflight 结果',
1001
+ optional: false
1002
+ }
1003
+ // Step 2: AI 生成核心文档(唯一 AI roundtrip)
1004
+ const step2 = {
1005
+ name: '生成核心文档',
1006
+ status: 'pending',
1007
+ prompt: `## Quick Scan — 核心文档生成
1008
+
1009
+ 项目规模较小(quick profile),请一次性生成所有核心文档。
1010
+
1011
+ ### 操作
1012
+ 1. 读取项目结构和关键文件(package.json / pyproject.toml / README / 入口文件)
1013
+ 2. 生成以下 4 份文档并写入 \`{DOCS_ROOT}/scan/\`:
1014
+ - **PROJECT.md** — 项目简介、技术栈、模块划分
1015
+ - **ARCHITECTURE.md** — 架构概览、模块关系、技术决策
1016
+ - **CONVENTIONS.md** — 代码风格、框架隐形规则
1017
+ - **STRUCTURE.md** — 目录树 + 模块说明
1018
+ 3. 如发现子项目,注册到 \`{PROJECTS_ROOT}/\` 下
1019
+
1020
+ 每份文档头必须包含 frontmatter:\`author\` 和 \`created_at\`。
1021
+
1022
+ ### ⛔ 硬约束
1023
+ - **严禁使用子代理(Agent/Task 工具)。** 所有文档在一个 turn 内完成。
1024
+ - 不要搜索 .sillyspec/ .claude/ .git/ node_modules/ dist/ build/
1025
+ - --output 只需要列出生成的文件名,不要写长篇总结
1026
+
1027
+ ### 输出
1028
+ 生成的文件列表`,
1029
+ outputHint: '文件列表',
1030
+ optional: false
1031
+ }
1032
+ // Step 3: CLI postcheck(不调 AI,自动完成)
1033
+ const selfCheck = steps.find(s => s.name === '自检和提交') || {
1034
+ name: '自检和提交', status: 'pending', prompt: '', outputHint: '结果', optional: false
1035
+ }
1036
+ const step3 = { ...selfCheck, status: 'pending', noAI: true, _cliAction: 'scanPostcheck', prompt: '' }
1037
+ stageData.steps = [step1, step2, step3]
1038
+ return
1039
+ }
1040
+
1041
+ if (mode === 'standard') {
1042
+ // 跳过 Step 4(断点续扫检测),跳过 Step 9(flows+glossary,可选)
1043
+ const skipNames = ['断点续扫检测', '生成业务流程和术语表(可选)']
1044
+ for (const step of stageData.steps) {
1045
+ if (skipNames.includes(step.name) && step.status === 'pending') {
1046
+ step.status = 'skipped'
1047
+ step.skippedAt = new Date().toLocaleString('zh-CN', { hour12: false })
1048
+ }
1049
+ }
1050
+ }
1051
+ }
1052
+
1053
+ /**
1054
+ * CLI-only: quick scan preflight
1055
+ * 收集项目快照,打印 summary,不调 AI
1056
+ */
1057
+ async function executeScanPreflight(cwd, platformOpts, scanProfile) {
1058
+ const specBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
1059
+ const projectName = basename(cwd)
1060
+ console.log(` 📁 项目: ${projectName}`)
1061
+ console.log(` 📊 Profile: ${scanProfile.mode} (${scanProfile.reason})`)
1062
+ // 快速列出顶层结构
1063
+ try {
1064
+ const { execSync } = await import('child_process')
1065
+ const dirs = execSync(`ls -d */ 2>/dev/null | grep -v node_modules | grep -v '.git' | grep -v '.sillyspec' | grep -v '.claude' | head -20`, { cwd, encoding: 'utf8' }).trim()
1066
+ if (dirs) {
1067
+ console.log(` 📂 目录: ${dirs.split('\n').map(d => d.replace(/\/$/, '')).join(', ')}`)
1068
+ }
1069
+ } catch {}
1070
+ console.log(` ✅ Preflight 完成,准备生成核心文档\n`)
1071
+ }
1072
+
1073
+ /**
1074
+ * CLI-only: quick scan postcheck
1075
+ * 执行文件存在性 + manifest 检查,不调 AI
1076
+ */
1077
+ async function executeScanPostcheck(cwd, platformOpts, scanProfile) {
1078
+ const { runScanPostCheck, printScanPostCheckResult } = await import('./scan-postcheck.js')
1079
+ const specDir = platformOpts?.specRoot || null
1080
+ const result = runScanPostCheck({
1081
+ cwd,
1082
+ specDir,
1083
+ scanMeta: {
1084
+ projectListParsed: true,
1085
+ manifestWritten: undefined,
1086
+ },
1087
+ })
1088
+ printScanPostCheckResult(result)
1089
+ // 写 manifest(如果还没写)
1090
+ if (platformOpts?.specRoot) {
1091
+ try {
1092
+ const { mkdirSync, writeFileSync } = await import('fs')
1093
+ const { join: pJoin, basename: pBasename } = await import('path')
1094
+ const { execSync } = await import('child_process')
1095
+ const manifestDir = platformOpts.specRoot
1096
+ let sourceCommit = null
1097
+ let sourceCommitError = null
1098
+ try {
1099
+ const gitResult = safeGit(cwd, ['rev-parse', 'HEAD'])
1100
+ sourceCommit = gitResult.value
1101
+ sourceCommitError = gitResult.error
1102
+ } catch (e) {
1103
+ sourceCommitError = e.message
1104
+ }
1105
+ mkdirSync(manifestDir, { recursive: true })
1106
+ const manifest = {
1107
+ scan_profile: {
1108
+ mode: scanProfile.mode,
1109
+ file_count: scanProfile._fileCount || 0,
1110
+ source_bytes: scanProfile._sourceBytes || 0,
1111
+ project_count: scanProfile._projectCount || 0,
1112
+ reason: scanProfile.reason,
1113
+ },
1114
+ workspace_id: platformOpts.workspaceId || null,
1115
+ scan_run_id: platformOpts.scanRunId || null,
1116
+ source_commit: sourceCommit,
1117
+ source_commit_error: sourceCommit === null ? (sourceCommitError || 'unknown') : undefined,
1118
+ generated_at: new Date().toISOString(),
1119
+ schema_version: 2,
1120
+ }
1121
+ const manifestPath = pJoin(manifestDir, 'manifest.json')
1122
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
1123
+ console.log(` 📄 manifest.json 已写入: ${manifestPath}`)
1124
+ } catch (e) {
1125
+ console.warn(` ⚠️ manifest 写入失败: ${e.message}`)
1126
+ }
1127
+ }
1128
+ }
1129
+
1130
+ /**
1131
+ * Plan postcheck 的执行代理:委托给 plan-postcheck.js 模块
1132
+ */
1133
+ async function executePlanPostcheck(cwd, platformOpts, progress) {
1134
+ const { executePlanPostcheck: runPostcheck } = await import('./stages/plan-postcheck.js')
1135
+ const { resolveChangeDir } = await import('./modules.js')
1136
+ await runPostcheck({
1137
+ cwd,
1138
+ specRoot: platformOpts?.specRoot,
1139
+ resolveChangeDir,
1140
+ progress
1141
+ })
1142
+ }
1143
+
1144
+ /**
1145
+ * sillyspec run <stage> 主命令
1146
+ */
1147
+ export async function runCommand(args, cwd, specDir = null) {
1148
+ // 解析参数
1149
+ const stageName = args[0]
1150
+ const flags = args.slice(1)
1151
+
1152
+ if (!stageName) {
1153
+ console.error('❌ 请指定阶段,例如: sillyspec run brainstorm')
1154
+ console.error(`可选: ${Object.keys(stageRegistry).join(', ')}, auto`)
1155
+ process.exit(1)
1156
+ }
1157
+
1158
+ if (!stageRegistry[stageName] && stageName !== 'auto') {
1159
+ console.error(`❌ 未知阶段: ${stageName}`)
1160
+ console.error(`可选: ${Object.keys(stageRegistry).join(', ')}, auto`)
1161
+ process.exit(1)
1162
+ }
1163
+
1164
+ // ── cwd 纠正:向上查找真实项目根 ──
1165
+ // 防止多 project 工作区中 cwd 停在子目录(如 backend/)时
1166
+ // 状态写入子目录下误建的 .sillyspec,导致状态分裂
1167
+ if (!specDir) {
1168
+ const resolvedRoot = resolveSpecDir(cwd)
1169
+ if (resolvedRoot && resolvedRoot !== join(cwd, '.sillyspec')) {
1170
+ const realRoot = dirname(resolvedRoot)
1171
+ if (realRoot !== cwd) {
1172
+ cwd = realRoot
1173
+ }
1174
+ }
1175
+ }
1176
+
1177
+ // 平台模式参数(供 SillyHub 等平台调用)
1178
+ // --spec-dir 是统一参数名,--spec-root 保留为向后兼容别名
1179
+ const getFlagValue = (name) => {
1180
+ const idx = flags.indexOf(name)
1181
+ return idx !== -1 && flags[idx + 1] ? flags[idx + 1] : null
1182
+ }
1183
+ const isDone = flags.includes('--done')
1184
+ const isSkip = flags.includes('--skip')
1185
+ const isStatus = flags.includes('--status')
1186
+ const isReset = flags.includes('--reset')
1187
+ const isReopen = flags.includes('--reopen')
1188
+ const fromStepValue = getFlagValue('--from-step')
1189
+ const isConfirm = flags.includes('--confirm')
1190
+ const isSkipApproval = flags.includes('--skip-approval')
1191
+ const isWait = flags.includes('--wait')
1192
+ const isContinue = flags.includes('--continue')
1193
+ const isNonInteractive = flags.includes('--non-interactive')
1194
+ const isInteractive = flags.includes('--interactive')
1195
+ const waitReason = getFlagValue('--reason')
1196
+ const waitOptions = getFlagValue('--options')
1197
+ const continueAnswer = getFlagValue('--answer')
1198
+ const confirmMode = getFlagValue('--confirm-mode')
1199
+ const resolvedSpecDir = specDir || getFlagValue('--spec-dir') || getFlagValue('--spec-root')
1200
+ const platformOpts = {
1201
+ specRoot: resolvedSpecDir ? resolve(resolvedSpecDir) : null,
1202
+ runtimeRoot: getFlagValue('--runtime-root') ? resolve(getFlagValue('--runtime-root')) : null,
1203
+ workspaceId: getFlagValue('--workspace-id'),
1204
+ scanRunId: getFlagValue('--scan-run-id'),
1205
+ }
1206
+
1207
+ // 跨 --done 生命周期:从 metadata 文件恢复 platformOpts
1208
+ // 首次 scan 时写入,所有后续调用(包括 run、--done、--skip)都读取
1209
+ // 优先在 specDir 下查找,否则回退到 cwd/.sillyspec/.runtime/
1210
+ let specRoot = platformOpts.specRoot || resolveSpecDir(cwd)
1211
+ // 平台参数恢复策略:
1212
+ // 1. 优先检查 cwd/.sillyspec-platform.json(轻量指针文件,不污染 .sillyspec 结构)
1213
+ // 2. 然后检查 specRoot/.runtime/platform-scan.json(首次 scan 写入)
1214
+ const platformPointer = join(cwd, '.sillyspec-platform.json')
1215
+ const platformScanFile = join(specRoot, '.runtime', 'platform-scan.json')
1216
+ let platformOptsFile = existsSync(platformPointer) ? platformPointer : platformScanFile
1217
+ let platformFileExists = existsSync(platformOptsFile)
1218
+ // 如果命令行没传 spec-root,尝试从持久化文件恢复
1219
+ if (!platformOpts.specRoot && !platformOpts.runtimeRoot) {
1220
+ if (platformFileExists) {
1221
+ try {
1222
+ const { readFileSync } = await import('fs')
1223
+ const saved = JSON.parse(readFileSync(platformOptsFile, 'utf8'))
1224
+ if (saved.specRoot) platformOpts.specRoot = saved.specRoot
1225
+ if (saved.runtimeRoot) platformOpts.runtimeRoot = saved.runtimeRoot
1226
+ if (saved.workspaceId) platformOpts.workspaceId = saved.workspaceId
1227
+ if (saved.scanRunId) platformOpts.scanRunId = saved.scanRunId
1228
+ // 平台模式 fail-fast:文件存在但缺少 specRoot
1229
+ if (!platformOpts.specRoot && !platformOpts.runtimeRoot) {
1230
+ console.error(`❌ 平台模式参数文件存在但缺少 specRoot/runtimeRoot: ${platformOptsFile}`)
1231
+ console.error(' 可能原因:platform-scan.json 损坏或写入不完整')
1232
+ console.error(' 解决:重新运行首次 scan 并传入 --spec-root')
1233
+ process.exit(1)
1234
+ }
1235
+ // 恢复成功:更新 specRoot(初始值可能是 cwd/.sillyspec,恢复后应为真实 specDir)
1236
+ specRoot = platformOpts.specRoot || specRoot
1237
+ } catch (e) {
1238
+ console.error(`❌ 平台模式参数文件读取失败: ${platformOptsFile}`)
1239
+ console.error(` 错误: ${e.message}`)
1240
+ console.error(' 可能原因:文件损坏')
1241
+ console.error(' 解决:删除该文件并重新运行首次 scan 传入 --spec-root')
1242
+ process.exit(1)
1243
+ }
1244
+ }
1245
+ }
1246
+ // 持久化 platformOpts
1247
+ // 在 specRoot/.runtime/ 写主文件,同时在 cwd/.sillyspec/.runtime/ 写恢复指针
1248
+ if (platformOpts.specRoot || platformOpts.runtimeRoot) {
1249
+ try {
1250
+ const { mkdirSync, writeFileSync } = await import('fs')
1251
+ mkdirSync(join(specRoot, '.runtime'), { recursive: true })
1252
+ writeFileSync(platformOptsFile, JSON.stringify({
1253
+ specRoot: platformOpts.specRoot,
1254
+ runtimeRoot: platformOpts.runtimeRoot,
1255
+ workspaceId: platformOpts.workspaceId,
1256
+ scanRunId: platformOpts.scanRunId,
1257
+ savedAt: new Date().toISOString(),
1258
+ }, null, 2) + '\n')
1259
+ // 恢复指针:在 cwd 下写 .sillyspec-platform.json(不在 .sillyspec 内,不污染源码结构)
1260
+ // 供后续 --done(不带 --spec-root)找到 specDir
1261
+ writeFileSync(join(cwd, '.sillyspec-platform.json'), JSON.stringify({
1262
+ specRoot: platformOpts.specRoot,
1263
+ runtimeRoot: platformOpts.runtimeRoot,
1264
+ workspaceId: platformOpts.workspaceId,
1265
+ scanRunId: platformOpts.scanRunId,
1266
+ savedAt: new Date().toISOString(),
1267
+ }, null, 2) + '\n')
1268
+ } catch {
1269
+ // 静默失败,不影响主流程
1270
+ }
1271
+ }
1272
+
1273
+ // 统一规范基路径:平台模式用 specRoot,本地模式用 cwd/.sillyspec
1274
+ // runCommand 后续所有 .sillyspec/ 操作必须用 specBase
1275
+ const specBase = platformOpts.specRoot || join(cwd, '.sillyspec')
1276
+
1277
+ // 平台模式:清理旧版本残留的 cwd/.sillyspec/(防止源码污染)。
1278
+ // ⚠️ 同 init.js:必须保护真实资产(changes/、projects/、sillyspec.db)。
1279
+ if (platformOpts.specRoot) {
1280
+ const legacyDir = join(cwd, '.sillyspec')
1281
+ if (existsSync(legacyDir)) {
1282
+ let hasChanges = false;
1283
+ try {
1284
+ const cd = join(legacyDir, 'changes');
1285
+ if (existsSync(cd)) hasChanges = readdirSync(cd).length > 0;
1286
+ } catch {}
1287
+ let hasProjects = false;
1288
+ try {
1289
+ const pd = join(legacyDir, 'projects');
1290
+ if (existsSync(pd)) hasProjects = readdirSync(pd).length > 0;
1291
+ } catch {}
1292
+ const hasDb = existsSync(join(legacyDir, 'sillyspec.db'));
1293
+
1294
+ if (hasChanges || hasProjects || hasDb) {
1295
+ console.error('❌ [sillyspec] 拒绝删除源码目录的 .sillyspec/:检测到真实资产。仅清理运行时残留。');
1296
+ for (const residue of ['.runtime', 'local.yaml', 'codebase']) {
1297
+ const p = join(legacyDir, residue);
1298
+ if (existsSync(p)) { try { rmSync(p, { recursive: true, force: true }) } catch {} }
1299
+ }
1300
+ } else {
1301
+ try { rmSync(legacyDir, { recursive: true, force: true }) } catch {}
1302
+ }
1303
+ }
1304
+ }
1305
+
1306
+ // 解析 --output
1307
+ let outputText = null
1308
+ const outputIdx = flags.indexOf('--output')
1309
+ if (outputIdx !== -1 && flags[outputIdx + 1]) {
1310
+ outputText = flags[outputIdx + 1]
1311
+ }
1312
+
1313
+ // 解析 --input
1314
+ let inputText = null
1315
+ const inputIdx = flags.indexOf('--input')
1316
+ if (inputIdx !== -1 && flags[inputIdx + 1]) {
1317
+ inputText = flags[inputIdx + 1]
1318
+ }
1319
+
1320
+ // 解析 --change <name>
1321
+ let changeName = null
1322
+ const changeIdx = flags.indexOf('--change')
1323
+ if (changeIdx !== -1 && flags[changeIdx + 1]) {
1324
+ changeName = flags[changeIdx + 1]
1325
+ }
1326
+
1327
+ // 解析 --files a.js,b.js(quick 专用:显式声明 allowedFiles)
1328
+ let quickFiles = []
1329
+ const filesIdx = flags.indexOf('--files')
1330
+ if (filesIdx !== -1 && flags[filesIdx + 1]) {
1331
+ quickFiles = flags[filesIdx + 1].split(',').map(f => f.trim()).filter(Boolean)
1332
+ }
1333
+
1334
+ const isAllowNew = flags.includes('--allow-new')
1335
+ const isForceBaseline = flags.includes('--force-baseline')
1336
+ const isForceRescan = flags.includes('--force-rescan')
1337
+
1338
+ // 未知参数 fail-fast
1339
+ const knownFlags = new Set([
1340
+ '--done', '--skip', '--status', '--reset', '--confirm', '--skip-approval',
1341
+ '--wait', '--continue', '--non-interactive', '--interactive',
1342
+ '--reason', '--options', '--answer', '--confirm-mode',
1343
+ '--output', '--input', '--change',
1344
+ '--spec-dir', '--spec-root', '--runtime-root', '--workspace-id', '--scan-run-id',
1345
+ '--files', '--allow-new', '--force-baseline', '--force-rescan',
1346
+ '--json', '--dir', '--help',
1347
+ '--reopen', '--from-step', '--mode',
1348
+ ])
1349
+ for (let i = 0; i < flags.length; i++) {
1350
+ const f = flags[i]
1351
+ if (f.startsWith('--')) {
1352
+ if (!knownFlags.has(f)) {
1353
+ console.error(`❌ 未知参数: ${f}`)
1354
+ console.error(`已知参数: ${[...knownFlags].sort().join(', ')}`)
1355
+ process.exit(1)
1356
+ }
1357
+ // 跳过 value 参数
1358
+ i++
1359
+ }
1360
+ }
1361
+
1362
+ const isAuxiliary = auxiliaryStages.includes(stageName)
1363
+ // scan 元数据追踪(存储在 stageData.scanMeta 中,completeStep 通过 progress 访问)
1364
+
1365
+ const pm = new ProgressManager({ specDir: specRoot })
1366
+ let progress = await pm.read(cwd, changeName)
1367
+
1368
+ if (!progress) {
1369
+ // 如果指定了变更名或有变更目录,自动初始化变更的 progress
1370
+ const autoChange = changeName || resolveChangeNameAuto(cwd, specRoot)
1371
+ if (autoChange) {
1372
+ progress = await pm.initChange(cwd, autoChange)
1373
+ } else if (isAuxiliary) {
1374
+ // 辅助阶段(scan/explore/quick/doctor/status)自动使用默认变更名
1375
+ const autoName = changeName || resolveChangeNameAuto(cwd, specRoot) || 'default'
1376
+ changeName = autoName
1377
+ progress = await pm.initChange(cwd, autoName)
1378
+ // initChange 可能因 project 表为空返回 null
1379
+ if (!progress) {
1380
+ progress = { currentStage: stageName, stages: {}, lastActive: new Date().toLocaleString('zh-CN', { hour12: false }), project: '' }
1381
+ }
1382
+ } else {
1383
+ // brainstorm 作为流程入口,自动生成变更名并初始化
1384
+ if (stageName === 'brainstorm') {
1385
+ const date = new Date().toISOString().slice(0, 10)
1386
+ const autoName = `${date}-new-change`
1387
+ console.log(`🔄 自动创建变更:${autoName}`)
1388
+ console.log(` 提示:可以用 --change <名称> 指定自定义变更名`)
1389
+ console.log(` 或事后重命名:sillyspec change-rename ${autoName} <新名称>`)
1390
+ progress = await pm.initChange(cwd, autoName)
1391
+ changeName = autoName
1392
+ } else {
1393
+ console.error('❌ 未找到进度数据,请先运行 sillyspec init 或指定 --change <变更名>')
1394
+ process.exit(1)
1395
+ }
1396
+ }
1397
+ }
1398
+
1399
+ // 确保 progress 有 currentChange
1400
+ const effectiveChange = changeName || progress.currentChange || resolveChangeName(cwd, progress, specRoot)
1401
+
1402
+ // -- auto 模式:自动推进所有流程阶段
1403
+ if (stageName === 'auto') {
1404
+ return await runAutoMode(pm, progress, cwd, flags, effectiveChange, platformOpts)
1405
+ }
1406
+
1407
+ // --change 只作为变更名标识,不再拦截流程
1408
+ // 注册变更到全局活跃列表(如果尚未注册)
1409
+ if (effectiveChange) {
1410
+ await pm.registerChange(cwd, effectiveChange)
1411
+ }
1412
+
1413
+ // --reset
1414
+ if (isReset) {
1415
+ return await resetStage(pm, progress, stageName, cwd, effectiveChange, platformOpts)
1416
+ }
1417
+
1418
+ // ── 规则 1:completed 阶段直接 run,拒绝(但 --status 放行)──
1419
+ const stageStatus = progress.stages[stageName]?.status
1420
+ if (stageStatus === 'completed' && !isReopen && !isStatus) {
1421
+ console.error(`\n❌ ${stageName} 阶段已完成。`)
1422
+ console.error(` 使用 --reopen 进行修订,或 --reset 从头开始。`)
1423
+ console.error(` 修订示例: sillyspec run ${stageName} --reopen --from-step <步骤序号或名称>`)
1424
+ process.exit(1)
1425
+ }
1426
+
1427
+ // ── 规则 5:stale 阶段直接 run,拒绝(但 --status / --reset 放行)──
1428
+ if (stageStatus === 'stale' && !isReopen && !isStatus && !isReset) {
1429
+ const staleReason = progress.stages[stageName]?.staleReason || '上游阶段已修订'
1430
+ console.error(`\n⚠️ ${stageName} 阶段已失效(stale)。`)
1431
+ console.error(` 原因:${staleReason}`)
1432
+ console.error(` 使用 --reopen --from-step <步骤> 进行修订,或 --reset 从头开始。`)
1433
+ process.exit(1)
1434
+ }
1435
+
1436
+ // ── --reopen 处理 ──
1437
+ if (isReopen) {
1438
+ // stale/revising 阶段可能 steps 为空,或者 execute 阶段的 steps 需要从最新 plan.md 刷新
1439
+ const stageDataPre = progress.stages[stageName]
1440
+ const needsInit = !stageDataPre || !stageDataPre.steps || stageDataPre.steps.length === 0
1441
+ // execute 阶段在 reopen 时需要从最新 plan.md 重新解析 steps(plan 可能已变更)
1442
+ if (needsInit || stageName === 'execute') {
1443
+ const freshSteps = await getStageSteps(stageName, cwd, progress, specRoot)
1444
+ if (freshSteps && freshSteps.length > 0) {
1445
+ if (!progress.stages[stageName]) progress.stages[stageName] = { status: 'stale', steps: [] }
1446
+ progress.stages[stageName].steps = freshSteps.map(s => ({ name: s.name, status: 'pending' }))
1447
+ await pm._write(cwd, progress, effectiveChange)
1448
+ progress = await pm.read(cwd, effectiveChange) || progress
1449
+ }
1450
+ }
1451
+
1452
+ const result = await pm.reopenStage(cwd, stageName, {
1453
+ fromStep: fromStepValue,
1454
+ changeName: effectiveChange,
1455
+ })
1456
+ if (!result.ok) {
1457
+ console.error(`\n❌ ${result.error}`)
1458
+ if (stageStatus === 'completed') {
1459
+ console.error(`\n 提示:sillyspec run ${stageName} --reopen --from-step <步骤序号或名称>`)
1460
+ }
1461
+ process.exit(1)
1462
+ }
1463
+ console.log(`\n🔧 ${stageName} 阶段已重新打开(revision ${result.revision})`)
1464
+ console.log(` 从步骤「${result.fromStep}」开始修订`)
1465
+ console.log(` 该步骤及之后的产出需要重新生成。`)
1466
+ if (stageName === 'execute') console.log(` ⚡ execute 步骤已从最新 plan.md 重新解析。`)
1467
+ console.log('')
1468
+
1469
+ // 重新读取 progress
1470
+ progress = await pm.read(cwd, effectiveChange) || progress
1471
+
1472
+ // 注入 revision context 到 platformOpts,供 outputStep 使用
1473
+ const stageData = progress.stages[stageName]
1474
+ if (stageData && stageData.revision > 0) {
1475
+ platformOpts._revision = {
1476
+ revision: stageData.revision,
1477
+ fromStep: stageData.reopenedFromStep,
1478
+ }
1479
+ }
1480
+ } else {
1481
+ // 非 reopen 的正常执行:如果阶段处于 revising 状态,也注入 revision context
1482
+ const revStageData = progress.stages[stageName]
1483
+ if (revStageData && revStageData.status === 'revising' && revStageData.revision > 0 && !platformOpts._revision) {
1484
+ platformOpts._revision = {
1485
+ revision: revStageData.revision,
1486
+ fromStep: revStageData.reopenedFromStep,
1487
+ }
1488
+ }
1489
+ }
1490
+
1491
+ // 确保步骤已初始化
1492
+ const changed = await ensureStageSteps(progress, stageName, cwd, specRoot)
1493
+ if (changed && effectiveChange) {
1494
+ await pm._write(cwd, progress, effectiveChange)
1495
+ triggerSync(cwd, effectiveChange, platformOpts)
1496
+ progress = await pm.read(cwd, effectiveChange) || progress
1497
+ }
1498
+
1499
+ // --status
1500
+ if (isStatus) {
1501
+ return showStatus(progress, stageName)
1502
+ }
1503
+
1504
+ // --skip
1505
+ if (isSkip) {
1506
+ return await skipStep(pm, progress, stageName, cwd, effectiveChange)
1507
+ }
1508
+
1509
+ // --wait: 将 step 设为 waiting(独立于 --done)
1510
+ if (isWait) {
1511
+ return await waitStep(pm, progress, stageName, cwd, outputText, waitReason, waitOptions, { changeName: effectiveChange, nonInteractive: isNonInteractive && !isInteractive, platformOpts })
1512
+ }
1513
+
1514
+ // --continue: 从 waiting 恢复
1515
+ if (isContinue) {
1516
+ return await continueStep(pm, progress, stageName, cwd, continueAnswer, { changeName: effectiveChange, nonInteractive: isNonInteractive && !isInteractive, platformOpts })
1517
+ }
1518
+
1519
+ // --done
1520
+ if (isDone) {
1521
+ const doneAnswer = getFlagValue('--answer')
1522
+ return await completeStep(pm, progress, stageName, cwd, outputText, inputText, { confirm: isConfirm, changeName: effectiveChange, nonInteractive: isNonInteractive && !isInteractive, platformOpts, confirmMode, doneAnswer })
1523
+ }
1524
+
1525
+ // 默认:输出当前步骤
1526
+ return await runStage(pm, progress, stageName, cwd, effectiveChange, isSkipApproval, platformOpts, { quickFiles, isAllowNew, isForceBaseline, isForceRescan })
1527
+ }
1528
+
1529
+ /**
1530
+ * 自动推导变更名(不依赖 progress)
1531
+ */
1532
+ function resolveChangeNameAuto(cwd, specDir = null) {
1533
+ const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
1534
+ if (!existsSync(changesDir)) return null
1535
+ const entries = readdirSync(changesDir, { withFileTypes: true })
1536
+ .filter(e => e.isDirectory() && e.name !== 'archive')
1537
+ if (entries.length === 1) return entries[0].name
1538
+ return null
1539
+ }
1540
+
1541
+ async function runStage(pm, progress, stageName, cwd, changeName, skipApproval = false, platformOpts = {}, quickOpts = {}) {
1542
+ const specBase = platformOpts.specRoot || join(cwd, '.sillyspec')
1543
+ // 状态转换校验
1544
+ const prevStage = progress.currentStage || ''
1545
+ // task-07: 提取 prevStage 的 stageData,传给 checkTransition 检测 failed_post_check 门控
1546
+ const fromStageData = (progress.stages && prevStage && progress.stages[prevStage]) || undefined
1547
+ const transition = checkTransition(prevStage, stageName, fromStageData ? { fromStageData } : {})
1548
+ if (!transition.allowed) {
1549
+ console.error(`❌ 阶段转换不允许: ${prevStage || '(起始)'} → ${stageName}`)
1550
+ console.error(` 原因: ${transition.reason}`)
1551
+ console.error(` 提示: 使用 --skip-approval 绕过(需明确意图)`)
1552
+ if (!skipApproval) {
1553
+ process.exit(1)
1554
+ }
1555
+ }
1556
+
1557
+ // execute 阶段启动前检查审批
1558
+ if (stageName === 'execute' && !skipApproval) {
1559
+ const approval = await checkApproval(cwd, changeName, platformOpts)
1560
+ if (approval) {
1561
+ if (approval.status === 'rejected') {
1562
+ console.error(`❌ 变更 ${changeName} 的执行已被拒绝:${approval.reason || '无原因'}`)
1563
+ process.exit(1)
1564
+ }
1565
+ if (approval.status === 'pending') {
1566
+ console.log(`⏳ 变更 ${changeName} 的执行审批待处理中...`)
1567
+ console.log(' 提示:使用 --skip-approval 跳过审批检查')
1568
+ }
1569
+ }
1570
+ }
1571
+
1572
+ // execute 阶段:CLI 自动创建 worktree(不等 AI agent)
1573
+ if (stageName === 'execute' && changeName) {
1574
+ const effectiveChange = changeName
1575
+ const { WorktreeManager } = await import('./worktree.js')
1576
+ const wm = new WorktreeManager({ cwd })
1577
+ const existingMeta = wm.getMeta(effectiveChange)
1578
+ if (existingMeta) {
1579
+ console.log(`🔗 worktree 已存在: ${existingMeta.worktreePath} (${existingMeta.mode})`)
1580
+ } else {
1581
+ try {
1582
+ const result = wm.create(effectiveChange)
1583
+ console.log(`🔗 worktree 已创建: ${result.worktreePath} (分支: ${result.branch}, 模式: ${result.mode})`)
1584
+ } catch (e) {
1585
+ console.error(`❌ worktree 创建失败: ${e.message}`)
1586
+ console.error(` 继续执行前请解决上述问题,或使用 --no-worktree 跳过。`)
1587
+ process.exit(1)
1588
+ }
1589
+ }
1590
+ // 入口 deps 自检(D-002):已存在 worktree(create short-circuit 不供给)时重供给
1591
+ if (existingMeta) {
1592
+ const execSpecBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
1593
+ await ensureDepsFreshness(cwd, effectiveChange, execSpecBase, existingMeta)
1594
+ }
1595
+ }
1596
+
1597
+ // ── execute 阶段启动时固定 executeRunId(绑定变更名,避免跨变更复用) ──
1598
+ let currentExecuteRunId = null
1599
+ if (stageName === 'execute') {
1600
+ const { generateExecuteRunId } = await import('./task-review.js')
1601
+ const execSpecBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
1602
+ const runtimeRoot = join(execSpecBase, '.runtime')
1603
+ const runIdFile = join(runtimeRoot, `current-execute-run-id-${changeName}`)
1604
+ mkdirSync(runtimeRoot, { recursive: true })
1605
+ // 优先读取已有的变更专属标记文件
1606
+ try {
1607
+ if (existsSync(runIdFile)) {
1608
+ currentExecuteRunId = readFileSync(runIdFile, 'utf8').trim()
1609
+ }
1610
+ } catch {}
1611
+ if (!currentExecuteRunId) {
1612
+ currentExecuteRunId = generateExecuteRunId()
1613
+ writeFileSync(runIdFile, currentExecuteRunId + '\n')
1614
+ }
1615
+ }
1616
+
1617
+ // 自动探测 currentChange
1618
+ if (autoDetectChange(progress, cwd)) {
1619
+ progress.lastActive = new Date().toLocaleString('zh-CN', { hour12: false })
1620
+ await pm._write(cwd, progress, changeName)
1621
+ triggerSync(cwd, changeName, platformOpts)
1622
+ }
1623
+
1624
+ const stageData = progress.stages[stageName]
1625
+ if (!stageData || !stageData.steps) {
1626
+ console.error(`❌ 阶段 ${stageName} 未初始化`)
1627
+ process.exit(1)
1628
+ }
1629
+
1630
+ // 用户显式调用 sillyspec run <stage>:把它标记为当前阶段
1631
+ if (progress.currentStage !== stageName) {
1632
+ progress.currentStage = stageName
1633
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
1634
+ await pm._write(cwd, progress, changeName)
1635
+ triggerSync(cwd, changeName, platformOpts)
1636
+ }
1637
+
1638
+ const steps = stageData.steps
1639
+ // ── 检查是否有 waiting step 需要先处理 ──
1640
+ const waitingIdx = steps.findIndex(s => s.status === 'waiting')
1641
+ if (waitingIdx !== -1) {
1642
+ const ws = steps[waitingIdx]
1643
+ console.error(`\n⏸️ Step ${waitingIdx + 1}/${steps.length} 正在等待用户输入:${ws.name}`)
1644
+ if (ws.waitReason) console.error(` 原因:${ws.waitReason}`)
1645
+ if (ws.waitOptions) console.error(` 选项:${formatWaitOptions(ws.waitOptions)}`)
1646
+ console.error(`\n 普通运行无法跳过等待中的步骤。请先处理:`)
1647
+ console.error(` sillyspec run ${stageName} --continue --answer "你的选择"${changeName ? ` --change ${changeName}` : ''}`)
1648
+ process.exit(1)
1649
+ }
1650
+
1651
+ let currentIdx = steps.findIndex(s => s.status !== 'completed' && s.status !== 'skipped')
1652
+
1653
+ // stale 步骤视为可执行(等同于 pending)
1654
+ if (currentIdx !== -1 && steps[currentIdx].status === 'stale') {
1655
+ steps[currentIdx].status = 'pending'
1656
+ await pm._write(cwd, progress, changeName)
1657
+ triggerSync(cwd, changeName, platformOpts)
1658
+ }
1659
+
1660
+ // ── scanProfile: 根据 project 规模动态裁剪步骤 ──
1661
+ let scanProfile = null
1662
+ if (stageName === 'scan' && steps.length > 0 && currentIdx === 0) {
1663
+ scanProfile = computeScanProfile(cwd, platformOpts)
1664
+ console.log(`\n📊 Scan Profile: ${scanProfile.mode} (原因: ${scanProfile.reason})`)
1665
+ if (scanProfile.mode !== 'deep') {
1666
+ applyScanProfileSteps(stageData, scanProfile, cwd, platformOpts)
1667
+ // 步骤被裁剪后 currentIdx 需要重新计算
1668
+ currentIdx = 0
1669
+ }
1670
+ // 保存 profile 供后续 postcheck 使用
1671
+ stageData.scanProfile = scanProfile
1672
+ await pm._write(cwd, progress, changeName)
1673
+ } else if (stageName === 'scan' && stageData.scanProfile) {
1674
+ scanProfile = stageData.scanProfile
1675
+ }
1676
+ if (scanProfile) platformOpts.scanProfile = scanProfile
1677
+
1678
+ if (stageName === 'scan') {
1679
+ try {
1680
+ const gitResult = safeGit(cwd, ['rev-parse', 'HEAD'])
1681
+ const scanGuard = {
1682
+ sourceCommit: gitResult.value,
1683
+ sourceCommitError: gitResult.error,
1684
+ startedAt: new Date().toISOString(),
1685
+ forceRescan: quickOpts?.isForceRescan || false,
1686
+ }
1687
+ const guardFile = join(specBase, '.runtime', 'scan-guard.json')
1688
+ mkdirSync(dirname(guardFile), { recursive: true })
1689
+ writeFileSync(guardFile, JSON.stringify(scanGuard, null, 2) + '\n')
1690
+ if (scanGuard.forceRescan) {
1691
+ console.log('🛡️ scan 覆盖保护已记录: --force-rescan 已开启')
1692
+ } else {
1693
+ console.log('🛡️ scan 覆盖保护已记录: existing scan docs require current source_commit/updated_at')
1694
+ }
1695
+ } catch (e) {
1696
+ console.warn(`⚠️ scan 覆盖保护记录失败: ${e.message}`)
1697
+ }
1698
+ }
1699
+
1700
+ if (currentIdx === -1) {
1701
+ // 已完成 → 自动重置,重新开始
1702
+ const freshSteps = await getStageSteps(stageName, cwd, progress, platformOpts?.specRoot || null)
1703
+ stageData.steps = freshSteps
1704
+ ? freshSteps.map(s => ({ name: s.name, status: 'pending' }))
1705
+ : []
1706
+ stageData.status = 'in-progress'
1707
+ stageData.startedAt = new Date().toLocaleString('zh-CN', { hour12: false })
1708
+ stageData.completedAt = null
1709
+ await pm._write(cwd, progress, changeName)
1710
+ triggerSync(cwd, changeName, platformOpts)
1711
+ currentIdx = 0
1712
+ console.log(`🔄 ${stageName} 阶段已自动重置,重新开始。\n`)
1713
+ }
1714
+
1715
+ // quick 阶段:记录 baselineFiles
1716
+ if (stageName === 'quick' && !progress.quickGuard) {
1717
+ try {
1718
+ const { execSync } = await import('child_process')
1719
+ const gitStatus = execSync('git status --porcelain', { cwd, encoding: 'utf8', timeout: 10000 })
1720
+ const baselineFiles = gitStatus
1721
+ .trim().split('\n').filter(Boolean)
1722
+ .map(line => line.slice(3).trim())
1723
+ .filter(f => !f.startsWith('.sillyspec/'))
1724
+ const allowedFiles = quickOpts?.quickFiles || []
1725
+ const allowNew = quickOpts?.isAllowNew || false
1726
+ const forceBaseline = quickOpts?.isForceBaseline || false
1727
+ progress.quickGuard = {
1728
+ baselineCommit: safeGit(cwd, ['rev-parse', 'HEAD']).value,
1729
+ baselineFiles,
1730
+ allowedFiles,
1731
+ allowNew,
1732
+ forceBaseline,
1733
+ startedAt: new Date().toISOString(),
1734
+ }
1735
+ // 写入 quick-guard.json 供 worktree-guard hook 读取
1736
+ const guardFile = join(specBase, '.runtime', 'quick-guard.json')
1737
+ writeFileSync(guardFile, JSON.stringify(progress.quickGuard, null, 2))
1738
+ const parts = [`${baselineFiles.length} 个已有脏文件`]
1739
+ if (allowedFiles.length > 0) parts.push(`${allowedFiles.length} 个 allowedFiles`)
1740
+ if (allowNew) parts.push('允许新增文件')
1741
+ console.log(`🛡️ quick 变更边界已记录: ${parts.join(', ')}`)
1742
+ await pm._write(cwd, progress, changeName)
1743
+ } catch (e) {
1744
+ console.warn(`⚠️ baseline 记录失败: ${e.message}`)
1745
+ }
1746
+ }
1747
+
1748
+ if (currentIdx > 0) {
1749
+ const completed = currentIdx
1750
+ const total = steps.length
1751
+ console.log(`⚠️ ${stageName} 已进行到第 ${currentIdx + 1}/${total} 步(前 ${completed} 步已完成)。`)
1752
+ console.log(` 继续执行将从中断处恢复,用 --reset 可重新开始。\n`)
1753
+ }
1754
+
1755
+ // ── Brainstorm → Plan Contract:plan 启动前校验 design.md ──
1756
+ if (stageName === 'plan' && currentIdx === 0) {
1757
+ const changeDir = resolveChangeDir(cwd, progress, platformOpts?.specRoot || null)
1758
+ const designPath = changeDir ? join(changeDir, 'design.md') : null
1759
+ if (designPath && existsSync(designPath)) {
1760
+ const { validateDesignForPlan } = await import('./stages/plan.js')
1761
+ const designContent = readFileSync(designPath, 'utf8')
1762
+ const designValidation = validateDesignForPlan(designContent)
1763
+ if (!designValidation.ok) {
1764
+ console.error(`\n❌ Brainstorm → Plan Contract 校验失败:`)
1765
+ for (const err of designValidation.errors) console.error(` - ${err}`)
1766
+ console.error(`\n design.md 不满足 plan 契约,请先修复后重试。`)
1767
+ console.error(` 提示:sillyspec run brainstorm --reopen --from-step <步骤> 修订设计文档`)
1768
+ process.exit(1)
1769
+ }
1770
+ if (designValidation.warnings.length > 0) {
1771
+ console.log(`⚠️ Design contract 警告(不阻断):`)
1772
+ for (const w of designValidation.warnings) console.log(` - ${w}`)
1773
+ console.log()
1774
+ }
1775
+ }
1776
+ }
1777
+
1778
+ const defSteps = await getStageSteps(stageName, cwd, progress, platformOpts?.specRoot || null)
1779
+ if (defSteps && defSteps[currentIdx]) {
1780
+ // noAI 步骤自动完成(CLI-only,不需要 Agent 参与)
1781
+ if (defSteps[currentIdx].noAI || stageData.steps[currentIdx]?.noAI) {
1782
+ const stepName = defSteps[currentIdx].name
1783
+ const cliAction = defSteps[currentIdx]._cliAction || stageData.steps[currentIdx]?._cliAction
1784
+ console.log(`⚙️ Step ${currentIdx + 1}/${stageData.steps.length}: ${stepName}(CLI 自动执行,无需 Agent)`)
1785
+ if (cliAction === 'scanPreflight') {
1786
+ await executeScanPreflight(cwd, platformOpts, scanProfile)
1787
+ } else if (cliAction === 'scanPostcheck') {
1788
+ await executeScanPostcheck(cwd, platformOpts, scanProfile)
1789
+ } else if (cliAction === 'planPostcheck') {
1790
+ await executePlanPostcheck(cwd, platformOpts, progress)
1791
+ }
1792
+ stageData.steps[currentIdx].status = 'completed'
1793
+ stageData.steps[currentIdx].completedAt = new Date().toLocaleString('zh-CN', { hour12: false })
1794
+ await pm._write(cwd, progress, changeName)
1795
+ // 自动前进到下一步
1796
+ const nextIdx = stageData.steps.findIndex(s => s.status === 'pending' || s.status === 'in-progress')
1797
+ if (nextIdx !== -1 && defSteps[nextIdx]) {
1798
+ console.log('')
1799
+ await outputStep(stageName, nextIdx, defSteps, cwd, changeName, progress.project || null, platformOpts)
1800
+ } else {
1801
+ // 所有步骤完成
1802
+ stageData.status = 'completed'
1803
+ stageData.completedAt = new Date().toLocaleString('zh-CN', { hour12: false })
1804
+ await pm._write(cwd, progress, changeName)
1805
+ console.log(`\n✅ ${stageName} 阶段全部完成。`)
1806
+ }
1807
+ return
1808
+ }
1809
+ await outputStep(stageName, currentIdx, defSteps, cwd, changeName, progress.project || null, platformOpts)
1810
+ }
1811
+ }
1812
+
1813
+ function validateMetadata(cwd, stageName, specBase) {
1814
+ const changesDir = join(specBase, 'changes')
1815
+ if (!existsSync(changesDir)) return
1816
+
1817
+ const cutoff = Date.now() - 10 * 60 * 1000
1818
+ const missing = []
1819
+
1820
+ function walk(dir) {
1821
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1822
+ const full = join(dir, entry.name)
1823
+ try {
1824
+ if (entry.isDirectory()) { walk(full); continue }
1825
+ if (!/\.(md|yaml|yml)$/.test(entry.name)) continue
1826
+ const mtime = statSync(full).mtimeMs
1827
+ if (mtime < cutoff) continue
1828
+ const content = readFileSync(full, 'utf-8')
1829
+ if (!content.includes('author:') && !content.includes('author:')) missing.push(full)
1830
+ if (!content.includes('created_at:') && !content.includes('created_at:')) missing.push(full)
1831
+ } catch (e) { /* skip unreadable files */ }
1832
+ }
1833
+ }
1834
+
1835
+ walk(changesDir)
1836
+ const unique = [...new Set(missing)]
1837
+ if (unique.length > 0) {
1838
+ console.log(`\n⚠️ 以下文件缺少 author 或 created_at 元数据:`)
1839
+ unique.forEach(f => console.log(` - ${f.replace(cwd + '/', '')}`))
1840
+ console.log('请在文件头部添加 author(git 用户名)和 created_at(精确到秒)')
1841
+ }
1842
+ }
1843
+
1844
+ /**
1845
+ * 验证关键文件是否存在于正确的变更目录下
1846
+ * 防止 AI 将文件写到错误的路径
1847
+ */
1848
+ function validateFileLocations(cwd, stageName, progress, changeName, specBase) {
1849
+ const effectiveChange = changeName || progress.currentChange
1850
+ if (!effectiveChange) return
1851
+
1852
+ const changeDir = join(specBase, 'changes', effectiveChange)
1853
+ if (!existsSync(changeDir)) return
1854
+
1855
+ // 每个阶段完成后预期存在的文件
1856
+ const expectedFiles = {
1857
+ brainstorm: ['design.md', 'proposal.md', 'requirements.md', 'tasks.md'],
1858
+ plan: ['plan.md'],
1859
+ archive: ['module-impact.md'],
1860
+ }
1861
+
1862
+ const expected = expectedFiles[stageName]
1863
+ if (!expected) return
1864
+
1865
+ const missing = []
1866
+ for (const file of expected) {
1867
+ if (!existsSync(join(changeDir, file))) {
1868
+ missing.push(file)
1869
+ }
1870
+ }
1871
+
1872
+ if (missing.length > 0) {
1873
+ console.log(`\n⚠️ 文件位置验证:以下文件未在变更目录中找到`)
1874
+ console.log(` 变更目录:${changeDir.replace(cwd + '/', '')}/`)
1875
+ for (const f of missing) {
1876
+ // 检查是否写到了错误的位置
1877
+ const wrongPath = join(specBase, 'changes', 'change', effectiveChange, f)
1878
+ if (existsSync(wrongPath)) {
1879
+ console.log(` ❌ ${f} — 不存在,但发现了错误路径:${wrongPath.replace(cwd + '/', '')}`)
1880
+ console.log(` 提示:应该写入 ${changeDir.replace(cwd + '/', '')}/${f}`)
1881
+ } else {
1882
+ console.log(` ⬜ ${f} — 未找到(该阶段可能未产出此文件)`)
1883
+ }
1884
+ }
1885
+ } else {
1886
+ console.log(`\n✅ 文件位置验证:所有 ${expected.length} 个预期文件均在变更目录中`)
1887
+ }
1888
+ }
1889
+
1890
+ async function archiveChangeDirectory(pm, cwd, progress, specBase) {
1891
+ const { renameSync } = await import('fs')
1892
+ const archiveChangeName = progress.currentChange
1893
+ if (!archiveChangeName) {
1894
+ console.error('❌ 归档失败:未找到当前变更名(currentChange)')
1895
+ process.exit(1)
1896
+ }
1897
+ const changesDir = join(specBase, 'changes')
1898
+ const archiveDir = join(changesDir, 'archive')
1899
+ const srcDir = join(changesDir, archiveChangeName)
1900
+ const date = new Date().toISOString().slice(0, 10)
1901
+ const destDir = join(archiveDir, `${date}-${archiveChangeName}`)
1902
+
1903
+ if (!existsSync(srcDir)) {
1904
+ console.error(`❌ 归档失败:源目录不存在 ${srcDir}`)
1905
+ process.exit(1)
1906
+ }
1907
+ if (existsSync(destDir)) {
1908
+ console.error(`❌ 归档失败:目标目录已存在 ${destDir}`)
1909
+ process.exit(1)
1910
+ }
1911
+ mkdirSync(archiveDir, { recursive: true })
1912
+ renameSync(srcDir, destDir)
1913
+
1914
+ if (!existsSync(destDir) || existsSync(srcDir)) {
1915
+ console.error('❌ 归档校验失败:移动操作异常')
1916
+ process.exit(1)
1917
+ }
1918
+
1919
+ await pm.unregisterChange(cwd, archiveChangeName)
1920
+ console.log(`📦 已归档:${archiveChangeName} → archive/${date}-${archiveChangeName}/`)
1921
+ }
1922
+
1923
+ // ── Wait Step ──
1924
+
1925
+ async function waitStep(pm, progress, stageName, cwd, outputText, waitReason, waitOptions, options = {}) {
1926
+ const { changeName, nonInteractive = false, platformOpts = {} } = options
1927
+ const specBase = platformOpts.specRoot || join(cwd, '.sillyspec')
1928
+ const stageData = progress.stages[stageName]
1929
+
1930
+ if (!stageData || !stageData.steps) {
1931
+ console.error(`❌ 阶段 ${stageName} 未初始化`)
1932
+ process.exit(1)
1933
+ }
1934
+
1935
+ // 查找下一个 pending 或 in-progress 的步骤
1936
+ const currentIdx = stageData.steps.findIndex(s => s.status === 'pending' || s.status === 'in-progress')
1937
+ if (currentIdx === -1) {
1938
+ console.error('没有可以等待的步骤')
1939
+ process.exit(1)
1940
+ }
1941
+
1942
+ // 前置检查:不允许已有 waiting 步骤时再 --wait
1943
+ const existingWaitingIdx = stageData.steps.findIndex(s => s.status === 'waiting')
1944
+ if (existingWaitingIdx !== -1) {
1945
+ const ws = stageData.steps[existingWaitingIdx]
1946
+ console.error(`❌ 已有步骤处于等待状态:Step ${existingWaitingIdx + 1} "${ws.name}"`)
1947
+ console.error(` 请先 --continue 或 --reset 该步骤,再开始新的 --wait`)
1948
+ process.exit(1)
1949
+ }
1950
+
1951
+ // maxWaitRounds 硬上限:达到后拒绝继续 --wait
1952
+ const currentStep = stageData.steps[currentIdx]
1953
+ const defSteps = await getStageSteps(stageName, cwd, progress, platformOpts?.specRoot || null)
1954
+ const stepDef = defSteps?.[currentIdx] || {}
1955
+ const maxWaitRounds = currentStep.maxWaitRounds ?? stepDef.maxWaitRounds
1956
+ const currentWaitRound = currentStep.waitRound || 0
1957
+ if (maxWaitRounds && currentWaitRound >= maxWaitRounds) {
1958
+ console.error(`❌ Step "${currentStep.name}" 已达到最大等待轮次(maxWaitRounds=${maxWaitRounds})`)
1959
+ console.error(` 请基于已有回答完成本步骤:`)
1960
+ console.error(` sillyspec run ${stageName} --done${changeName ? ` --change ${changeName}` : ''} --output "需求理解摘要"`)
1961
+ process.exit(1)
1962
+ }
1963
+
1964
+ // 非交互模式下拒绝等待
1965
+ if (nonInteractive) {
1966
+ console.error(`❌ Human decision required in non-interactive mode.`)
1967
+ console.error(` Reason: ${waitReason || '(unknown)'}`)
1968
+ if (waitOptions) console.error(` Options: ${formatWaitOptions(waitOptions)}`)
1969
+ console.error(` Fix: rerun with --interactive or provide decision via sillyspec run ${stageName} --continue --answer "..."`)
1970
+ process.exit(2)
1971
+ }
1972
+
1973
+ const now = new Date().toLocaleString('zh-CN', { hour12: false })
1974
+ stageData.steps[currentIdx].status = 'waiting'
1975
+ stageData.steps[currentIdx].waitedAt = now
1976
+ if (outputText) {
1977
+ const MAX_OUTPUT = 200
1978
+ stageData.steps[currentIdx].output = outputText.length > MAX_OUTPUT
1979
+ ? outputText.slice(0, MAX_OUTPUT) + '…' : outputText
1980
+ }
1981
+ if (waitReason) stageData.steps[currentIdx].waitReason = waitReason
1982
+ if (waitOptions) {
1983
+ // 统一存为 JSON 数组
1984
+ try {
1985
+ const parsed = JSON.parse(waitOptions)
1986
+ if (Array.isArray(parsed)) {
1987
+ stageData.steps[currentIdx].waitOptions = JSON.stringify(parsed)
1988
+ } else {
1989
+ stageData.steps[currentIdx].waitOptions = JSON.stringify(waitOptions.split(',').map(o => o.trim()))
1990
+ }
1991
+ } catch {
1992
+ stageData.steps[currentIdx].waitOptions = JSON.stringify(waitOptions.split(',').map(o => o.trim()))
1993
+ }
1994
+ }
1995
+
1996
+ progress.lastActive = now
1997
+ await pm._write(cwd, progress, changeName)
1998
+ triggerSync(cwd, changeName, platformOpts)
1999
+
2000
+ console.log(`⏸️ Step ${currentIdx + 1}/${stageData.steps.length} 已暂停等待:${stageData.steps[currentIdx].name}`)
2001
+ if (waitReason) console.log(` 原因:${waitReason}`)
2002
+ if (waitOptions) console.log(` 选项:${formatWaitOptions(waitOptions)}`)
2003
+ console.log(` 继续时执行:sillyspec run ${stageName} --continue --answer "你的选择"${changeName ? ` --change ${changeName}` : ''}`)
2004
+ }
2005
+
2006
+ // ── Continue Step ──
2007
+
2008
+ async function continueStep(pm, progress, stageName, cwd, answer, options = {}) {
2009
+ const { changeName, platformOpts = {} } = options
2010
+ const specBase = platformOpts.specRoot || join(cwd, '.sillyspec')
2011
+ const stageData = progress.stages[stageName]
2012
+
2013
+ if (!stageData || !stageData.steps) {
2014
+ console.error(`❌ 阶段 ${stageName} 未初始化`)
2015
+ process.exit(1)
2016
+ }
2017
+
2018
+ if (!answer) {
2019
+ console.error('❌ --continue 需要 --answer 参数')
2020
+ process.exit(1)
2021
+ }
2022
+
2023
+ // 查找 waiting 的步骤
2024
+ const waitingSteps = stageData.steps.map((s, i) => ({ ...s, idx: i })).filter(s => s.status === 'waiting')
2025
+ if (waitingSteps.length === 0) {
2026
+ console.error('没有处于等待状态的步骤')
2027
+ process.exit(1)
2028
+ }
2029
+ if (waitingSteps.length > 1) {
2030
+ console.error(`❌ 检测到 ${waitingSteps.length} 个等待中的步骤,无法确定恢复目标:`)
2031
+ for (const ws of waitingSteps) {
2032
+ console.error(` Step ${ws.idx + 1}: ${ws.name}${ws.waitReason ? `(${ws.waitReason})` : ''}`)
2033
+ }
2034
+ console.error(` 请使用 --reset 重置,或手动修复 DB`)
2035
+ process.exit(1)
2036
+ }
2037
+ const currentIdx = waitingSteps[0].idx
2038
+ const defSteps = await getStageSteps(stageName, cwd, progress, platformOpts?.specRoot || null)
2039
+ const currentStepDef = defSteps?.[currentIdx] || {}
2040
+ const currentStep = stageData.steps[currentIdx]
2041
+ const isRepeatableWait = currentStepDef.repeatableWait === true || currentStep.repeatableWait === true
2042
+ const requiresWait = currentStepDef.requiresWait === true || currentStep.requiresWait === true
2043
+ const shouldReturnToCurrentStep = isRepeatableWait || requiresWait
2044
+
2045
+ const now = new Date().toLocaleString('zh-CN', { hour12: false })
2046
+ const prevOutput = currentStep.output || ''
2047
+ const waitRound = (currentStep.waitRound || 0) + 1
2048
+ currentStep.waitRound = waitRound
2049
+ currentStep.waitAnswer = answer
2050
+ currentStep.waitAnswers = Array.isArray(currentStep.waitAnswers) ? currentStep.waitAnswers : []
2051
+ currentStep.waitAnswers.push({
2052
+ round: waitRound,
2053
+ answer,
2054
+ question: prevOutput || null,
2055
+ answeredAt: now,
2056
+ })
2057
+ currentStep.maxWaitRounds = currentStepDef.maxWaitRounds ?? currentStep.maxWaitRounds
2058
+
2059
+ // 合并 waiting 信息到 output
2060
+ const waitInfo = currentStep.waitReason || ''
2061
+ if (waitInfo) {
2062
+ currentStep.output = prevOutput
2063
+ ? `${prevOutput} | 用户回答#${waitRound}:${answer}`
2064
+ : `用户回答#${waitRound}:${answer}`
2065
+ }
2066
+
2067
+ // 清除等待状态
2068
+ delete currentStep.waitReason
2069
+ delete currentStep.waitOptions
2070
+ delete currentStep.waitedAt
2071
+
2072
+ if (shouldReturnToCurrentStep) {
2073
+ currentStep.status = 'pending'
2074
+ currentStep.completedAt = null
2075
+ } else {
2076
+ currentStep.status = 'completed'
2077
+ currentStep.completedAt = now
2078
+ }
2079
+
2080
+ progress.lastActive = now
2081
+ await pm._write(cwd, progress, changeName)
2082
+ triggerSync(cwd, changeName, platformOpts)
2083
+
2084
+ console.log(`✅ Step ${currentIdx + 1}/${stageData.steps.length} 已继续:${currentStep.name}`)
2085
+ console.log(` 回答:${answer}`)
2086
+
2087
+ // Append to user-inputs.md
2088
+ const inputsPath = join(specBase, '.runtime', 'user-inputs.md')
2089
+ const entry = `\n## ${now} | ${changeName || '?'} | ${stageName}: ${currentStep.name} [CONTINUED]\n- 回答:${answer}\n`
2090
+ appendFileSync(inputsPath, entry)
2091
+
2092
+ // shouldReturnToCurrentStep: 回到当前步骤继续执行(repeatable=多轮探索,requiresWait=确认后执行动作)
2093
+ if (shouldReturnToCurrentStep) {
2094
+ console.log(`\n🔁 Step ${currentIdx + 1}/${stageData.steps.length} 已收到用户输入,回到当前步骤继续执行。`)
2095
+ if (isRepeatableWait) {
2096
+ console.log(` 已收集回答轮次:${waitRound}${currentStep.maxWaitRounds ? `/${currentStep.maxWaitRounds}` : ''}`)
2097
+ }
2098
+ if (defSteps && defSteps[currentIdx]) {
2099
+ console.log('')
2100
+ await outputStep(
2101
+ stageName,
2102
+ currentIdx,
2103
+ defSteps,
2104
+ cwd,
2105
+ changeName,
2106
+ progress.project || null,
2107
+ platformOpts,
2108
+ formatWaitHistory(currentStep)
2109
+ )
2110
+ }
2111
+ return { stageCompleted: false, currentIdx, nextPendingIdx: currentIdx }
2112
+ }
2113
+
2114
+ // 检查阶段是否全部完成
2115
+ const nextPendingIdx = stageData.steps.findIndex(s => s.status === 'pending')
2116
+ const nextWaitingIdx = stageData.steps.findIndex(s => s.status === 'waiting')
2117
+ if (nextPendingIdx === -1 && nextWaitingIdx === -1) {
2118
+ stageData.status = 'completed'
2119
+ stageData.completedAt = now
2120
+ await pm._write(cwd, progress, changeName)
2121
+ console.log(`\n✅ ${stageName} 阶段已完成(${stageData.steps.length}/${stageData.steps.length} 步)`)
2122
+ // ── execute 阶段完成时条件性清理 worktree ──
2123
+ if (stageName === 'execute' && changeName) {
2124
+ try {
2125
+ const { WorktreeManager } = await import('./worktree.js');
2126
+ const wm = new WorktreeManager({ cwd });
2127
+ const meta = wm.getMeta(changeName);
2128
+ if (!meta) {
2129
+ console.log('🔗 Worktree: n/a (no meta)');
2130
+ } else if (meta.mode === 'native-worktree') {
2131
+ console.log('🔗 Worktree: kept (外部隔离环境)');
2132
+ } else if (meta.mode === 'in-place-fallback') {
2133
+ console.log('🔗 Worktree: n/a (in-place 模式)');
2134
+ } else {
2135
+ const check = wm.hasUnappliedChanges(changeName);
2136
+ if (check.hasChanges) {
2137
+ console.log(`🔗 Worktree: pending apply (${check.changedFiles.length} 个未应用变更)`);
2138
+ console.log(` 下一步: sillyspec worktree apply ${changeName}`);
2139
+ } else {
2140
+ const cleanResult = wm.cleanup(changeName);
2141
+ console.log(`🔗 Worktree: ${cleanResult.result}`);
2142
+ }
2143
+ }
2144
+ } catch (e) {
2145
+ console.warn(`🔗 Worktree: check failed — ${e.message}`);
2146
+ }
2147
+ }
2148
+ return { stageCompleted: true, currentIdx, nextPendingIdx: -1 }
2149
+ }
2150
+
2151
+ // 输出下一步
2152
+ if (nextPendingIdx !== -1 && defSteps) {
2153
+ console.log('')
2154
+ await outputStep(stageName, nextPendingIdx, defSteps, cwd, changeName, progress.project || null, platformOpts, answer)
2155
+ } else if (nextWaitingIdx !== -1 && defSteps) {
2156
+ // 下一个步骤也在等待状态
2157
+ const ws = stageData.steps[nextWaitingIdx]
2158
+ console.log(`\n⏸️ Step ${nextWaitingIdx + 1}/${stageData.steps.length} 仍在等待:${ws.name}`)
2159
+ if (ws.waitReason) console.log(` 原因:${ws.waitReason}`)
2160
+ console.log(` 继续:sillyspec run ${stageName} --continue --answer "..."${changeName ? ` --change ${changeName}` : ''}`)
2161
+ }
2162
+
2163
+ return { stageCompleted: false, currentIdx, nextPendingIdx: nextPendingIdx }
2164
+ }
2165
+
2166
+ /**
2167
+ * 判断当前 execute step 所在 wave 是否全部 task 都声明 no_deps_verify: true(D-006@v2)。
2168
+ * 仅 wave 执行步骤(名如 "Wave N 执行")可 opt-out;非 wave 步骤恒返回 false(保守过门)。
2169
+ */
2170
+ function isCurrentWaveAllNoDepsVerify(stepName, changeDir) {
2171
+ if (!stepName) return false
2172
+ const m = String(stepName).match(/^Wave\s+(\d+)/i)
2173
+ if (!m) return false
2174
+ const waveN = parseInt(m[1], 10)
2175
+ if (!changeDir) return false
2176
+ const planPath = join(changeDir, 'plan.md')
2177
+ if (!existsSync(planPath)) return false
2178
+ const plan = readFileSync(planPath, 'utf8')
2179
+ const waveRe = new RegExp(`^##\\s*Wave\\s+${waveN}\\b[^\\n]*\\n([\\s\\S]*?)(?=\\n##\\s|\\n#\\s|$)`, 'm')
2180
+ const waveMatch = plan.match(waveRe)
2181
+ if (!waveMatch) return false
2182
+ const taskIds = [...waveMatch[1].matchAll(/^[-*]\s*\[[ x]\]\s*(task-\d+)/gim)].map(x => x[1])
2183
+ if (taskIds.length === 0) return false
2184
+ for (const id of taskIds) {
2185
+ const cardPath = join(changeDir, 'tasks', `${id}.md`)
2186
+ if (!existsSync(cardPath)) return false // 卡片缺失 → 保守不跳
2187
+ const card = readFileSync(cardPath, 'utf8')
2188
+ const fm = card.match(/^---\n([\s\S]*?)\n---/)
2189
+ if (!fm) return false
2190
+ if (!/no_deps_verify:\s*true/i.test(fm[1])) return false
2191
+ }
2192
+ return true
2193
+ }
2194
+
2195
+ /**
2196
+ * execute deps 验证硬门(change 2026-06-28-worktree-deps-provision / D-001@v1, D-003@v1, D-006@v2)。
2197
+ * depsStatus 不达标且非 wave 级 opt-out 时阻断 --done:置 step=blocked + exit(1),与 requiresWait 同范式。
2198
+ * 放行返回 true;阻断时 process.exit(1) 不返回。
2199
+ */
2200
+ async function enforceDepsGate(stageName, cwd, changeName, step, steps, currentIdx, specBase, platformOpts) {
2201
+ if (stageName !== 'execute') return true
2202
+ let meta = null
2203
+ try {
2204
+ const { WorktreeManager } = await import('./worktree.js')
2205
+ meta = new WorktreeManager({ cwd }).getMeta(changeName)
2206
+ } catch {}
2207
+ const depsStatus = meta?.depsStatus
2208
+ if (['linked', 'installed', 'n/a'].includes(depsStatus)) return true
2209
+ const changeDir = changeName ? join(specBase, 'changes', changeName) : null
2210
+ if (isCurrentWaveAllNoDepsVerify(step?.name, changeDir)) return true
2211
+ if (steps && steps[currentIdx]) steps[currentIdx].status = 'blocked'
2212
+ console.error(`❌ 拒绝 --done:依赖未就绪(depsStatus=${depsStatus || 'unknown'}),不得在无构建/测试能力时声称完成。`)
2213
+ console.error(` 修复:sillyspec worktree doctor --fix${changeName ? ` --change ${changeName}` : ''}`)
2214
+ console.error(` 或在 worktree 内手动安装依赖后重试。`)
2215
+ if (meta?.depsError) console.error(` 上次供给错误:${meta.depsError}`)
2216
+ process.exit(1)
2217
+ }
2218
+
2219
+ /**
2220
+ * execute 入口 deps 自检(D-002,change 2026-06-28-worktree-deps-provision)。
2221
+ * 已存在 worktree(create short-circuit 不供给)时,校验 depsStatus 缺失 / node_modules
2222
+ * 丢失(missing) / lockfile 变化(stale) → 触发 provisionDeps 重供给并写回 meta。
2223
+ */
2224
+ async function ensureDepsFreshness(cwd, changeName, specBase, worktreeMeta) {
2225
+ if (!worktreeMeta || !worktreeMeta.worktreePath) return
2226
+ const { provisionDeps, lockfileHash } = await import('./worktree-deps.js')
2227
+ const wtPath = worktreeMeta.worktreePath
2228
+ const nodeModulesExists = existsSync(join(wtPath, 'node_modules'))
2229
+ const currentHash = lockfileHash(wtPath)
2230
+ const noStatus = !worktreeMeta.depsStatus
2231
+ const missing = ['linked', 'installed'].includes(worktreeMeta.depsStatus) && !nodeModulesExists
2232
+ const stale = !!(worktreeMeta.depsLockHash && currentHash && currentHash !== worktreeMeta.depsLockHash)
2233
+ if (!noStatus && !missing && !stale) return
2234
+ const reason = noStatus ? 'depsStatus 缺失' : (missing ? 'node_modules 丢失' : 'lockfile 变化')
2235
+ console.log(`🔄 worktree deps 自检:${reason}(depsStatus=${worktreeMeta.depsStatus || 'unknown'}),重新供给...`)
2236
+ let deps = {}
2237
+ try {
2238
+ deps = provisionDeps(wtPath, cwd, { specBase }) || {}
2239
+ } catch (e) {
2240
+ deps = { depsStatus: 'failed', depsError: `provisionDeps crashed: ${e.message}` }
2241
+ }
2242
+ try {
2243
+ const { WorktreeManager } = await import('./worktree.js')
2244
+ const metaPath = join(new WorktreeManager({ cwd }).getWorktreePath(changeName), 'meta.json')
2245
+ const updated = { ...worktreeMeta, ...deps }
2246
+ writeFileSync(metaPath, JSON.stringify(updated, null, 2) + '\n')
2247
+ console.log(`✅ deps 重新供给完成:depsStatus=${deps.depsStatus}`)
2248
+ } catch (e) {
2249
+ console.warn(`⚠️ deps meta 写回失败:${e.message}`)
2250
+ }
2251
+ }
2252
+
2253
+ async function completeStep(pm, progress, stageName, cwd, outputText, inputText = null, options = {}) {
2254
+ const { printNext = true, confirm = false, changeName, platformOpts = {}, nonInteractive = false, confirmMode = null } = options
2255
+ const specBase = platformOpts.specRoot || join(cwd, '.sillyspec')
2256
+ const stageData = progress.stages[stageName]
2257
+ const scanProfile = stageData?.scanProfile || null
2258
+
2259
+ // ── WAIT MARKER 硬校验 ──
2260
+ // 如果 output 包含等待标记,拒绝 --done 推进
2261
+ if (outputText) {
2262
+ const match = WAIT_MARKER_RE.exec(outputText)
2263
+ if (match) {
2264
+ console.error(`❌ Refused: step output contains ${match[1]} — human input required.`)
2265
+ console.error(` 使用 --wait 替代 --done,例如:`)
2266
+ console.error(` sillyspec run ${stageName} --wait --reason "等待用户决策" --output "你的摘要"${changeName ? ` --change ${changeName}` : ''}`)
2267
+ process.exit(1)
2268
+ }
2269
+ }
2270
+
2271
+ // scanProfile 非 deep 模式:截断 outputText 减少 token 传递
2272
+ let effectiveOutput = outputText
2273
+ if (scanProfile && scanProfile.mode !== 'deep' && outputText && outputText.length > 1000) {
2274
+ effectiveOutput = outputText.slice(0, 1000) + '\n\n…[输出已截断,完整内容见 artifact]'
2275
+ }
2276
+ if (!stageData || !stageData.steps) {
2277
+ console.error(`❌ 阶段 ${stageName} 未初始化`)
2278
+ process.exit(1)
2279
+ }
2280
+
2281
+ const steps = stageData.steps
2282
+ const currentIdx = steps.findIndex(s => s.status === 'pending' || s.status === 'in-progress')
2283
+ if (currentIdx === -1) {
2284
+ console.error('没有待完成的步骤')
2285
+ process.exit(1)
2286
+ }
2287
+
2288
+ // ── requiresWait 硬门控 ──
2289
+ const defStepsForCurrent = await getStageSteps(stageName, cwd, progress, platformOpts?.specRoot || null)
2290
+ const currentStepDef = defStepsForCurrent?.[currentIdx] || {}
2291
+ const currentStep = steps[currentIdx]
2292
+ if (currentStepDef.requiresWait === true && !currentStep.waitAnswer) {
2293
+ // 检查 --done 是否带了 --answer:如果是,自动补全 waitAnswer 状态,一步完成
2294
+ const doneAnswer = typeof options !== 'undefined' && options.doneAnswer ? options.doneAnswer : null
2295
+ if (doneAnswer) {
2296
+ currentStep.status = 'waiting'
2297
+ currentStep.waitAnswer = doneAnswer
2298
+ currentStep.waitReason = currentStepDef.waitReason || '等待用户输入'
2299
+ console.log(`⚠️ Step "${currentStep.name}" 需要 wait,但 --done 带了 --answer,自动补全 wait 状态。`)
2300
+ } else {
2301
+ console.error(`❌ Step "${currentStep.name}" 必须先等待用户输入,不能直接 --done。`)
2302
+ console.error(` 原因:${currentStepDef.waitReason || '该步骤需要人工确认/回答'}`)
2303
+ if (currentStepDef.waitOptions) {
2304
+ console.error(` 选项:${currentStepDef.waitOptions.join(', ')}`)
2305
+ }
2306
+ console.error(` 请先执行:`)
2307
+ console.error(` sillyspec run ${stageName} --wait --reason "${currentStepDef.waitReason || '等待用户输入'}" --options "${(currentStepDef.waitOptions || ['确认']).join(',')}"${changeName ? ` --change ${changeName}` : ''} --output "你的问题/方案摘要"`)
2308
+ console.error(` 或使用 --done --answer "用户回答" 一步完成 wait + done`)
2309
+ process.exit(1)
2310
+ }
2311
+ }
2312
+
2313
+ // ── execute deps 验证硬门(change 2026-06-28-worktree-deps-provision)──
2314
+ await enforceDepsGate(stageName, cwd, changeName, steps[currentIdx], steps, currentIdx, specBase, platformOpts)
2315
+
2316
+ steps[currentIdx].status = 'completed'
2317
+ steps[currentIdx].completedAt = new Date().toLocaleString('zh-CN',{hour12:false})
2318
+ if (outputText) {
2319
+ const MAX_OUTPUT = 200
2320
+ if (outputText.length > MAX_OUTPUT) {
2321
+ steps[currentIdx].output = outputText.slice(0, MAX_OUTPUT) + '…'
2322
+ steps[currentIdx].output_truncated = true
2323
+ steps[currentIdx].output_original_length = outputText.length
2324
+ // 平台模式:artifact 写入 runtime-root,否则写 .sillyspec/.runtime/artifacts
2325
+ const artifactBase = platformOpts?.runtimeRoot
2326
+ ? join(platformOpts.runtimeRoot, 'scan-runs', platformOpts.scanRunId || 'unknown')
2327
+ : join(specBase, '.runtime', 'artifacts')
2328
+ mkdirSync(artifactBase, { recursive: true })
2329
+ const ts = new Date().toISOString().slice(0,19).replace(/[-T:]/g, '')
2330
+ writeFileSync(join(artifactBase, `${changeName || 'unknown'}-${stageName}-step${currentIdx + 1}-${ts}.txt`), outputText)
2331
+ } else {
2332
+ steps[currentIdx].output = outputText
2333
+ }
2334
+ }
2335
+
2336
+ if (stageName === 'archive' && steps[currentIdx]?.name === '确认归档') {
2337
+ if (!confirm) {
2338
+ steps[currentIdx].status = 'pending'
2339
+ steps[currentIdx].completedAt = null
2340
+ if (outputText) steps[currentIdx].output = null
2341
+ await pm._write(cwd, progress, changeName)
2342
+ console.log('⚠️ 请添加 --confirm 确认归档,例如:sillyspec run archive --done --confirm --output "确认归档"')
2343
+ return { stageCompleted: false, currentIdx, nextPendingIdx: currentIdx }
2344
+ }
2345
+ await archiveChangeDirectory(pm, cwd, progress, specBase)
2346
+ }
2347
+
2348
+ // archive "确认归档" 步骤完成后,校验归档完整性
2349
+ if (stageName === 'archive' && steps[currentIdx]?.name === '确认归档' && confirm) {
2350
+ const projectName = progress.project || basename(cwd)
2351
+ const contractResult = runValidators('archive', cwd, changeName, { projectName, specRoot: platformOpts?.specRoot })
2352
+ if (contractResult.errors.length > 0) {
2353
+ console.error(`\n❌ 归档校验失败:`)
2354
+ for (const err of contractResult.errors) {
2355
+ console.error(` - ${err}`)
2356
+ }
2357
+ }
2358
+ if (contractResult.warnings.length > 0) {
2359
+ console.warn(`\n⚠️ 归档校验警告:`)
2360
+ for (const w of contractResult.warnings) {
2361
+ console.warn(` - ${w}`)
2362
+ }
2363
+ }
2364
+ }
2365
+
2366
+ // plan 阶段 "generate_plan" 完成后,动态插入任务蓝图 + postcheck 步骤
2367
+ // 使用稳定 id 匹配,不依赖中文标题
2368
+ if (stageName === 'plan') {
2369
+ const currentStepDef = defStepsForCurrent?.[currentIdx]
2370
+ const currentStepEntry = steps[currentIdx]
2371
+ const stepId = currentStepDef?.id || currentStepEntry?.id || currentStepEntry?._stepId
2372
+ if (stepId === 'generate_plan') {
2373
+ const changeDir = resolveChangeDir(cwd, progress)
2374
+ if (changeDir) {
2375
+ const planFile = join(changeDir, 'plan.md')
2376
+ if (existsSync(planFile)) {
2377
+ const planContent = readFileSync(planFile, 'utf8')
2378
+ const { buildPlanSteps, fixedPrefix, fixedSuffix } = await import('./stages/plan.js')
2379
+ const fullSteps = buildPlanSteps(changeDir, planContent)
2380
+ const prefixLen = fixedPrefix.length
2381
+ const suffixLen = fixedSuffix.length
2382
+ // 新结构:[...fixedPrefix, coordinatorStep?, postcheckStep?]
2383
+ // fixedSuffix 为空,所以 coordinator + postcheck 都在 prefix 之后
2384
+ const coordinatorSteps = fullSteps.slice(prefixLen, suffixLen > 0 ? -suffixLen : undefined)
2385
+ if (coordinatorSteps.length > 0) {
2386
+ for (let i = 0; i < coordinatorSteps.length; i++) {
2387
+ const stepDef = coordinatorSteps[i]
2388
+ const stepEntry = {
2389
+ id: stepDef.id,
2390
+ name: stepDef.name,
2391
+ status: 'pending',
2392
+ prompt: stepDef.prompt || '',
2393
+ outputHint: stepDef.outputHint,
2394
+ optional: stepDef.optional
2395
+ }
2396
+ // 传递 noAI / _cliAction 属性
2397
+ if (stepDef.noAI) stepEntry.noAI = true
2398
+ if (stepDef._cliAction) stepEntry._cliAction = stepDef._cliAction
2399
+ steps.splice(currentIdx + 1 + i, 0, stepEntry)
2400
+ }
2401
+ console.log(` 📝 已动态插入 ${coordinatorSteps.length} 个步骤(${coordinatorSteps.map(s => s.name).join(', ')})`)
2402
+ }
2403
+ }
2404
+ }
2405
+ }
2406
+ }
2407
+
2408
+ // scan 阶段 step 2 "构建扫描项目列表" 完成后,按项目展开 perProject 步骤
2409
+ if (stageName === 'scan' && steps[currentIdx]?.name === '构建扫描项目列表') {
2410
+ // 解析项目列表:只接受结构化输出(YAML block 或 BEGIN_PROJECT_LIST 标记)
2411
+ // 不再从自由文本猜测项目名——自由文本列表的误解析会导致垃圾项目落盘
2412
+ let parsedProjects = [] // Array<{id, path?}>
2413
+ let parsedFromStructuredOutput = false
2414
+ if (outputText) {
2415
+ // 格式 A: YAML block — 匹配 scan_projects: 下所有 - id: xxx 条目(含多行属性)
2416
+ const yamlBlock = outputText.match(/scan_projects:\s*\n([\s\S]+?)(?=$|\n[^\s])/)
2417
+ if (yamlBlock) {
2418
+ const entries = [...yamlBlock[1].matchAll(/-\s+id:\s*(\S+)(?:[\s\S]*?)(?=\n\s+-\s+id:|$)/g)]
2419
+ for (const m of entries) {
2420
+ const id = sanitizeProjectName(m[1])
2421
+ if (!id) continue
2422
+ // 提取可选 path 字段
2423
+ const pathMatch = m[0].match(/path:\s*(\S+)/)
2424
+ const entry = pathMatch ? { id, path: pathMatch[1].trim() } : { id }
2425
+ parsedProjects.push(entry)
2426
+ }
2427
+ parsedFromStructuredOutput = parsedProjects.length > 0
2428
+ }
2429
+ // 格式 B: BEGIN_PROJECT_LIST ... END_PROJECT_LIST 标记块
2430
+ if (!parsedFromStructuredOutput) {
2431
+ const blockMatch = outputText.match(/BEGIN_PROJECT_LIST\s*\n([\s\S]*?)\n*END_PROJECT_LIST/)
2432
+ if (blockMatch) {
2433
+ const raw = [...blockMatch[1].matchAll(/^-\s+(\S+)/gm)].map(m => m[1])
2434
+ parsedProjects = raw.map(s => sanitizeProjectName(s)).filter(Boolean).map(id => ({ id }))
2435
+ parsedFromStructuredOutput = parsedProjects.length > 0
2436
+ }
2437
+ }
2438
+ }
2439
+
2440
+ const projectNames = parsedProjects.map(p => p.id)
2441
+
2442
+ if (parsedFromStructuredOutput) {
2443
+ stageData.scanMeta = stageData.scanMeta || {}
2444
+ stageData.scanMeta.projectListParsed = true
2445
+ } else {
2446
+ // 结构化输出未解析到 → 回退读取已有 projects/*.yaml
2447
+ // 读取时也校验:path 不存在的 yaml 视为垃圾,直接跳过
2448
+ console.warn('⚠️ step 2 未输出结构化项目列表,回退扫描已注册项目')
2449
+ stageData.scanMeta = stageData.scanMeta || {}
2450
+ stageData.scanMeta.projectListParsed = false
2451
+ const projectsDir = join(specBase, 'projects')
2452
+ if (existsSync(projectsDir)) {
2453
+ const yamlFiles = readdirSync(projectsDir).filter(f => f.endsWith('.yaml'))
2454
+ const fallbackProjects = []
2455
+ const fallbackSkipped = []
2456
+ for (const yf of yamlFiles) {
2457
+ const pName = yf.replace(/\.yaml$/, '')
2458
+ const yamlContent = readFileSync(join(projectsDir, yf), 'utf8')
2459
+ const pathMatch = yamlContent.match(/^path:\s*(.+)/m)
2460
+ const pPath = pathMatch ? pathMatch[1].trim() : pName
2461
+ // 校验 path 是否存在且在 source_root 内
2462
+ const absPath = resolve(cwd, pPath)
2463
+ if (pPath.includes('..') || (!absPath.startsWith(resolve(cwd)) && absPath !== resolve(cwd))) {
2464
+ fallbackSkipped.push(`${pName} (path 越界: ${pPath})`)
2465
+ continue
2466
+ }
2467
+ if (!existsSync(absPath)) {
2468
+ fallbackSkipped.push(`${pName} (path 不存在: ${pPath})`)
2469
+ continue
2470
+ }
2471
+ fallbackProjects.push({ id: pName, path: pPath })
2472
+ }
2473
+ if (fallbackSkipped.length > 0) {
2474
+ console.warn(`⚠️ 跳过 ${fallbackSkipped.length} 个垃圾/过期项目配置:${fallbackSkipped.join(', ')}`)
2475
+ console.warn(' 建议清理 projects/ 下的无效 yaml 文件')
2476
+ }
2477
+ parsedProjects = fallbackProjects
2478
+ projectNames.length = 0
2479
+ projectNames.push(...fallbackProjects.map(p => p.id))
2480
+ }
2481
+ if (parsedProjects.length === 0) {
2482
+ // 无结构化输出 + 无合法已有项目 → step 2 失败
2483
+ console.error('❌ step 2 未输出结构化项目列表,且 projects/ 下无合法项目配置')
2484
+ console.error(' 请在 --output 中输出 scan_projects YAML block 或 BEGIN_PROJECT_LIST 标记块')
2485
+ steps[currentIdx].validationError = '未输出结构化项目列表且无合法 fallback'
2486
+ // 不展开 perProject 步骤,直接跳到下一步
2487
+ }
2488
+ }
2489
+
2490
+ // 校验解析出的项目列表(原子守卫:不通过就不落盘)
2491
+ const validation = validateParsedProjects(parsedProjects, cwd)
2492
+ if (!validation.ok) {
2493
+ console.error(`❌ 项目列表校验失败: ${validation.errors.join('; ')}`)
2494
+ console.error(' step 2 完成,但不展开 perProject 步骤。请检查 --output 中的项目列表。')
2495
+ steps[currentIdx].validationError = validation.errors.join('; ')
2496
+ }
2497
+
2498
+ // 自动注册 + 保存 runtime + 展开 perProject 步骤(仅在校验通过时)
2499
+ const projectsDir = join(specBase, 'projects')
2500
+ if (validation.ok) {
2501
+ for (const proj of parsedProjects) {
2502
+ const pName = proj.id
2503
+ const projYaml = join(projectsDir, `${pName}.yaml`)
2504
+ if (!existsSync(projYaml)) {
2505
+ mkdirSync(projectsDir, { recursive: true })
2506
+ const candidates = [
2507
+ join(cwd, pName),
2508
+ join(cwd, 'backend', pName),
2509
+ join(cwd, 'packages', pName),
2510
+ join(cwd, 'apps', pName),
2511
+ join(cwd, 'services', pName),
2512
+ ]
2513
+ const detected = candidates.find(c => existsSync(c))
2514
+ const regPath = detected || join(cwd, pName)
2515
+ writeFileSync(projYaml, `name: ${pName}\npath: ${regPath}\nstatus: active\n`)
2516
+ console.log(` 📝 自动注册子项目: ${pName} → ${regPath}`)
2517
+ }
2518
+ }
2519
+
2520
+ // 保存 runtime 状态
2521
+ const scanStatePath = join(specBase, '.runtime', 'scan-projects.json')
2522
+ mkdirSync(join(specBase, '.runtime'), { recursive: true })
2523
+ let scanState = { projects: projectNames, expanded: false }
2524
+ if (existsSync(scanStatePath)) {
2525
+ try { scanState = JSON.parse(readFileSync(scanStatePath, 'utf8')) } catch {}
2526
+ }
2527
+
2528
+ // 收集当前步骤之后所有 perProject 步骤
2529
+ const stageDef = stageRegistry[stageName]
2530
+ const allSteps = stageDef?.steps || []
2531
+ const perProjectSteps = allSteps.filter(s => s.perProject)
2532
+
2533
+ // 防重复展开
2534
+ const alreadyExpanded = scanState.expanded || steps.some(s => s.name?.match(/\[.+\]\s*$/))
2535
+ if (!alreadyExpanded && perProjectSteps.length > 0) {
2536
+ // 找到当前步骤(step 2)在动态 steps 中的位置
2537
+ const insertBase = currentIdx + 1
2538
+ let insertPos = insertBase
2539
+ for (const pName of projectNames) {
2540
+ // 读取项目配置获取 projectRoot
2541
+ const projYaml = join(specBase, 'projects', `${pName}.yaml`)
2542
+ let projectRoot = '.'
2543
+ if (existsSync(projYaml)) {
2544
+ const yamlContent = readFileSync(projYaml, 'utf8')
2545
+ const pathMatch = yamlContent.match(/^path:\s*(.+)/m)
2546
+ if (pathMatch) projectRoot = pathMatch[1].trim()
2547
+ }
2548
+ const docOutputDir = platformOpts.specRoot ? `${specBase}/docs/${pName}` : `.sillyspec/docs/${pName}`
2549
+ const contextPrefix = `\n---\n## 当前项目\n- **项目名**: ${pName}\n- **项目路径**: ${projectRoot}\n- **文档输出**: ${docOutputDir}\n\n⚠️ 本步骤只处理上面这个项目,不要处理其他项目。\n---\n\n`
2550
+
2551
+ for (const ppStep of perProjectSteps) {
2552
+ steps.splice(insertPos, 0, {
2553
+ name: `${ppStep.name} [${pName}]`,
2554
+ project: pName,
2555
+ status: 'pending',
2556
+ prompt: contextPrefix + ppStep.prompt,
2557
+ outputHint: ppStep.outputHint,
2558
+ optional: ppStep.optional
2559
+ })
2560
+ insertPos++
2561
+ }
2562
+ }
2563
+ // 移除原始的 perProject 步骤(未展开的版本)
2564
+ for (let i = steps.length - 1; i >= 0; i--) {
2565
+ if (steps[i].perProject && !steps[i].name?.includes('[')) {
2566
+ steps.splice(i, 1)
2567
+ }
2568
+ }
2569
+ console.log(` 📝 已按项目展开 ${perProjectSteps.length} 个步骤 × ${projectNames.length} 个项目 = ${perProjectSteps.length * projectNames.length} 个项目步骤`)
2570
+ console.log(` 📁 扫描项目:${projectNames.join(', ')}`)
2571
+ // 标记已展开,防止 resume 重复插入
2572
+ scanState.expanded = true
2573
+ writeFileSync(scanStatePath, JSON.stringify(scanState))
2574
+ } // end !alreadyExpanded
2575
+ } // end validation.ok
2576
+ } // end step 2
2577
+
2578
+ const nextPendingIdx = steps.findIndex(s => s.status === 'pending' || s.status === 'in-progress')
2579
+
2580
+ if (nextPendingIdx === -1) {
2581
+ // 也检查是否有 waiting 的步骤
2582
+ const hasWaiting = steps.some(s => s.status === 'waiting')
2583
+ if (hasWaiting) {
2584
+ // 有等待中的步骤,阶段未完成
2585
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
2586
+ await pm._write(cwd, progress, changeName)
2587
+ const wsIdx = steps.findIndex(s => s.status === 'waiting')
2588
+ console.log(`\n⏸️ 阶段暂停:Step ${wsIdx + 1} 等待用户输入`)
2589
+ if (steps[wsIdx].waitReason) console.log(` 原因:${steps[wsIdx].waitReason}`)
2590
+ return { stageCompleted: false, currentIdx, nextPendingIdx: -1 }
2591
+ }
2592
+ // quick 阶段完成前强制检查 quicklog 是否创建
2593
+ if (stageName === 'quick') {
2594
+ const quicklogDir = join(specBase, 'quicklog')
2595
+ const hasQuicklog = existsSync(quicklogDir) && readdirSync(quicklogDir).some(f => f.endsWith('.md') && f.startsWith('QUICKLOG'))
2596
+ if (!hasQuicklog) {
2597
+ console.error(`\n❌ quick 阶段完成校验失败:未检测到 QUICKLOG 记录文件。`)
2598
+ console.error(` step 2 要求创建 quicklog 记录,但文件不存在。`)
2599
+ console.error(` 请先创建 quicklog 记录再 --done,或使用 --skip-approval 跳过此校验。`)
2600
+ return { stageCompleted: false, currentIdx, nextPendingIdx: -1 }
2601
+ }
2602
+ if (progress.quickGuard) {
2603
+ const review = await auditQuickCompletion(cwd, progress.quickGuard, { isConfirm })
2604
+ progress.quickGuard.review = review
2605
+ progress.quickGuard.completedAt = new Date().toISOString()
2606
+ printQuickAuditReview(review)
2607
+ if (review.status === 'blocked') {
2608
+ steps[currentIdx].status = 'pending'
2609
+ steps[currentIdx].completedAt = null
2610
+ if (outputText) steps[currentIdx].output = null
2611
+ process.exit(1)
2612
+ }
2613
+ try {
2614
+ const { unlinkSync } = await import('fs')
2615
+ const guardFile = join(specBase, '.runtime', 'quick-guard.json')
2616
+ unlinkSync(guardFile)
2617
+ } catch {}
2618
+ progress.lastQuickReview = review
2619
+ delete progress.quickGuard
2620
+ }
2621
+ }
2622
+
2623
+ stageData.status = 'completed'
2624
+ stageData.completedAt = new Date().toLocaleString('zh-CN',{hour12:false})
2625
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
2626
+ await pm._write(cwd, progress, changeName)
2627
+ triggerSync(cwd, changeName, platformOpts)
2628
+
2629
+ // Append to user-inputs.md
2630
+ if (outputText) {
2631
+ const inputsPath = join(specBase, '.runtime', 'user-inputs.md')
2632
+ const entry = `\n## ${new Date().toLocaleString('zh-CN',{hour12:false})} | ${changeName || '?'} | ${stageName}: ${steps[currentIdx].name}\n${inputText ? "- 输入:" + inputText + "\n" : ""}- 输出:${outputText}\n`
2633
+ appendFileSync(inputsPath, entry)
2634
+ }
2635
+
2636
+ // 平台模式:scan 完成后生成 manifest.json + post-check
2637
+ if (stageName === 'scan' && (platformOpts.specRoot || platformOpts.runtimeRoot)) {
2638
+ try {
2639
+ stageData.scanMeta = stageData.scanMeta || {}; stageData.scanMeta.manifestWritten = false; // 默认失败
2640
+ const { mkdirSync, writeFileSync, readFileSync: _readFileSync } = await import('fs')
2641
+ const { join } = await import('path')
2642
+ const { execSync } = await import('child_process')
2643
+ const manifestDir = platformOpts.specRoot
2644
+ mkdirSync(manifestDir, { recursive: true })
2645
+ let sourceCommit = null
2646
+ let sourceCommitError = null
2647
+ try {
2648
+ const gitResult = safeGit(cwd, ['rev-parse', 'HEAD'])
2649
+ sourceCommit = gitResult.value
2650
+ sourceCommitError = gitResult.error
2651
+ } catch (e) {
2652
+ sourceCommitError = e.message
2653
+ }
2654
+ const manifest = {
2655
+ workspace_id: platformOpts.workspaceId || null,
2656
+ scan_run_id: platformOpts.scanRunId || null,
2657
+ source_root: cwd,
2658
+ spec_root: platformOpts.specRoot || null,
2659
+ runtime_root: platformOpts.runtimeRoot || null,
2660
+ source_commit: sourceCommit,
2661
+ source_commit_error: sourceCommit === null ? (sourceCommitError || 'unknown') : undefined,
2662
+ generated_at: new Date().toISOString(),
2663
+ schema_version: 1,
2664
+ postcheck_result_path: null,
2665
+ workflow_runs_dir: platformOpts.runtimeRoot
2666
+ ? join(platformOpts.runtimeRoot, 'scan-runs', platformOpts.scanRunId || 'unknown', 'workflow-runs')
2667
+ : null,
2668
+ platform_pointer_path: join(cwd, '.sillyspec-platform.json'),
2669
+ platform_pointer_status: POINTER_STATUS.ACTIVE,
2670
+ }
2671
+ const manifestPath = join(manifestDir, 'manifest.json')
2672
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
2673
+ console.log(`📄 manifest.json 已写入: ${manifestPath}`)
2674
+ stageData.scanMeta = stageData.scanMeta || {}; stageData.scanMeta.manifestWritten = true;
2675
+ if (!sourceCommit) {
2676
+ console.log(`⚠️ source_commit 无法获取(可能非 git 目录),已设为 null`)
2677
+ }
2678
+ // 清理平台参数临时文件
2679
+ const { unlinkSync } = await import('fs')
2680
+ const platformOptsFile = join(manifestDir, '.runtime', 'platform-scan.json')
2681
+ try { unlinkSync(platformOptsFile) } catch {}
2682
+
2683
+ // CLI 层 post-check(替代旧的简单检查)
2684
+ const { runScanPostCheck, printScanPostCheckResult, formatStructuredResult, writeStructuredResult } = await import('./scan-postcheck.js')
2685
+ const postResult = runScanPostCheck({
2686
+ cwd,
2687
+ specDir: platformOpts.specRoot,
2688
+ outputText,
2689
+ scanMeta: {
2690
+ projectListParsed: stageData.scanMeta?.projectListParsed ?? null,
2691
+ manifestWritten: stageData.scanMeta?.manifestWritten ?? null,
2692
+ },
2693
+ })
2694
+ printScanPostCheckResult(postResult)
2695
+
2696
+ // 生成结构化 JSON 并写入 runtime(供 SillyHub 消费)
2697
+ const structured = formatStructuredResult(postResult, {
2698
+ workspace_id: platformOpts.workspaceId,
2699
+ scan_run_id: platformOpts.scanRunId,
2700
+ source_root: cwd,
2701
+ spec_root: platformOpts.specRoot,
2702
+ runtime_root: platformOpts.runtimeRoot,
2703
+ })
2704
+ const postcheckJsonPath = writeStructuredResult(structured, platformOpts.specRoot, {
2705
+ runtimeRoot: platformOpts.runtimeRoot,
2706
+ scanRunId: platformOpts.scanRunId,
2707
+ })
2708
+ if (postcheckJsonPath) {
2709
+ console.log(`📄 postcheck-result.json 已写入: ${postcheckJsonPath}`)
2710
+ manifest.postcheck_result_path = postcheckJsonPath
2711
+ }
2712
+
2713
+ // 将 post-check 结果写入 manifest
2714
+ manifest.scan_post_check = {
2715
+ status: postResult.status,
2716
+ checks: postResult.checks,
2717
+ }
2718
+ // 更新 manifest
2719
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
2720
+ console.log(`📄 manifest.json 已更新(含 post-check 结果)`)
2721
+
2722
+ // 更新平台指针状态为 scan_completed
2723
+ const pointerPath = join(cwd, '.sillyspec-platform.json')
2724
+ try {
2725
+ const pointer = JSON.parse(_readFileSync(pointerPath, 'utf8'))
2726
+ pointer.status = POINTER_STATUS.SCAN_COMPLETED
2727
+ pointer.completedAt = new Date().toISOString()
2728
+ pointer.scanStatus = postResult.status
2729
+ writeFileSync(pointerPath, JSON.stringify(pointer, null, 2) + '\n')
2730
+ } catch {}
2731
+
2732
+ // failed_post_check 时强制阻止 clean success
2733
+ if (postResult.status === 'failed_post_check') {
2734
+ stageData.status = SCAN_STATUS.FAILED_POST_CHECK
2735
+ stageData.completedAt = new Date().toLocaleString('zh-CN',{hour12:false})
2736
+ await pm._write(cwd, progress, changeName)
2737
+ triggerSync(cwd, changeName, platformOpts)
2738
+ console.error(`\n❌ scan post-check 失败,状态设为 failed_post_check。不允许 clean success。`)
2739
+ console.error(` 请检查上方错误信息并修复后重新 scan。`)
2740
+ // 平台模式:exit(1) 让 daemon/SillyHub 感知非 0 退出码(manifest.json 已落盘,不会被撤销)
2741
+ if (platformOpts.specRoot || platformOpts.runtimeRoot) {
2742
+ console.error(' 平台模式:CLI 将以 exit code 1 退出,通知 SillyHub scan 失败。')
2743
+ process.exit(1)
2744
+ }
2745
+ // 接口与 plan contract (run.js:2551 附近 plan 失败分支) 对齐:
2746
+ // 返回 { stageCompleted:false, currentIdx, nextPendingIdx: currentIdx }
2747
+ // 让上层 runStage 走"完成但不推进"分支,--done 被拒
2748
+ return { stageCompleted: false, currentIdx, nextPendingIdx: currentIdx }
2749
+ } else if (postResult.status === 'completed_with_warnings') {
2750
+ // 警告不阻止完成,但记录
2751
+ stageData.status = 'completed'
2752
+ stageData.completedAt = new Date().toLocaleString('zh-CN',{hour12:false})
2753
+ await pm._write(cwd, progress, changeName)
2754
+ }
2755
+ } catch (e) {
2756
+ console.warn(`⚠️ manifest.json 写入失败: ${e.message}`)
2757
+ }
2758
+ }
2759
+
2760
+ // 非 platform 模式 scan 也做轻量 post-check + 结构化输出
2761
+ if (stageName === 'scan' && !platformOpts.specRoot && !platformOpts.runtimeRoot) {
2762
+ const { runScanPostCheck, printScanPostCheckResult, formatStructuredResult, writeStructuredResult } = await import('./scan-postcheck.js')
2763
+ const postResult = runScanPostCheck({ cwd, specDir: null, outputText })
2764
+ printScanPostCheckResult(postResult)
2765
+ // 结构化结果写入 .sillyspec/.runtime/
2766
+ const structured = formatStructuredResult(postResult, { source_root: cwd })
2767
+ const postcheckJsonPath = writeStructuredResult(structured, join(cwd, '.sillyspec'))
2768
+ if (postcheckJsonPath) {
2769
+ console.log(`📄 postcheck-result.json 已写入: ${postcheckJsonPath}`)
2770
+ }
2771
+ }
2772
+
2773
+ // 防御性守卫变量:确认所有步骤确实标记为 completed
2774
+ const actualCompleted = steps.filter(s => s.status === 'completed').length
2775
+ const actualTotal = steps.length
2776
+
2777
+ validateMetadata(cwd, stageName, specBase)
2778
+
2779
+ // 验证关键文件是否在正确的变更目录下(仅当所有步骤确实完成时才校验)
2780
+ if (actualCompleted === actualTotal && actualTotal > 0) {
2781
+ validateFileLocations(cwd, stageName, progress, changeName, specBase)
2782
+ }
2783
+
2784
+ // 辅助阶段完成后重置步骤
2785
+ const stageDef = stageRegistry[stageName]
2786
+ if (stageDef?.auxiliary) {
2787
+ const freshSteps = (stageDef.steps || []).map(s => ({
2788
+ name: s.name,
2789
+ status: 'pending',
2790
+ output: null,
2791
+ completedAt: null
2792
+ }))
2793
+ stageData.steps = freshSteps
2794
+ stageData.status = 'pending'
2795
+ stageData.completedAt = null
2796
+ if (progress.currentStage === stageName) progress.currentStage = ''
2797
+ await pm._write(cwd, progress, changeName)
2798
+ }
2799
+
2800
+ const total = steps.length
2801
+ console.log(`✅ ${stageName} 阶段已完成(${total}/${total} 步)`)
2802
+
2803
+ if (stageName === 'execute') {
2804
+ // execute run summary:展示真实可得的结构化信息
2805
+ try {
2806
+ const lastOutput = steps[steps.length - 1]?.output || ''
2807
+ const summary = formatExecuteSummary({
2808
+ changeName,
2809
+ stepsCompleted: total,
2810
+ stepsTotal: total,
2811
+ agentSummary: lastOutput,
2812
+ cwd,
2813
+ })
2814
+ console.log(`\n${summary}`)
2815
+ } catch (e) {
2816
+ // summary 失败不影响主流程
2817
+ console.log('\n👉 下一步:sillyspec run verify(验证通过后才能归档)')
2818
+ }
2819
+ } else if (stageName === 'verify') {
2820
+ console.log('\n👉 下一步:sillyspec run archive(验证通过,可以归档了)')
2821
+ } else if (stageName === 'archive') {
2822
+ console.log('\n👉 归档完成!现在可以提交了:git commit -m "..."')
2823
+ } else {
2824
+ console.log(`\n下一步由你决定:sillyspec run <stage>(brainstorm/plan/execute/verify/archive 等)`)
2825
+ }
2826
+
2827
+ // 阶段完成校验 — 防御性守卫:仅当所有步骤确实标记为 completed 时才跑 validator
2828
+ if (actualCompleted === actualTotal && actualTotal > 0) {
2829
+ const projectName = progress.project || basename(cwd)
2830
+ const contractResult = runValidators(stageName, cwd, changeName, { projectName, specRoot: platformOpts?.specRoot })
2831
+ if (contractResult.errors.length > 0) {
2832
+ console.error(`\n❌ 阶段 ${stageName} 校验失败:`)
2833
+ for (const err of contractResult.errors) {
2834
+ console.error(` - ${err}`)
2835
+ }
2836
+ console.error(`\n 提示:修复缺失产物后重新运行此步骤,或使用 --skip-approval 跳过校验`)
2837
+ }
2838
+ if (contractResult.warnings.length > 0) {
2839
+ console.warn(`\n⚠️ 阶段 ${stageName} 校验警告:`)
2840
+ for (const w of contractResult.warnings) {
2841
+ console.warn(` - ${w}`)
2842
+ }
2843
+ }
2844
+
2845
+ // ── Plan postcheck contract:plan.md 必须满足 execute 契约 ──
2846
+ if (stageName === 'plan') {
2847
+ const planFile = resolveChangeDir(cwd, progress, platformOpts?.specRoot)
2848
+ const planPath = planFile ? join(planFile, 'plan.md') : null
2849
+ if (planPath && existsSync(planPath)) {
2850
+ const { validatePlanForExecute } = await import('./stages/execute.js')
2851
+ const planContent = readFileSync(planPath, 'utf8')
2852
+ const planValidation = validatePlanForExecute(planContent)
2853
+ if (!planValidation.ok) {
2854
+ console.error(`\n❌ Plan → Execute Contract 校验失败:`)
2855
+ for (const err of planValidation.errors) console.error(` - ${err}`)
2856
+ console.error(`\n plan.md 不满足 execute 契约,请修复后重新完成此步骤。`)
2857
+ // 阻断 completed
2858
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
2859
+ await pm._write(cwd, progress, changeName)
2860
+ triggerSync(cwd, changeName, platformOpts)
2861
+ return { stageCompleted: false, currentIdx, nextPendingIdx: currentIdx }
2862
+ }
2863
+ if (planValidation.warnings.length > 0) {
2864
+ console.warn(`\n⚠️ Plan contract 警告(不阻断完成):`)
2865
+ for (const w of planValidation.warnings) console.warn(` - ${w}`)
2866
+ }
2867
+ if (planValidation.ok) {
2868
+ console.log(`\n✅ Plan → Execute Contract 校验通过(${planValidation.tasks.length} tasks, ${planValidation.waves.length} waves)`)
2869
+ }
2870
+ }
2871
+ }
2872
+
2873
+ // ── Execute Task Review Gate:所有 task 必须有 review.json 且 verdict 通过 ──
2874
+ if (stageName === 'execute') {
2875
+ try {
2876
+ const { validateTaskReviews, printReviewResult, writeVerifyRequiredEvidence } = await import('./task-review.js')
2877
+ const effectiveSpecBase = platformOpts?.specRoot || specBase
2878
+ const planFile = resolveChangeDir(cwd, progress, platformOpts?.specRoot)
2879
+ const planPath = planFile ? join(planFile, 'plan.md') : null
2880
+
2881
+ if (planPath && existsSync(planPath)) {
2882
+ const planContent = readFileSync(planPath, 'utf8')
2883
+ const runtimeRoot = join(effectiveSpecBase, '.runtime')
2884
+
2885
+ // execute run id:从变更专属标记文件读取
2886
+ const runIdFile = join(runtimeRoot, `current-execute-run-id-${changeName}`)
2887
+ let executeRunId = ''
2888
+ try {
2889
+ if (existsSync(runIdFile)) {
2890
+ executeRunId = readFileSync(runIdFile, 'utf8').trim()
2891
+ }
2892
+ } catch {}
2893
+ if (!executeRunId) {
2894
+ const { generateExecuteRunId } = await import('./task-review.js')
2895
+ executeRunId = generateExecuteRunId()
2896
+ }
2897
+
2898
+ const reviewResult = validateTaskReviews({ planContent, runtimeRoot, executeRunId })
2899
+ printReviewResult(reviewResult)
2900
+
2901
+ if (!reviewResult.ok) {
2902
+ // Task review 校验失败,阻断 execute 完成
2903
+ // 检查是否存在 checkbox 已勾但 review 不通过的情况
2904
+ const uncheckedTasks = reviewResult.errors.filter(e => e.includes('缺少 review.json'))
2905
+ if (uncheckedTasks.length > 0) {
2906
+ console.error('\n⚠️ 部分任务已在 plan.md 中勾选,但 review.json 不存在。')
2907
+ console.error(' 请取消勾选这些任务的 checkbox,或补充对应的 review.json。')
2908
+ }
2909
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
2910
+ await pm._write(cwd, progress, changeName)
2911
+ triggerSync(cwd, changeName, platformOpts)
2912
+ return { stageCompleted: false, currentIdx, nextPendingIdx: currentIdx }
2913
+ }
2914
+
2915
+ // cannot_verify 的 requiredEvidence 写入 change 目录,供 verify 阶段消费
2916
+ if (reviewResult.requiredEvidence.length > 0) {
2917
+ const evidencePath = writeVerifyRequiredEvidence(join(effectiveSpecBase, 'changes', changeName), reviewResult.requiredEvidence)
2918
+ if (evidencePath) {
2919
+ console.log(`📄 verify-required-evidence.json 已写入: ${evidencePath}`)
2920
+ console.log(' verify 阶段必须满足这些证据要求。')
2921
+ }
2922
+ }
2923
+ }
2924
+ } catch (e) {
2925
+ console.warn(`⚠️ Task Review Gate 异常: ${e.message}`)
2926
+ // 不阻断,但记录异常
2927
+ }
2928
+ }
2929
+ } else if (actualCompleted < actualTotal) {
2930
+ // 实际步骤未全部完成,跳过 validator(状态可能不同步)
2931
+ console.log(`\n⚠️ 阶段校验跳过:${actualTotal} 步中仅 ${actualCompleted} 步标记为已完成,可能存在状态不同步。如确认阶段已完成,请运行 --status 确认。`)
2932
+ }
2933
+
2934
+ // ── execute 阶段完成时条件性清理 worktree(不依赖 AI agent 的完成确认步骤)──
2935
+ if (stageName === 'execute' && changeName) {
2936
+ try {
2937
+ const { WorktreeManager } = await import('./worktree.js');
2938
+ const wm = new WorktreeManager({ cwd });
2939
+ const meta = wm.getMeta(changeName);
2940
+ if (!meta) {
2941
+ console.log('🔗 Worktree: n/a (no meta)');
2942
+ } else if (meta.mode === 'native-worktree') {
2943
+ console.log('🔗 Worktree: kept (外部隔离环境)');
2944
+ } else if (meta.mode === 'in-place-fallback') {
2945
+ console.log('🔗 Worktree: n/a (in-place 模式)');
2946
+ } else {
2947
+ const check = wm.hasUnappliedChanges(changeName);
2948
+ if (check.hasChanges) {
2949
+ console.log(`🔗 Worktree: pending apply (${check.changedFiles.length} 个未应用变更)`);
2950
+ console.log(` 下一步: sillyspec worktree apply ${changeName}`);
2951
+ } else {
2952
+ const cleanResult = wm.cleanup(changeName);
2953
+ if (cleanResult.result === 'skipped' || cleanResult.result === 'kept') {
2954
+ console.log(`🔗 Worktree: ${cleanResult.result}`);
2955
+ } else {
2956
+ console.log(`🔗 Worktree: ${cleanResult.result}`);
2957
+ if (cleanResult.details?.length > 0) {
2958
+ for (const d of cleanResult.details) {
2959
+ if (d.startsWith('⚠️')) console.log(` ${d}`);
2960
+ }
2961
+ }
2962
+ }
2963
+ }
2964
+ }
2965
+ } catch (e) {
2966
+ console.warn(`🔗 Worktree: check failed — ${e.message}`);
2967
+ }
2968
+ }
2969
+
2970
+ return { stageCompleted: true, currentIdx, nextPendingIdx: -1 }
2971
+ }
2972
+
2973
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
2974
+ await pm._write(cwd, progress, changeName)
2975
+ triggerSync(cwd, changeName, platformOpts)
2976
+
2977
+ // Append to user-inputs.md
2978
+ if (outputText) {
2979
+ const inputsPath = join(specBase, '.runtime', 'user-inputs.md')
2980
+ const entry = `\n## ${new Date().toLocaleString('zh-CN',{hour12:false})} | ${changeName || '?'} | ${stageName}: ${steps[currentIdx].name}\n${inputText ? "- 输入:" + inputText + "\n" : ""}- 输出:${outputText}\n`
2981
+ appendFileSync(inputsPath, entry)
2982
+ }
2983
+
2984
+ const defSteps = await getStageSteps(stageName, cwd, progress, platformOpts?.specRoot || null)
2985
+ console.log(`✅ Step ${currentIdx + 1}/${steps.length} 完成:${steps[currentIdx].name}\n`)
2986
+
2987
+ // Workflow post_check:scan 深度扫描完成后自动检查产物
2988
+ if (stageName === 'scan' && steps[currentIdx]?.name?.includes('深度扫描')) {
2989
+ try {
2990
+ const { loadWorkflow, runPostCheck, formatCheckReport, saveWorkflowRun } = await import('./workflow.js')
2991
+ const wf = loadWorkflow(cwd, 'scan-docs')
2992
+ if (wf) {
2993
+ // 确定当前项目(优先级链):
2994
+ // progress.project (dbProjectName,平台模式真实项目名,与 outputStep 占位符渲染对齐)
2995
+ // > change?.project (变更对象的项目字段,平台模式 change 创建时传入)
2996
+ // > steps[idx].project (perProject 展开标记,兼容旧模式)
2997
+ // > steps[idx].name 正则提取 [xxx] 后缀
2998
+ // > null(回退检查所有项目)
2999
+ // task-05 修复:日志显示项目名变 frontend 是 perProject 误展开 bug,
3000
+ // 用 progress.project(与 outputStep 占位符渲染路径一致)修正 myaaa/frontend 分裂。
3001
+ const currentProjectName = progress.project
3002
+ || (typeof change !== 'undefined' && change ? change.project : null)
3003
+ || steps[currentIdx].project
3004
+ || (steps[currentIdx].name.match(/\[([^\]]+)\]\s*$/) || [])[1]
3005
+ || null
3006
+
3007
+ // 确定要检查的项目列表
3008
+ let projectsToCheck = []
3009
+ if (currentProjectName) {
3010
+ // 按项目展开模式:只检查当前项目
3011
+ projectsToCheck = [currentProjectName]
3012
+ } else {
3013
+ // 兼容旧模式(未展开):检查所有项目
3014
+ const projectsDir = join(specBase, 'projects')
3015
+ const projectFiles = existsSync(projectsDir)
3016
+ ? readdirSync(projectsDir).filter(f => f.endsWith('.yaml'))
3017
+ : []
3018
+ projectsToCheck = projectFiles.map(f => f.replace(/\.yaml$/, ''))
3019
+ }
3020
+
3021
+ let anyFailed = false
3022
+ for (const pName of projectsToCheck) {
3023
+ const result = runPostCheck(wf, cwd, pName, {}, specBase)
3024
+ const report = formatCheckReport(result)
3025
+ console.log(report)
3026
+ if (result.status === 'fail') {
3027
+ anyFailed = true
3028
+ // retry_prompts 由 _checkWorkflow 自动生成
3029
+ for (const rp of (result.retry_prompts || [])) {
3030
+ console.log(`\n🔄 重试提示(项目 ${pName}):\n`)
3031
+ console.log(rp.prompt)
3032
+ }
3033
+ }
3034
+ const saved = saveWorkflowRun(result, {
3035
+ cwd,
3036
+ source: 'run.js',
3037
+ stage: 'scan',
3038
+ step: steps[currentIdx]?.name,
3039
+ ...(platformOpts.runtimeRoot ? { runtimeRoot: platformOpts.runtimeRoot } : {}),
3040
+ ...(platformOpts.scanRunId ? { scanRunId: platformOpts.scanRunId } : {})
3041
+ })
3042
+ if (saved) console.log(`📁 结果已归档:${saved}`)
3043
+ }
3044
+ if (anyFailed) {
3045
+ console.log(`\n⚠️ 存在检查失败项,请按上面的重试提示修复后再继续。`)
3046
+ // task-07: 阻断推进(与 task-06 平台模式 scan-postcheck 失败分支 return 结构对齐)
3047
+ // scan 深度扫描产物校验未通过时,不允许 clean success / 进入下一 step,
3048
+ // 让上层走"完成但不推进"分支,--done 被拒。
3049
+ return { stageCompleted: false, currentIdx, nextPendingIdx: currentIdx }
3050
+ }
3051
+ }
3052
+ } catch (e) {
3053
+ console.warn(`⚠️ workflow 检查跳过:${e.message}`)
3054
+ }
3055
+ }
3056
+
3057
+ // Workflow post_check:archive extract-module-impact 完成后检查产物
3058
+ if (stageName === 'archive' && steps[currentIdx]?.name?.includes('extract-module-impact')) {
3059
+ try {
3060
+ const { loadWorkflow, runPostCheck, formatCheckReport, saveWorkflowRun } = await import('./workflow.js')
3061
+ const wf = loadWorkflow(cwd, 'archive-impact')
3062
+ if (wf && changeName) {
3063
+ const raw = JSON.stringify(wf)
3064
+ const resolved = JSON.parse(raw.replace(/<change-name>/g, changeName))
3065
+ const result = runPostCheck(resolved, cwd, 'sillyspec', {}, specBase)
3066
+ // 只报告 impact-analyzer 的结果(doc-syncer 是后续步骤)
3067
+ const impactResult = (result.roles || []).find(r => r.id === 'impact-analyzer')
3068
+ if (impactResult) {
3069
+ const icon = impactResult.status === 'pass' ? '✅' : '❌'
3070
+ console.log(`${icon} module-impact.md 检查${impactResult.status === 'pass' ? '通过' : '失败'}`)
3071
+ for (const f of (result.failures || []).filter(f => f.role_id === 'impact-analyzer')) {
3072
+ console.log(` └─ ${f}`)
3073
+ }
3074
+ }
3075
+ const saved = saveWorkflowRun(result, {
3076
+ cwd,
3077
+ source: 'run.js',
3078
+ stage: 'archive',
3079
+ step: steps[currentIdx]?.name,
3080
+ ...(platformOpts.runtimeRoot ? { runtimeRoot: platformOpts.runtimeRoot } : {}),
3081
+ ...(platformOpts.scanRunId ? { scanRunId: platformOpts.scanRunId } : {})
3082
+ })
3083
+ if (saved) console.log(`📁 结果已归档:${saved}`)
3084
+ }
3085
+ } catch (e) {
3086
+ console.warn(`⚠️ workflow 检查跳过:${e.message}`)
3087
+ }
3088
+ }
3089
+
3090
+ if (printNext) {
3091
+ await outputStep(stageName, nextPendingIdx, defSteps, cwd, changeName, progress.project || null, platformOpts)
3092
+ }
3093
+ return { stageCompleted: false, currentIdx, nextPendingIdx }
3094
+ }
3095
+
3096
+ async function skipStep(pm, progress, stageName, cwd, changeName) {
3097
+ const stageData = progress.stages[stageName]
3098
+ if (!stageData || !stageData.steps) {
3099
+ console.error(`❌ 阶段 ${stageName} 未初始化`)
3100
+ process.exit(1)
3101
+ }
3102
+
3103
+ const steps = stageData.steps
3104
+ const currentIdx = steps.findIndex(s => s.status === 'pending' || s.status === 'in-progress')
3105
+
3106
+ if (currentIdx === -1) {
3107
+ const wsIdx = steps.findIndex(s => s.status === 'waiting')
3108
+ if (wsIdx !== -1) {
3109
+ console.error(`⏸️ Step ${wsIdx + 1} 正在等待用户输入,不能跳过。`)
3110
+ console.error(` 请先使用 --continue --answer "..." 继续,或用 --reset 重置。`)
3111
+ } else {
3112
+ console.error('没有待跳过的步骤')
3113
+ }
3114
+ process.exit(1)
3115
+ }
3116
+
3117
+ const defSteps = await getStageSteps(stageName, cwd, progress, platformOpts?.specRoot || null)
3118
+ const stepDef = defSteps ? defSteps[currentIdx] : null
3119
+ if (stepDef && !stepDef.optional) {
3120
+ console.error(`❌ 步骤 "${steps[currentIdx].name}" 不可跳过`)
3121
+ process.exit(1)
3122
+ }
3123
+
3124
+ steps[currentIdx].status = 'skipped'
3125
+ steps[currentIdx].skippedAt = new Date().toLocaleString('zh-CN',{hour12:false})
3126
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
3127
+ await pm._write(cwd, progress, changeName)
3128
+ triggerSync(cwd, changeName, platformOpts)
3129
+
3130
+ console.log(`⏭️ Step ${currentIdx + 1}/${steps.length} 已跳过:${steps[currentIdx].name}`)
3131
+
3132
+ const nextPendingIdx = steps.findIndex(s => s.status === 'pending' || s.status === 'in-progress')
3133
+ if (nextPendingIdx !== -1 && defSteps) {
3134
+ console.log('')
3135
+ await outputStep(stageName, nextPendingIdx, defSteps, cwd, changeName, progress.project || null, platformOpts)
3136
+ } else {
3137
+ const wsIdx = steps.findIndex(s => s.status === 'waiting')
3138
+ if (wsIdx !== -1) {
3139
+ console.log(`\n⏸️ Step ${wsIdx + 1}/${steps.length} 正在等待:${steps[wsIdx].name}`)
3140
+ if (steps[wsIdx].waitReason) console.log(` 原因:${steps[wsIdx].waitReason}`)
3141
+ console.log(` 继续:sillyspec run ${stageName} --continue --answer "..."${changeName ? ` --change ${changeName}` : ''}`)
3142
+ }
3143
+ }
3144
+ }
3145
+
3146
+ function showStatus(progress, stageName) {
3147
+ const stageData = progress.stages[stageName]
3148
+ const stageDef = stageRegistry[stageName]
3149
+
3150
+ if (!stageData || !stageData.steps || stageData.steps.length === 0) {
3151
+ console.log(`阶段:${stageName}(${stageDef?.title || stageName})`)
3152
+ console.log(`进度:未初始化`)
3153
+ if (stageData?.status) {
3154
+ console.log(`状态:${stageData.status}`)
3155
+ if (stageData.staleReason) console.log(`⚠️ 失效原因:${stageData.staleReason}`)
3156
+ }
3157
+ return
3158
+ }
3159
+
3160
+ const steps = stageData.steps
3161
+ const completed = steps.filter(s => s.status === 'completed' || s.status === 'skipped').length
3162
+ const bar = '█'.repeat(completed) + '░'.repeat(steps.length - completed)
3163
+
3164
+ console.log(`阶段:${stageName}(${stageDef?.title || stageName})`)
3165
+ console.log(`进度:[${bar}] ${completed}/${steps.length}`)
3166
+
3167
+ // ── Revision v1 信息 ──
3168
+ if (stageData.status === 'revising') {
3169
+ console.log(`\n🔧 修订中 (revision ${stageData.revision || 1})`)
3170
+ if (stageData.reopenedFromStep) console.log(` 从步骤:${stageData.reopenedFromStep}`)
3171
+ if (stageData.reopenedAt) console.log(` 重开时间:${stageData.reopenedAt}`)
3172
+ }
3173
+ if (stageData.status === 'stale') {
3174
+ console.log(`\n⚠️ 已失效`)
3175
+ if (stageData.staleReason) console.log(` 原因:${stageData.staleReason}`)
3176
+ console.log(` 建议:sillyspec run ${stageName} --reopen --from-step 1`)
3177
+ }
3178
+ if (stageData.status === 'completed') {
3179
+ console.log(`\n✅ 已完成`)
3180
+ }
3181
+
3182
+ console.log('')
3183
+
3184
+ const firstPending = steps.findIndex(s => s.status === 'pending' || s.status === 'in-progress')
3185
+
3186
+ if (progress.batchProgress) {
3187
+ const bp = progress.batchProgress
3188
+ const bpTotal = bp.total || 0
3189
+ const bpCompleted = bp.completed || 0
3190
+ const bpFailed = bp.failed || 0
3191
+ const bpSkipped = bp.skipped || 0
3192
+ const bpBarLen = 20
3193
+ const bpFilled = Math.round((bpCompleted / Math.max(bpTotal, 1)) * bpBarLen)
3194
+ const bpBar = '█'.repeat(bpFilled) + '░'.repeat(bpBarLen - bpFilled)
3195
+ const bpParts = []
3196
+ if (bpFailed > 0) bpParts.push(`${bpFailed} 失败`)
3197
+ if (bpSkipped > 0) bpParts.push(`${bpSkipped} 跳过`)
3198
+ const bpSuffix = bpParts.length ? ` (${bpParts.join(', ')})` : ''
3199
+ console.log(`\n📊 批量进度: ${bpBar} ${bpCompleted}/${bpTotal}${bpSuffix}\n`)
3200
+ }
3201
+
3202
+ steps.forEach((step, i) => {
3203
+ const icon = step.status === 'completed' ? '✅' : step.status === 'skipped' ? '⏭️' : step.status === 'waiting' ? '⏸️' : '⬜'
3204
+ const isCurrent = (step.status === 'pending' || step.status === 'in-progress') && i === firstPending
3205
+ const isWaiting = step.status === 'waiting'
3206
+ console.log(`${icon} Step ${i + 1}: ${step.name}${isCurrent ? ' ← 当前' : ''}${isWaiting ? ' [WAITING]' : ''}`)
3207
+ if (isWaiting) {
3208
+ if (step.waitReason) console.log(` 原因:${step.waitReason}`)
3209
+ if (step.waitOptions) console.log(` 选项:${formatWaitOptions(step.waitOptions)}`)
3210
+ if (step.waitedAt) console.log(` 等待时间:${step.waitedAt}`)
3211
+ }
3212
+ })
3213
+ }
3214
+
3215
+ async function resetStage(pm, progress, stageName, cwd, changeName, platformOpts = {}) {
3216
+ const defSteps = await getStageSteps(stageName, cwd, progress, platformOpts?.specRoot || null)
3217
+ progress.stages[stageName] = {
3218
+ status: 'in-progress',
3219
+ startedAt: new Date().toLocaleString('zh-CN',{hour12:false}),
3220
+ completedAt: null,
3221
+ steps: defSteps ? defSteps.map(s => ({ name: s.name, status: 'pending' })) : []
3222
+ }
3223
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
3224
+ await pm._write(cwd, progress, changeName)
3225
+ triggerSync(cwd, changeName, platformOpts)
3226
+ console.log(`🔄 ${stageName} 阶段已重置`)
3227
+ }
3228
+
3229
+ /**
3230
+ * auto 模式:自动推进 brainstorm → plan → execute → verify
3231
+ */
3232
+ async function runAutoMode(pm, progress, cwd, flags, changeName, platformOpts = {}) {
3233
+ const flowStages = ['brainstorm', 'plan', 'execute', 'verify', 'archive']
3234
+ const isDone = flags.includes('--done')
3235
+ const outputIdx = flags.indexOf('--output')
3236
+ const outputText = outputIdx !== -1 && flags[outputIdx + 1] ? flags[outputIdx + 1] : null
3237
+ const inputIdx = flags.indexOf('--input')
3238
+ const inputText = inputIdx !== -1 && flags[inputIdx + 1] ? flags[inputIdx + 1] : null
3239
+ const skipApproval = flags.includes('--skip-approval')
3240
+ const explicitMode = (() => {
3241
+ const m = flags.indexOf('--mode')
3242
+ return m !== -1 && flags[m + 1] ? flags[m + 1] : null
3243
+ })()
3244
+ const specBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
3245
+
3246
+ // Helper: 在 auto 模式下获取步骤定义
3247
+ const getAutoSteps = async (stage) => {
3248
+ if (stage === 'brainstorm') {
3249
+ return brainstormAutoDef.steps
3250
+ }
3251
+ return getStageSteps(stage, cwd, progress, platformOpts?.specRoot || null)
3252
+ }
3253
+
3254
+ const nextInFlow = (stage) => {
3255
+ const i = flowStages.indexOf(stage)
3256
+ return i >= 0 && i < flowStages.length - 1 ? flowStages[i + 1] : null
3257
+ }
3258
+ const firstOpenStage = () => flowStages.find(s => progress.stages?.[s]?.status !== 'completed')
3259
+ const ensureAutoStage = async (stage) => {
3260
+ const stageChanged = progress.currentStage !== stage
3261
+ progress.currentStage = stage
3262
+ // Auto 模式下 brainstorm 使用 artifact-first 步骤
3263
+ if (stage === 'brainstorm') {
3264
+ const existingSteps = progress.stages?.brainstorm?.steps
3265
+ const isAutoModeSteps = existingSteps?.length === 4 && existingSteps?.[0]?.name === '状态检查与上下文加载'
3266
+ if (!isAutoModeSteps) {
3267
+ if (!progress.stages) progress.stages = {}
3268
+ progress.stages.brainstorm = {
3269
+ status: 'in-progress',
3270
+ startedAt: new Date().toLocaleString('zh-CN', { hour12: false }),
3271
+ completedAt: null,
3272
+ steps: brainstormAutoDef.steps.map(s => ({ name: s.name, status: 'pending' }))
3273
+ }
3274
+ await pm._write(cwd, progress, changeName)
3275
+ triggerSync(cwd, changeName, platformOpts)
3276
+ progress = await pm.read(cwd, changeName)
3277
+ return progress
3278
+ }
3279
+ }
3280
+ const changed = await ensureStageSteps(progress, stage, cwd)
3281
+ if (stageChanged || changed) {
3282
+ await pm._write(cwd, progress, changeName)
3283
+ triggerSync(cwd, changeName, platformOpts)
3284
+ }
3285
+ progress = await pm.read(cwd, changeName)
3286
+ return progress
3287
+ }
3288
+
3289
+ // ── Classify change on first entry ──
3290
+ if (!progress.stages?.brainstorm?.status && !progress.stages?.plan?.status) {
3291
+ const { classifyChange } = await import('./classify-change.js')
3292
+ const classification = classifyChange({ description: inputText || '', explicitMode })
3293
+ if (classification.mode === 'quick') {
3294
+ console.log(`📊 auto 模式分类:${classification.mode}(${classification.reason})`)
3295
+ console.log(` 此变更建议使用 quick 模式,运行:sillyspec run quick "${inputText || '需求'}"`)
3296
+ return
3297
+ }
3298
+ console.log(`📊 auto 模式分类:${classification.mode}(${classification.reason})`)
3299
+ }
3300
+
3301
+ let currentStage = progress.currentStage
3302
+ if (!currentStage || progress.stages?.[currentStage]?.status === 'completed') {
3303
+ currentStage = firstOpenStage()
3304
+ }
3305
+ if (!currentStage) {
3306
+ console.log('All auto flow stages are complete.')
3307
+ return
3308
+ }
3309
+ if (!flowStages.includes(currentStage)) {
3310
+ const openStage = firstOpenStage()
3311
+ if (!openStage) {
3312
+ console.log('All auto flow stages are complete.')
3313
+ return
3314
+ }
3315
+ console.log(`⚠️ 当前阶段 ${currentStage} 不在 auto 流程中,自动跳转到 ${openStage}`)
3316
+ currentStage = openStage
3317
+ }
3318
+ await ensureAutoStage(currentStage)
3319
+
3320
+ if (!isDone) {
3321
+ console.log('════════════════════════════════════════')
3322
+ console.log(' SillySpec Auto Mode')
3323
+ if (changeName) console.log(` Change: ${changeName}`)
3324
+ console.log('════════════════════════════════════════')
3325
+ console.log(` Flow: ${flowStages.join(' -> ')}`)
3326
+ console.log(` Current: ${currentStage}`)
3327
+ for (const stage of flowStages) {
3328
+ const stageData = progress.stages?.[stage]
3329
+ const total = stageData?.steps?.length || '?'
3330
+ const completed = stageData?.steps?.filter(step => step.status === 'completed' || step.status === 'skipped').length || 0
3331
+ const marker = stageData?.status === 'completed' ? 'done' : stage === currentStage ? 'active' : 'pending'
3332
+ console.log(` ${marker} ${stage} (${completed}/${total})`)
3333
+ }
3334
+ console.log('')
3335
+
3336
+ const defSteps = await getAutoSteps(currentStage)
3337
+ const pendingIdx = progress.stages[currentStage]?.steps?.findIndex(step => step.status === 'pending' || step.status === 'in-progress') ?? -1
3338
+ if (pendingIdx === -1) {
3339
+ const wsIdx = progress.stages[currentStage]?.steps?.findIndex(step => step.status === 'waiting') ?? -1
3340
+ if (wsIdx !== -1) {
3341
+ const ws = progress.stages[currentStage].steps[wsIdx]
3342
+ console.log(`⏸️ Step ${wsIdx + 1} 等待用户输入:${ws.name}`)
3343
+ if (ws.waitReason) console.log(` 原因:${ws.waitReason}`)
3344
+ console.log(` 继续:sillyspec run auto --continue --answer "..."`)
3345
+ return
3346
+ }
3347
+ const next = nextInFlow(currentStage)
3348
+ if (next) console.log(`${currentStage} is complete. Run: sillyspec run auto --done --output "${currentStage} complete"`)
3349
+ else console.log('All auto flow stages are complete.')
3350
+ return
3351
+ }
3352
+ // execute 阶段启动前检查审批
3353
+ if (currentStage === 'execute' && !skipApproval) {
3354
+ const approval = await checkApproval(cwd, changeName, platformOpts)
3355
+ if (approval) {
3356
+ if (approval.status === 'rejected') {
3357
+ console.error(`❌ 变更 ${changeName} 的执行已被拒绝:${approval.reason || '无原因'}`)
3358
+ process.exit(1)
3359
+ }
3360
+ if (approval.status === 'pending') {
3361
+ console.log(`⏳ 变更 ${changeName} 的执行审批待处理中...`)
3362
+ console.log(' 提示:使用 --skip-approval 跳过审批检查')
3363
+ }
3364
+ }
3365
+ }
3366
+ await outputStep(currentStage, pendingIdx, defSteps, cwd, changeName, progress.project || null, platformOpts)
3367
+ return
3368
+ }
3369
+
3370
+ if (!outputText) {
3371
+ console.error('auto --done requires --output')
3372
+ process.exit(1)
3373
+ }
3374
+
3375
+ const result = await completeStep(pm, progress, currentStage, cwd, outputText, inputText, { printNext: false, changeName, platformOpts })
3376
+ if (!result) return
3377
+ progress = await pm.read(cwd, changeName)
3378
+
3379
+ const nextPendingIdx = progress.stages[currentStage]?.steps?.findIndex(step => step.status === 'pending' || step.status === 'in-progress') ?? -1
3380
+ if (nextPendingIdx !== -1) {
3381
+ const defSteps = await getAutoSteps(currentStage)
3382
+ // execute 阶段启动前检查审批
3383
+ if (currentStage === 'execute' && !skipApproval) {
3384
+ const approval = await checkApproval(cwd, changeName, platformOpts)
3385
+ if (approval) {
3386
+ if (approval.status === 'rejected') {
3387
+ console.error(`❌ 变更 ${changeName} 的执行已被拒绝:${approval.reason || '无原因'}`)
3388
+ process.exit(1)
3389
+ }
3390
+ if (approval.status === 'pending') {
3391
+ console.log(`⏳ 变更 ${changeName} 的执行审批待处理中...`)
3392
+ console.log(' 提示:使用 --skip-approval 跳过审批检查')
3393
+ }
3394
+ }
3395
+ }
3396
+ await outputStep(currentStage, nextPendingIdx, defSteps, cwd, changeName, progress.project || null, platformOpts)
3397
+ return
3398
+ }
3399
+
3400
+ const next = nextInFlow(currentStage)
3401
+ if (!next) {
3402
+ console.log('\nAll auto flow stages are complete.')
3403
+ return
3404
+ }
3405
+
3406
+ // ── next-action.json 驱动:brainstorm → plan 推进判断 ──
3407
+ if (currentStage === 'brainstorm' && next === 'plan') {
3408
+ const changeDir = resolveChangeDir(cwd, progress, platformOpts?.specRoot || null)
3409
+ if (changeDir) {
3410
+ const nextActionFile = join(changeDir, 'brainstorm', 'next-action.json')
3411
+ try {
3412
+ const nextAction = JSON.parse(readFileSync(nextActionFile, 'utf8'))
3413
+ if (nextAction.has_blocking_questions === true) {
3414
+ console.log(`\n⏸️ brainstorm 有阻塞问题,无法自动进入 plan:`)
3415
+ for (const q of (nextAction.questions || [])) {
3416
+ console.log(` Q-${q.id}: ${q.question}`)
3417
+ if (q.options) console.log(` 选项:${q.options.join(' / ')}`)
3418
+ if (q.recommended) console.log(` 推荐:${q.recommended}`)
3419
+ }
3420
+ console.log(`\n 请回答阻塞问题后继续:sillyspec run auto --done --output "已回答"`)
3421
+ return
3422
+ }
3423
+ console.log(`\n✅ next-action.json: ${nextAction.status},自动进入 plan`)
3424
+ } catch (e) {
3425
+ // next-action.json 不存在或格式错误,继续推进(向后兼容)
3426
+ console.log(`\n⚠️ next-action.json 未找到,继续进入 plan`)
3427
+ }
3428
+ }
3429
+ }
3430
+
3431
+ progress.currentStage = next
3432
+ if (!progress.stages[next]) {
3433
+ progress.stages[next] = { status: 'pending', steps: [], startedAt: null, completedAt: null }
3434
+ }
3435
+ if (progress.stages[next].status === 'pending' || !progress.stages[next].status) {
3436
+ progress.stages[next].status = 'in-progress'
3437
+ progress.stages[next].startedAt = new Date().toLocaleString('zh-CN',{hour12:false})
3438
+ }
3439
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
3440
+ await ensureStageSteps(progress, next, cwd)
3441
+ await pm._write(cwd, progress, changeName)
3442
+ triggerSync(cwd, changeName, platformOpts)
3443
+ progress = await pm.read(cwd, changeName)
3444
+
3445
+ console.log(`\n${currentStage} complete. Auto advanced to ${next}.`)
3446
+ const nextSteps = await getAutoSteps(next)
3447
+ const firstPending = progress.stages[next]?.steps?.findIndex(step => step.status === 'pending' || step.status === 'in-progress') ?? -1
3448
+ if (firstPending !== -1) {
3449
+ // execute 阶段启动前检查审批
3450
+ if (next === 'execute' && !skipApproval) {
3451
+ const approval = await checkApproval(cwd, changeName, platformOpts)
3452
+ if (approval) {
3453
+ if (approval.status === 'rejected') {
3454
+ console.error(`❌ 变更 ${changeName} 的执行已被拒绝:${approval.reason || '无原因'}`)
3455
+ process.exit(1)
3456
+ }
3457
+ if (approval.status === 'pending') {
3458
+ console.log(`⏳ 变更 ${changeName} 的执行审批待处理中...`)
3459
+ console.log(' 提示:使用 --skip-approval 跳过审批检查')
3460
+ }
3461
+ }
3462
+ }
3463
+ await outputStep(next, firstPending, nextSteps, cwd, changeName, progress.project || null, platformOpts)
3464
+ }
3465
+ }