sillyspec 3.20.1 → 3.20.3

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