sillyspec 3.26.10 → 3.26.11

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 (97) hide show
  1. package/.claude/skills/sillyspec-archive/SKILL.md +85 -85
  2. package/.claude/skills/sillyspec-brainstorm/SKILL.md +114 -114
  3. package/.claude/skills/sillyspec-commit/SKILL.md +109 -109
  4. package/.claude/skills/sillyspec-continue/SKILL.md +45 -45
  5. package/.claude/skills/sillyspec-doctor/SKILL.md +76 -76
  6. package/.claude/skills/sillyspec-execute/SKILL.md +200 -200
  7. package/.claude/skills/sillyspec-explore/SKILL.md +95 -95
  8. package/.claude/skills/sillyspec-knowledge/SKILL.md +269 -269
  9. package/.claude/skills/sillyspec-plan/SKILL.md +148 -148
  10. package/.claude/skills/sillyspec-quick/SKILL.md +111 -111
  11. package/.claude/skills/sillyspec-resume/SKILL.md +68 -68
  12. package/.claude/skills/sillyspec-scan/SKILL.md +79 -79
  13. package/.claude/skills/sillyspec-state/SKILL.md +64 -64
  14. package/.claude/skills/sillyspec-status/SKILL.md +54 -54
  15. package/.claude/skills/sillyspec-verify/SKILL.md +83 -83
  16. package/.claude/skills/sillyspec-workspace/SKILL.md +169 -169
  17. package/.gitattributes +2 -0
  18. package/.husky/pre-push +20 -20
  19. package/.npmrc-publish +2 -0
  20. package/README.md +201 -201
  21. package/SKILL.md +90 -90
  22. package/package.json +39 -39
  23. package/packages/dashboard/dist/assets/index-Bq_Z2hne.js +7446 -7446
  24. package/packages/dashboard/dist/assets/index-O2W5RV4z.css +1 -1
  25. package/packages/dashboard/dist/index.html +16 -16
  26. package/packages/dashboard/package.json +25 -25
  27. package/packages/dashboard/server/executor.js +86 -86
  28. package/packages/dashboard/server/index.js +601 -601
  29. package/packages/dashboard/server/parser.js +526 -526
  30. package/src/change-risk-profile.js +254 -254
  31. package/src/classify-change.js +109 -109
  32. package/src/config-schema.js +310 -310
  33. package/src/contract-matrix.js +379 -379
  34. package/src/db.js +350 -350
  35. package/src/dispatch/backends/local-agent.js +155 -155
  36. package/src/dispatch/backends/sillyhub-mcp.js +245 -245
  37. package/src/dispatch/probe.js +210 -210
  38. package/src/dispatch/strategy.js +121 -121
  39. package/src/docs-check.js +131 -4
  40. package/src/doctor-diagnostics.js +711 -711
  41. package/src/endpoint-extractor.js +401 -401
  42. package/src/fs-atomic.js +69 -69
  43. package/src/git-helper.js +79 -79
  44. package/src/hooks/claude-pre-tool-use.cjs +125 -125
  45. package/src/hooks/worktree-guard.js +848 -848
  46. package/src/index.js +90 -8
  47. package/src/init.js +623 -623
  48. package/src/knowledge-match.js +130 -130
  49. package/src/local-detect.js +120 -120
  50. package/src/machine-interface.js +543 -543
  51. package/src/migrate.js +127 -127
  52. package/src/progress/change-registry.js +297 -260
  53. package/src/progress/consistency-doctor.js +355 -355
  54. package/src/progress/shared.js +36 -36
  55. package/src/progress/stage-machine.js +29 -1
  56. package/src/progress/step-store.js +261 -261
  57. package/src/progress.js +1131 -1127
  58. package/src/quicklog.js +693 -693
  59. package/src/review-tier.js +77 -77
  60. package/src/run/command.js +1385 -1364
  61. package/src/run/complete-handlers.js +1443 -1399
  62. package/src/run/complete.js +225 -24
  63. package/src/run/gates.js +755 -755
  64. package/src/run/prompt.js +761 -761
  65. package/src/run/quick-audit.js +155 -146
  66. package/src/run/shared.js +1268 -1215
  67. package/src/run/stage.js +487 -479
  68. package/src/scan-postcheck.js +371 -371
  69. package/src/setup.js +416 -416
  70. package/src/sillyhub-mcp/client.js +529 -529
  71. package/src/spec-sync.js +323 -319
  72. package/src/stage-contract.js +897 -897
  73. package/src/stage-review.js +549 -549
  74. package/src/stages/archive.js +155 -155
  75. package/src/stages/brainstorm-auto.js +236 -236
  76. package/src/stages/brainstorm.js +596 -597
  77. package/src/stages/cmd-existence.js +145 -145
  78. package/src/stages/doctor.js +371 -371
  79. package/src/stages/execute.js +1003 -1003
  80. package/src/stages/explore.js +34 -34
  81. package/src/stages/index.js +29 -29
  82. package/src/stages/knowledge.js +498 -498
  83. package/src/stages/plan-postcheck.js +1302 -1302
  84. package/src/stages/plan.js +625 -623
  85. package/src/stages/quick.js +151 -151
  86. package/src/stages/scan.js +607 -607
  87. package/src/stages/status.js +64 -64
  88. package/src/stages/verify.js +264 -264
  89. package/src/sync.js +1223 -1135
  90. package/src/task-review.js +1019 -1019
  91. package/src/verify-postcheck.js +1186 -1186
  92. package/src/workflow.js +600 -600
  93. package/src/worktree-apply.js +1213 -1136
  94. package/src/worktree-deps.js +353 -353
  95. package/src/worktree.js +1481 -1481
  96. package/templates/workflows/archive-impact.yaml +79 -79
  97. package/templates/workflows/scan-docs.yaml +132 -132
@@ -1,1364 +1,1385 @@
1
- /**
2
- * run/command.js(W6 Step8c 从 run.js 抽出)。
3
- *
4
- * 命令分发层:runCommand(主入口,被 src/index.js + 6 个 test import)+ auto 模式 +
5
- * ensureStageSteps(被 step-migration test import)+ 4 个 runCommand 私有 helper
6
- * (resolveChangeName / resolveChangeNameAuto / showStatus / resetStage)。
7
- *
8
- * 调用图(单向,无环):runCommand → { runStage(stage.js), runAutoMode, resetStage, showStatus,
9
- * ensureStageSteps, completeStep/skip/wait/continue(complete.js) };runAutoMode → { outputStep,
10
- * completeStep, ensureStageSteps, checkApproval(shared) },不调 runStage(内联 outputStep)。
11
- *
12
- * 安全锚:run.js 始终 barrel。runCommand + ensureStageSteps 被 test 直接 import → run.js barrel
13
- * re-export(契约保留);其余 5 函数 runCommand 私有,无 test 直接 import。
14
- *
15
- * 路径修正(相对 src/run/):
16
- * - 动态 import './init.js' / './worktree.js' / './classify-change.js' → '../'(src/ 下退一层)
17
- * - 'fs'(runCommand 内 await import('fs'))裸模块名不变
18
- * - 静态 import './progress.js' / './stage-contract.js' / './stages/*' / './fs-atomic.js' → '../'
19
- * './run/shared.js' / './run/quick-audit.js' / './run/prompt.js' / './run/complete.js' /
20
- * './run/stage.js' → './shared.js' 等同级
21
- */
22
- import { basename, join, resolve, dirname } from 'node:path'
23
- import { existsSync, readdirSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs'
24
- import { randomBytes, randomUUID } from 'node:crypto'
25
- import { writeAtomicSync } from '../fs-atomic.js'
26
- import { resolveSpecDir, countAncestorSpecDirs, resolveChangeDir, triggerSync, getStageSteps, formatWaitOptions, checkApproval, didYouMean, assertSafeChangeName, detectQuickSessionDrift, detectWorktreeSpecDrift, resolveRuntimeRoot, writePlatformPointer, checkPlatformManaged, PLATFORM_MANAGED_FILENAME } from './shared.js'
27
- import { resolveQuickLinkedChanges } from './quick-audit.js'
28
- import { outputStep } from './prompt.js'
29
- import { completeStep, skipStep, waitStep, continueStep } from './complete.js'
30
- import { runStage } from './stage.js'
31
- import { sanitizeDesc } from '../quicklog.js'
32
- import { ProgressManager } from '../progress.js'
33
- import { validateChangeExists, checkTransition } from '../stage-contract.js'
34
- import { READONLY_AUXILIARY_STAGES } from '../constants.js'
35
- import { stageRegistry, auxiliaryStages } from '../stages/index.js'
36
- import { definition as brainstormAutoDef } from '../stages/brainstorm-auto.js'
37
- import { setQuickFileNotes } from '../quicklog.js'
38
-
39
- // F2/F4: 哪些 flag 吃下一个 token 作「值」(其余 --flag 都是布尔,不吞值)。
40
- // 校验循环只对 VALUE_FLAGS 跳下一个 token(否则 --done 后跟 typo 会被当 --done 的值吞掉)。
41
- // getFlagValue 也据此拒收「下一个 token 是另一个 flag 名」当值。
42
- const VALUE_FLAGS = new Set([
43
- '--reason', '--options', '--answer', '--confirm-mode',
44
- '--output', '--input', '--change', '--linked-changes',
45
- '--spec-dir', '--spec-root', '--runtime-root', '--workspace-id', '--scan-run-id',
46
- '--files', '--file-notes', '--from-step', '--mode', '--dir', '--confirm-mode',
47
- '--base', // scan diff 基线 commit(吃值;只在 run scan --diff 转发路径消费)
48
- ])
49
-
50
- /**
51
- * 检测 `--files` 是否被空格分隔误用(坑 quick-files-space-separated-silently-drops)。
52
- *
53
- * --files 是单值 flag(VALUE_FLAGS:校验循环只跳一个 token、--k=v 只展开一个值),空格分隔的
54
- * 多文件只有首个被当值,其余沦为位置参数被 `:482` 的 `startsWith('--')` 校验静默忽略 →
55
- * guard.allowedFiles 只剩首个 → --done 边界审计误拦,边界保护形同虚设。
56
- *
57
- * 返回 --files 值及其后所有连续非 flag token(疑似被丢的多文件);length > 1 即误用,调用方
58
- * fail-loud(process.exit 2,同 run --json :109 显式拒绝静默吞风格)。贪婪收集多值会破坏
59
- * VALUE_FLAGS 单值框架(校验循环/等号展开/getFlagValue 都假设单值),故仅检测不改语义。
60
- *
61
- * 纯函数:无副作用、不读 process、不 mutate 入参,供 command.js 解析 + 单测复用。
62
- * @param {string[]} flags runCommand 规范化后的 flags 数组(--k=v 已展开)
63
- * @returns {string[]} --files 值 + 其后连续非 flag token;无 --files / 值是 flag 名 / 含逗号 → []
64
- */
65
- export function detectSpaceSeparatedFiles(flags) {
66
- const idx = flags.indexOf('--files')
67
- if (idx === -1) return []
68
- const val = flags[idx + 1]
69
- // 值缺失 / 值本身是 flag 名(--files --done 漏值)/ 逗号分隔(正确用法)→ 不检测
70
- if (!val || val.startsWith('--') || val.includes(',')) return []
71
- const suspects = [val]
72
- for (let j = idx + 2; j < flags.length && !flags[j].startsWith('--'); j++) suspects.push(flags[j])
73
- return suspects
74
- }
75
-
76
- /**
77
- * 从 progress 或变更目录推导变更名
78
- */
79
- function resolveChangeName(cwd, progress, specDir = null) {
80
- if (progress.currentChange) return progress.currentChange
81
- const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
82
- if (!existsSync(changesDir)) return null
83
- const entries = readdirSync(changesDir, { withFileTypes: true })
84
- .filter(e => e.isDirectory() && e.name !== 'archive')
85
- if (entries.length === 1) return entries[0].name
86
- return null
87
- }
88
-
89
- /**
90
- * 确保阶段的 steps 已初始化到 progress
91
- */
92
- export async function ensureStageSteps(progress, stageName, cwd, specDir = null) {
93
- if (!progress.stages) progress.stages = {}
94
-
95
- const steps = await getStageSteps(stageName, cwd, progress, specDir)
96
- if (!steps) return false
97
-
98
- if (!progress.stages[stageName] || !progress.stages[stageName].steps || progress.stages[stageName].steps.length === 0) {
99
- progress.stages[stageName] = {
100
- status: 'in-progress',
101
- startedAt: new Date().toLocaleString('zh-CN',{hour12:false}),
102
- completedAt: null,
103
- steps: steps.map(s => ({ name: s.name, status: 'pending' }))
104
- }
105
- return true // 需要写入
106
- }
107
-
108
- // 检查步骤数量是否匹配(execute 动态步骤可能变化)
109
- if (progress.stages[stageName].steps.length !== steps.length) {
110
- const oldSteps = progress.stages[stageName].steps
111
- progress.stages[stageName].steps = steps.map(s => {
112
- const old = oldSteps.find(step => step.name === s.name)
113
- if (old) return old // 精确名命中 → 保留旧状态
114
- // migratedFrom:新步骤是合并/重命名来的(如 brainstorm 13→8 折叠)。
115
- // 吸收的旧步骤全部 completed → 新步骤标 completed,避免 completed 丢失导致 currentIdx 回跳。
116
- if (Array.isArray(s.migratedFrom) && s.migratedFrom.length > 0) {
117
- const migrated = oldSteps.filter(step => s.migratedFrom.includes(step.name))
118
- if (migrated.length > 0 && migrated.every(step => step.status === 'completed')) {
119
- return { name: s.name, status: 'completed', migratedFrom: true }
120
- }
121
- }
122
- return { name: s.name, status: 'pending' }
123
- })
124
- return true
125
- }
126
-
127
- return false
128
- }
129
-
130
- /**
131
- * run <stage> --help/-h 的用法帮助(runCommand 内 --help 短路调用)。
132
- * 只打印不落盘:帮助查询不该有副作用(建会话/写 QUICKLOG)。
133
- */
134
- function printStageUsage(stageName) {
135
- const stage = stageRegistry[stageName]
136
- console.log(`
137
- sillyspec run ${stageName}${stage && stage.title ? ` — ${stage.title}` : ''}${stage && stage.description ? `\n ${stage.description}` : ''}
138
-
139
- 用法:
140
- sillyspec run ${stageName} 开始/继续该阶段(输出下一步 prompt)
141
- sillyspec run ${stageName} --status 查看阶段进度
142
- sillyspec run ${stageName} --done --output "摘要" [--input "用户原话"] 完成当前步骤
143
- sillyspec run ${stageName} --change <名> 指定变更(多活跃变更必填)
144
-
145
- 通用参数: --done --output --input --status --skip --reset --reopen --from-step
146
- --wait --continue --answer --change --spec-dir --non-interactive
147
- --interactive --skip-approval --json(不支持)
148
- quick 专属: --linked-changes none|a,b --files a.js,b.js --allow-new
149
- --allow-delete --force-baseline --confirm --file-notes
150
- scan 专属: --quick --standard --deep --force-rescan --diff [--base <commit>] [--full] [--report]
151
- archive专属: --confirm
152
- `)
153
- }
154
-
155
- /**
156
- * sillyspec run <stage> 主命令
157
- */
158
- export async function runCommand(args, cwd, specDir = null, opts = {}) {
159
- // W1-B: run <stage> 暂不支持 --json。之前 --json 进 knownFlags 白名单却从不读取(静默吞),
160
- // agent 按 gate/derive 契约期望 envelope 实则拿到混合人类文本。显式 fail-fast 杜绝歧义;
161
- // 完整 run envelope 待 outputStep 重构(W6)后支持(prompt + nextAction 结构化)。
162
- if (opts.json) {
163
- console.error('❌ run <stage> 暂不支持 --json(静默吞是 bug,故显式拒绝)。')
164
- console.error(' 查事实用 gate/derive(支持 --json envelope);run 输出人类可读 prompt 供 agent 直接执行。')
165
- process.exit(2) // 用法错 → exit 2
166
- }
167
- // 解析参数
168
- const stageName = args[0]
169
- let flags = args.slice(1) // let:下方规范化 --k=v 会改写
170
-
171
- // F7: 规范化 --key=value → ['--key', 'value']。许多 CLI 通用等号语法此前被整 token 当未知参数拒绝。
172
- // 只对值类 flag 展开(见 VALUE_FLAGS);布尔 flag 不吃值,--skip-approval=x 这种无意义,原样进校验报错。
173
- flags = flags.flatMap(tok => {
174
- if (typeof tok === 'string' && tok.startsWith('--') && tok.includes('=')) {
175
- const eq = tok.indexOf('=')
176
- const key = tok.slice(0, eq)
177
- const val = tok.slice(eq + 1)
178
- if (VALUE_FLAGS.has(key)) return [key, val]
179
- }
180
- return [tok]
181
- })
182
-
183
- if (!stageName) {
184
- console.error('❌ 请指定阶段,例如: sillyspec run brainstorm')
185
- console.error(`可选: ${Object.keys(stageRegistry).join(', ')}, auto`)
186
- process.exit(2) // 用法错 → exit 2
187
- }
188
-
189
- if (!stageRegistry[stageName] && stageName !== 'auto') {
190
- console.error(`❌ 未知阶段: ${stageName}`)
191
- console.error(`可选: ${Object.keys(stageRegistry).join(', ')}, auto`)
192
- process.exit(2) // 用法错 → exit 2
193
- }
194
-
195
- // ── cwd 纠正:向上查找真实项目根 ──
196
- // 防止多 project 工作区中 cwd 停在子目录(如 backend/)时
197
- // 状态写入子目录下误建的 .sillyspec,导致状态分裂
198
- if (!specDir && !existsSync(join(cwd, '.sillyspec-platform.json'))) {
199
- // 平台模式(cwd 有 .sillyspec-platform.json 指针)不做 cwd 纠正:指针已明确 specDir,
200
- // 向上找 .sillyspec 反而会撞到无关项目(如用户 home 的 .sillyspec),导致 --done 恢复
201
- // 读写 ~/.sillyspec-platform.json 出错的 specRoot。
202
- const resolvedRoot = resolveSpecDir(cwd)
203
- if (resolvedRoot && resolvedRoot !== join(cwd, '.sillyspec')) {
204
- const realRoot = dirname(resolvedRoot)
205
- if (realRoot !== cwd) {
206
- cwd = realRoot
207
- }
208
- }
209
- }
210
-
211
- // 平台模式参数(供 SillyHub 等平台调用)
212
- // --spec-dir 是统一参数名,--spec-root 保留为向后兼容别名
213
- const getFlagValue = (name) => {
214
- const idx = flags.indexOf(name)
215
- if (idx === -1) return null
216
- const next = flags[idx + 1]
217
- // F4: 下一个 token 若是另一个 flag 名(--xxx),说明本 flag 漏值,
218
- // 不能把 flag 名当值返回(否则 --change --done → changeName="--done" 一路污染)。
219
- if (!next || (typeof next === 'string' && next.startsWith('--'))) return null
220
- return next
221
- }
222
- const isDone = flags.includes('--done')
223
- const isSkip = flags.includes('--skip')
224
- const isStatus = flags.includes('--status')
225
- const isReset = flags.includes('--reset')
226
- const isReopen = flags.includes('--reopen')
227
- const fromStepValue = getFlagValue('--from-step')
228
- const isConfirm = flags.includes('--confirm')
229
- const isSkipApproval = flags.includes('--skip-approval')
230
- const isWait = flags.includes('--wait')
231
- const isContinue = flags.includes('--continue')
232
- const isNonInteractive = flags.includes('--non-interactive')
233
- const isInteractive = flags.includes('--interactive')
234
- // F3 冲突 flag 检测:步骤/阶段动作 flag 互斥——各自定义「对当前步骤做什么」,同时给 2+ 个
235
- // 语义矛盾。旧实现按代码里 if 顺序静默取先命中的、其余被忽略,agent 以为生效的其实没生效
236
- // (如 --done --reset 只 reset 不 done,agent 却以为完成了步骤)。显式报冲突让 agent 选一个。
237
- const STEP_ACTIONS = [
238
- ['--done', isDone, '完成当前步骤'],
239
- ['--skip', isSkip, '跳过当前步骤'],
240
- ['--reset', isReset, '重置整个阶段(从头开始)'],
241
- ['--reopen', isReopen, '重新打开已完成阶段进入修订(配 --from-step)'],
242
- ['--wait', isWait, '暂停等用户决策'],
243
- ['--continue', isContinue, '恢复等待中的步骤'],
244
- ['--status', isStatus, '查看进度(只读)'],
245
- ]
246
- const activeActions = STEP_ACTIONS.filter(([, v]) => v)
247
- if (activeActions.length >= 2) {
248
- console.error('❌ 步骤动作参数冲突(同时只能指定一个):')
249
- for (const [name, , desc] of activeActions) console.error(` ${name} — ${desc}`)
250
- console.error(' 这些动作互斥,请只保留其中一个再重试。')
251
- process.exit(2)
252
- }
253
- // scan profile flag 互斥:--quick/--standard/--deep 同时给≥2 个语义矛盾(computeScanProfile
254
- // 只取首个命中、其余静默忽略 → agent 以为生效的其实没生效,与 STEP_ACTIONS 同类风险)。
255
- const PROFILE_FLAGS = [
256
- ['--quick', flags.includes('--quick'), 'quick profile(快速接入,4 份核心文档)'],
257
- ['--standard', flags.includes('--standard'), 'standard profile(压缩步骤)'],
258
- ['--deep', flags.includes('--deep'), 'deep profile(完整扫描)'],
259
- ]
260
- const activeProfiles = PROFILE_FLAGS.filter(([, v]) => v)
261
- if (activeProfiles.length >= 2) {
262
- console.error('❌ scan profile 参数冲突(同时只能指定一个):')
263
- for (const [name, , desc] of activeProfiles) console.error(` ${name} — ${desc}`)
264
- console.error(' 这三档互斥,请只保留其中一个再重试。')
265
- process.exit(2)
266
- }
267
- // 注:--non-interactive 与 --interactive 的冲突在 index.js 检测(--interactive 被 index.js
268
- // 作为全局 flag 吞掉、不透传到此处,故 isInteractive 在此恒为 false)。
269
- const waitReason = getFlagValue('--reason')
270
- const waitOptions = getFlagValue('--options')
271
- const continueAnswer = getFlagValue('--answer')
272
- const resolvedSpecDir = specDir || getFlagValue('--spec-dir') || getFlagValue('--spec-root')
273
- const platformOpts = {
274
- specRoot: resolvedSpecDir ? resolve(resolvedSpecDir) : null,
275
- runtimeRoot: getFlagValue('--runtime-root') ? resolve(getFlagValue('--runtime-root')) : null,
276
- workspaceId: getFlagValue('--workspace-id'),
277
- scanRunId: getFlagValue('--scan-run-id'),
278
- }
279
-
280
- // 跨 --done 生命周期:从 metadata 文件恢复 platformOpts
281
- // 首次 scan 时写入,所有后续调用(包括 run、--done、--skip)都读取
282
- // 优先在 specDir 下查找,否则回退到 cwd/.sillyspec/.runtime/
283
- let specRoot = platformOpts.specRoot || resolveSpecDir(cwd)
284
- // 平台参数恢复策略:
285
- // 1. 优先检查 cwd/.sillyspec-platform.json(轻量指针文件,不污染 .sillyspec 结构)
286
- // 2. 然后检查 specRoot/.runtime/platform-scan.json(首次 scan 写入)
287
- const platformPointer = join(cwd, '.sillyspec-platform.json')
288
- const platformScanFile = join(specRoot, '.runtime', 'platform-scan.json')
289
- let platformOptsFile = existsSync(platformPointer) ? platformPointer : platformScanFile
290
- let platformFileExists = existsSync(platformOptsFile)
291
- // 如果命令行没传 spec-root,尝试从持久化文件恢复
292
- if (!platformOpts.specRoot && !platformOpts.runtimeRoot) {
293
- if (platformFileExists) {
294
- try {
295
- const { readFileSync } = await import('fs')
296
- const saved = JSON.parse(readFileSync(platformOptsFile, 'utf8'))
297
- if (saved.specRoot) platformOpts.specRoot = saved.specRoot
298
- if (saved.runtimeRoot) platformOpts.runtimeRoot = saved.runtimeRoot
299
- if (saved.workspaceId) platformOpts.workspaceId = saved.workspaceId
300
- if (saved.scanRunId) platformOpts.scanRunId = saved.scanRunId
301
- // 平台模式 fail-fast:文件存在但缺少 specRoot
302
- if (!platformOpts.specRoot && !platformOpts.runtimeRoot) {
303
- console.error(`❌ 平台模式参数文件存在但缺少 specRoot/runtimeRoot: ${platformOptsFile}`)
304
- console.error(' 可能原因:platform-scan.json 损坏或写入不完整')
305
- console.error(' 解决:重新运行首次 scan 并传入 --spec-root')
306
- process.exit(2) // 环境错(平台文件损坏)→ exit 2
307
- }
308
- // 恢复成功:更新 specRoot(初始值可能是 cwd/.sillyspec,恢复后应为真实 specDir)
309
- specRoot = platformOpts.specRoot || specRoot
310
- } catch (e) {
311
- console.error(`❌ 平台模式参数文件读取失败: ${platformOptsFile}`)
312
- console.error(` 错误: ${e.message}`)
313
- console.error(' 可能原因:文件损坏')
314
- console.error(' 解决:删除该文件并重新运行首次 scan 传入 --spec-root')
315
- process.exit(2) // 环境错(文件损坏)→ exit 2
316
- }
317
- }
318
- }
319
- // ── 平台接管声明 fail-closed(入口二,D-B@v2)──
320
- // runCommand 有独立指针恢复链(不经 resolvePlatformSpecDir),指针缺失时若不在此
321
- // 封堵,run/quick/scan 等全部 stage 命令会静默落本地库(与入口一行为分裂)。
322
- // 触发条件:命令行没传平台参数 + 指针与 platform-scan.json 皆未命中 + 接管声明存在。
323
- // 显式 --spec-dir/--spec-root 传参时 platformOpts.specRoot 已赋值,天然不进此分支(逃生口)。
324
- if (!platformOpts.specRoot && !platformOpts.runtimeRoot && !platformFileExists) {
325
- const decl = checkPlatformManaged(cwd)
326
- if (decl) {
327
- console.error(`❌ 平台接管声明生效:本项目已由平台托管(原 specRoot: ${decl.specRoot || '(未记录)'}),但恢复指针缺失,拒绝静默回退本地模式。`)
328
- console.error(` 声明文件: ${join(cwd, PLATFORM_MANAGED_FILENAME)}`)
329
- console.error(' 恢复:① 重跑平台 scan/init(带 --spec-root)重建指针;② 确认不再使用平台:sillyspec platform disconnect(删除接管声明);③ 显式 --spec-dir <路径> 临时指定目录。')
330
- // exit(1) 而非邻近环境错的 exit(2):这是"状态保护阻断"(对齐 PointerUnreachableError
331
- // 顶层 catch 语义),非"用法/环境错"——见 design.md §5.3 v2 复审观察 (a)
332
- process.exit(1)
333
- }
334
- }
335
- // 持久化 platformOpts
336
- // 在 specRoot/.runtime/ 写主文件,同时在 cwd 下写恢复指针
337
- // (writePlatformPointer 收敛双写逻辑,cmdInit 平台模式共用,防两处字段漂移)
338
- if (platformOpts.specRoot || platformOpts.runtimeRoot) {
339
- writePlatformPointer(cwd, platformOpts)
340
- }
341
-
342
- // 统一规范基路径:平台模式用 specRoot,本地模式用 cwd/.sillyspec
343
- // runCommand 后续所有 .sillyspec/ 操作必须用 specBase
344
- // let:下方 worktree 副本漂移守卫命中时锚回 wt.mainSpecBase(task-05/D-03)
345
- let specBase = platformOpts.specRoot || join(cwd, '.sillyspec')
346
-
347
- // 漂移提醒:cwd 祖先链 ≥2 个 .sillyspec = monorepo 多实例,当前命中的「最近」实例
348
- // 可能不是用户意图的项目(如 cd 进被独立 scan 的子项目跑测试后忘回根)。
349
- // 平台模式 / 显式 --spec-dir 跳过(已明确指定,无歧义)。仅提醒不阻断。
350
- if (!platformOpts.specRoot && !specDir) {
351
- const ancestorCount = countAncestorSpecDirs(cwd)
352
- if (ancestorCount >= 2) {
353
- console.warn(`⚠️ 检测到祖先链有 ${ancestorCount} 个 .sillyspec 实例(monorepo 多实例),当前使用: ${specBase}`)
354
- console.warn(` 若意图是另一个项目:cd 回该项目根,或用 --spec-dir <根>/.sillyspec 显式指定。`)
355
- }
356
- }
357
-
358
- // scan diff 转发(D-001@v1:command.js 只认 --diff flag,等价 `sillyspec scan diff` 子命令;
359
- // 裸 token `run scan diff` 不在此解析——那是 index.js 子命令拦截的职责,防 command.js 静默吞)。
360
- // 纯只读比较:零会话/QUICKLOG 副作用,仅解析 --base/--full/--report 后转发 scan-diff 退出码。
361
- if (stageName === 'scan' && flags.includes('--diff')) {
362
- const { runScanDiff } = await import('../scan-diff.js')
363
- const diffBaseIdx = flags.indexOf('--base')
364
- const diffBase = diffBaseIdx >= 0 && flags[diffBaseIdx + 1] ? flags[diffBaseIdx + 1] : null
365
- process.exitCode = runScanDiff({
366
- projectRoot: cwd,
367
- specBase,
368
- projectName: basename(cwd),
369
- base: diffBase,
370
- full: flags.includes('--full'),
371
- report: flags.includes('--report'),
372
- })
373
- return
374
- }
375
-
376
- // 平台模式:首次接入时清理旧版本残留的 cwd/.sillyspec/(防止源码污染)。
377
- // ⚠️ 同 init.js:必须保护真实资产(changes/、projects/、sillyspec.db)。
378
- // 只在「首次」执行一次——用 cwd 下的 .sillyspec-platform-cleaned 标记文件记录已处理,
379
- // 后续每次 run 直接跳过,避免重复检查 + 红叉噪声(此清理不阻塞流程、不动真实资产)。
380
- if (platformOpts.specRoot) {
381
- const legacyDir = join(cwd, '.sillyspec')
382
- const cleanedMarker = join(cwd, '.sillyspec-platform-cleaned')
383
- if (!existsSync(cleanedMarker)) {
384
- if (existsSync(legacyDir)) {
385
- let hasChanges = false;
386
- try {
387
- const cd = join(legacyDir, 'changes');
388
- if (existsSync(cd)) hasChanges = readdirSync(cd).length > 0;
389
- } catch {}
390
- let hasProjects = false;
391
- try {
392
- const pd = join(legacyDir, 'projects');
393
- if (existsSync(pd)) hasProjects = readdirSync(pd).length > 0;
394
- } catch {}
395
- const hasDb = existsSync(join(legacyDir, 'sillyspec.db'));
396
-
397
- if (hasChanges || hasProjects || hasDb) {
398
- // 真实资产存在:只清运行时残留(白名单保留 worktrees/进度),不整删
399
- const { cleanupRuntimeResidue } = await import('../init.js')
400
- cleanupRuntimeResidue(legacyDir);
401
- console.log('ℹ️ [sillyspec] 源码目录 .sillyspec/ 含真实资产,已跳过整删,仅清理运行时残留(仅本次首次,后续不再提示)。');
402
- } else {
403
- try { rmSync(legacyDir, { recursive: true, force: true }) } catch {}
404
- if (!existsSync(legacyDir)) console.log('🧹 已清理旧版本残留的源码 .sillyspec/ 目录');
405
- }
406
- }
407
- // 标记本 cwd 已做平台残留清理决策,后续 run 跳过(即使之后 .sillyspec/ 被重建也不误清)
408
- try { writeFileSync(cleanedMarker, new Date().toISOString() + '\n') } catch {}
409
- }
410
- }
411
-
412
- // 解析 --output
413
- let outputText = null
414
- const outputIdx = flags.indexOf('--output')
415
- if (outputIdx !== -1 && flags[outputIdx + 1]) {
416
- outputText = flags[outputIdx + 1]
417
- }
418
-
419
- // 解析 --input
420
- let inputText = null
421
- const inputIdx = flags.indexOf('--input')
422
- if (inputIdx !== -1 && flags[inputIdx + 1]) {
423
- inputText = flags[inputIdx + 1]
424
- }
425
-
426
- // 解析 --linked-changes <a,b|none>(quick 专用:显式声明关联变更,CI/脚本友好)
427
- // 与 --change 解耦:--linked-changes 语义清晰(关联变更),不与「指定变更名」混淆。
428
- // null = 未指定(走持久化/交互/兼容回退);[] = 显式 none(不关联);[...] = 显式列表
429
- let explicitLinked = null
430
- const linkedIdx = flags.indexOf('--linked-changes')
431
- if (linkedIdx !== -1 && flags[linkedIdx + 1]) {
432
- const v = flags[linkedIdx + 1].trim()
433
- explicitLinked = v.toLowerCase() === 'none' ? [] : v.split(',').map(s => s.trim()).filter(Boolean)
434
- }
435
-
436
- // 解析 --change <name>(quick 阶段向后兼容:逗号分隔作为「关联变更」;
437
- // 历史写法,语义与「指定变更名」冲突,新用法建议改用 --linked-changes)
438
- let changeName = null
439
- let linkedChanges = []
440
- const changeIdx = flags.indexOf('--change')
441
- if (changeIdx !== -1 && flags[changeIdx + 1]) {
442
- changeName = flags[changeIdx + 1]
443
- if (stageName === 'quick') {
444
- linkedChanges = changeName.split(',').map(s => s.trim()).filter(Boolean)
445
- changeName = null
446
- }
447
- }
448
- // --linked-changes 优先于 --change(显式 > 隐式兼容)
449
- if (explicitLinked !== null) {
450
- linkedChanges = explicitLinked
451
- }
452
- // F6 路径穿越消毒:change 名会被 join 进 .sillyspec/changes/<name>/ 当目录名,
453
- // 含 ../ 或路径分隔符会逃出 changes/ 写到任意位置。quick 的 --change 复用为 sessionId
454
- // (quick-<8hex>,正则已约束) 或 linkedChanges,故 quick 的 changeName 不在此校验。
455
- try {
456
- if (stageName !== 'quick' && changeName) assertSafeChangeName(changeName)
457
- for (const lc of linkedChanges) {
458
- if (lc && lc !== 'none') assertSafeChangeName(lc, '关联变更名(--linked-changes)')
459
- }
460
- } catch (e) {
461
- console.error(`❌ ${e.message}`)
462
- console.error(` 合法变更名示例:2026-07-27-add-login(仅字母/数字/._-,不含 / \\ ..)`)
463
- process.exit(2)
464
- }
465
- // quick 会话隔离(D-001@v1 + D-003@v1 + §4.4 跨进程传递):每会话用 sessionId 作 changeName,
466
- // DB 分行 progress.quick-<uuid8>,避免并行 quick 会话共享单行 progress.default.quick 互相覆盖。
467
- // sessionId = crypto.randomUUID 前 8 hex(摒弃旧 quick-YYYYMMDD-HHMMSS 时间戳,同秒并发撞)。
468
- // crypto.randomUUID 从 node:crypto import(兼容 engines node>=18,不依赖 Node 19+ 全局)。
469
- //
470
- // --done 跨进程恢复 sessionId 的优先级(§4.4):
471
- // 1. --change quick-<uuid8>(单值且匹配 sessionId 形态)→ 精确指定本会话 sessionId
472
- // (quick 的 --change 历史被复用为 linkedChanges 见上 1370-1377;此处对「恰好一个 quick-<8hex>」
473
- // 特例识别为 sessionId,多值/不匹配仍走 linkedChanges 语义,向后兼容)
474
- // 2. 未识别出 sessionId 且为 --done → fallback 读 .runtime/current-quick-run-id(单会话兼容;
475
- // 多会话时可能拿到他者,文档声明建议带 --change)
476
- // 3. 仍读不到 → 生成新 UUID(兼容旧行为;进度可能命中空行,由后续 pm.read 兜底)
477
- const QUICK_SID_RE = /^quick-[0-9a-f]{8}$/
478
- let quickSessionId = null
479
- let quickFallbackUsed = false // Q7: --done 未带 --change 时 fallback 读 current-quick-run-id 命中(区别于显式 --change quick-<hex>)
480
- if (stageName === 'quick') {
481
- // 1373-1376 已把 quick 的 --change 值清进 linkedChanges、changeName 置 null。
482
- // 此处回看 --change 原始值:若恰好是单个 quick-<8hex> → 识别为本会话 sessionId(精确恢复),
483
- // 并撤销把它当 linkedChanges 的误判。多值或不匹配 → 维持 linkedChanges 语义(旧兼容)。
484
- const rawChange = changeIdx !== -1 && flags[changeIdx + 1] ? flags[changeIdx + 1].trim() : null
485
- const rawIsSingleSid = rawChange && rawChange.indexOf(',') === -1 && QUICK_SID_RE.test(rawChange)
486
- if (rawIsSingleSid) {
487
- // --done --change quick-<uuid8>:精确恢复(撤销 1373-1376 把它误当 linkedChanges)
488
- quickSessionId = rawChange
489
- changeName = rawChange
490
- linkedChanges = []
491
- } else if (!changeName) {
492
- // 未精确指定:非 --done 必生成新 sessionId;--done 先 fallback current-quick-run-id,读不到再生成
493
- const isDoneLike = isDone || isStatus || isSkip || isReset || isReopen
494
- if (isDoneLike) {
495
- try {
496
- const runtimeRoot = resolveRuntimeRoot(platformOpts, specRoot)
497
- const idFile = join(runtimeRoot, 'current-quick-run-id')
498
- if (existsSync(idFile)) {
499
- const v = readFileSync(idFile, 'utf8').trim()
500
- if (QUICK_SID_RE.test(v)) { quickSessionId = v; quickFallbackUsed = true }
501
- }
502
- } catch {}
503
- }
504
- if (!quickSessionId) {
505
- quickSessionId = 'quick-' + randomUUID().slice(0, 8)
506
- }
507
- changeName = quickSessionId
508
- } else {
509
- // 用户显式传了非 sessionId 形态的变更名 → 尊重,不生成 UUID(旧兼容路径)
510
- quickSessionId = changeName
511
- }
512
- }
513
-
514
- // quick 关联变更存在性守卫(坑 quick-change-phantom-linked):quick 的 --change/--linked-changes
515
- // 被解析为关联变更后静默接受不存在的名字(quick 不建变更,链接幻影名必是笔误/语义误用——想给
516
- // 会话起名却传了 --change),后果是 QUICKLOG 挂悬空关联污染 change 关联图谱 + --done 时 sessionId
517
- // 走 fallback 可能命中他者会话。f70c9c3 只修了「建幻影目录」后果(appendTaskCheckbox 加
518
- // existsSync 守卫),本守卫把误用拦在 flag 装载层。只校验 CLI 显式装载的 linkedChanges;
519
- // 持久化 guard.json 复用(下方 run↔--done 之间变更可能被归档)与交互式选择(列表只列存在项)不检。
520
- if (stageName === 'quick' && linkedChanges.length > 0) {
521
- const missing = linkedChanges.filter(lc => lc !== 'none' && !existsSync(join(specRoot, 'changes', lc)))
522
- if (missing.length > 0) {
523
- console.error(`❌ quick 的 --change/--linked-changes 被当作「关联变更」处理,但以下变更不存在:${missing.join('、')}`)
524
- console.error(' (quick 不创建变更,关联的变更必须预先存在)')
525
- console.error(' - 想给会话起名:不要传 --change,sessionId 由 CLI 自动生成(后续 --done 用它)')
526
- console.error(' - 想关联变更:修正拼写(.sillyspec/changes/ 下已存在的目录名),显式写法 --linked-changes <名>')
527
- console.error(' - 想新建变更:quick 不建变更,走 brainstorm 完整流程')
528
- process.exit(2)
529
- }
530
- }
531
-
532
- // 解析 --files a.js,b.js(quick 专用:显式声明 allowedFiles)
533
- // --files 是单值 flag,空格分隔的多文件只取首个致其余静默丢失(坑 quick-files-space-separated-silently-drops)。
534
- // detectSpaceSeparatedFiles 检测误用 → fail-loud 报错指明逗号用法(同 run --json :109 风格)。
535
- const spaceSuspects = detectSpaceSeparatedFiles(flags)
536
- if (spaceSuspects.length > 1) {
537
- console.error('❌ --files 检测到空格分隔的多文件:CLI 只识别首个,其余会被静默丢弃(边界保护失效)。')
538
- console.error(` 疑似多文件:${spaceSuspects.join(' ')}`)
539
- console.error(' --files 是单值参数,多文件请用逗号分隔(无空格):')
540
- console.error(` --files ${spaceSuspects.join(',')}`)
541
- process.exit(2) // 用法错 → exit 2
542
- }
543
- let quickFiles = []
544
- const filesIdx = flags.indexOf('--files')
545
- if (filesIdx !== -1 && flags[filesIdx + 1]) {
546
- quickFiles = flags[filesIdx + 1].split(',').map(f => f.trim()).filter(Boolean)
547
- }
548
-
549
- // 解析 --file-notes "path::括注 || path::括注"(quick 专用:QUICKLOG「文件:」行落盘多行括注)。
550
- // 旁路注入 quicklog.js(per-process setter),不经 complete 收尾路径透传(避碰多 agent 并发改的收尾热点)。
551
- // completeQuicklogEntry 读后即清;不传 → '' → 回填审计到的实际文件单行(向后兼容)。
552
- let quickFileNotes = ''
553
- const fileNotesIdx = flags.indexOf('--file-notes')
554
- if (fileNotesIdx !== -1 && flags[fileNotesIdx + 1]) {
555
- quickFileNotes = flags[fileNotesIdx + 1]
556
- }
557
- setQuickFileNotes(quickFileNotes)
558
-
559
- const isAllowNew = flags.includes('--allow-new')
560
- const isAllowDelete = flags.includes('--allow-delete')
561
- const isForceBaseline = flags.includes('--force-baseline')
562
- const isForceRescan = flags.includes('--force-rescan')
563
-
564
- // 未知参数 fail-fast
565
- const knownFlags = new Set([
566
- '--done', '--skip', '--status', '--reset', '--confirm', '--skip-approval',
567
- '--wait', '--continue', '--non-interactive', '--interactive',
568
- '--reason', '--options', '--answer', '--confirm-mode',
569
- '--output', '--input', '--change', '--linked-changes',
570
- '--spec-dir', '--spec-root', '--runtime-root', '--workspace-id', '--scan-run-id',
571
- '--files', '--file-notes', '--allow-new', '--allow-delete', '--force-baseline', '--force-rescan',
572
- '--json', '--dir', '--help',
573
- '--reopen', '--from-step', '--mode',
574
- '--deep', '--quick', '--standard', // scan profile 三档显式选择(scan-profile.js 从 argv 读;互斥见下方 PROFILE_FLAGS 检测)
575
- '--diff', '--base', '--full', '--report', // scan diff(D-001:command.js 只补 flag,裸 token 解析归 index.js 子命令拦截)
576
- '-h',
577
- ])
578
- for (let i = 0; i < flags.length; i++) {
579
- const f = flags[i]
580
- if (f.startsWith('--')) {
581
- if (!knownFlags.has(f)) {
582
- // F10: flag 级 did-you-mean(此前只命令级有)
583
- const suggestion = didYouMean(f, [...knownFlags])
584
- console.error(`❌ 未知参数: ${f}`)
585
- if (suggestion) console.error(` 你是想输入「${suggestion}」吗?`)
586
- else console.error(`已知参数: ${[...knownFlags].sort().join(', ')}`)
587
- process.exit(2) // 用法错 → exit 2
588
- }
589
- // F2: 只有吃值的 flag 才跳下一个 token。布尔 flag(--done 等)不能 i++——
590
- // 否则会把紧跟的 typo flag 当成 --done 的「值」吞掉,既不校验也不生效(静默忽略)。
591
- if (VALUE_FLAGS.has(f)) i++
592
- }
593
- }
594
-
595
- // ── --help/-h 短路:flag 校验通过后、任何副作用(cwd 纠正/会话创建/QUICKLOG 落盘)之前 ──
596
- // --help 此前在 knownFlags 白名单里被静默吞掉,run quick --help 会误开 quick 会话+写骨架
597
- // 条目(查询意图不该有副作用);-h 更是被当未知参数 exit 2。帮助查询 = 用法展示 = 退出 0。
598
- if (flags.includes('--help') || flags.includes('-h')) {
599
- printStageUsage(stageName)
600
- process.exit(0)
601
- }
602
-
603
- const isAuxiliary = auxiliaryStages.includes(stageName)
604
- // scan 元数据追踪(存储在 stageData.scanMeta 中,completeStep 通过 progress 访问)
605
-
606
- // let:下方 worktree 副本漂移守卫命中时用主仓 specRoot 重建 pm(task-05/D-03)
607
- let pm = new ProgressManager({ specDir: specRoot })
608
-
609
- // quick 阶段:确定关联变更
610
- // 优先级:--linked-changes / --change 显式 > 已持久化 quick-guard.json(--done 复用)> 交互式 > 非交互 fallback
611
- // 关键:--done 收尾时复用首次 run 持久化的 linkedChanges,不在管道/CI 下重复弹交互 prompt。
612
- // explicitLinked === null 且未传 --change 时才进入此分支(显式 --linked-changes none 不应触发交互)。
613
- if (stageName === 'quick' && explicitLinked === null && linkedChanges.length === 0) {
614
- // D-002:guard 按 session 存(.runtime/quick-sessions/<sessionId>/guard.json)。
615
- // sessionId == changeName == quick-<uuid8>(上面参数解析已确定)。回退读旧单文件 quick-guard.json(task-03 前兼容)。
616
- let persistedLinked = null
617
- try {
618
- const sessionGuardFile = join(specRoot, '.runtime', 'quick-sessions', changeName, 'guard.json')
619
- const legacyGuardFile = join(specRoot, '.runtime', 'quick-guard.json')
620
- const g = existsSync(sessionGuardFile)
621
- ? JSON.parse(readFileSync(sessionGuardFile, 'utf8'))
622
- : (existsSync(legacyGuardFile) ? JSON.parse(readFileSync(legacyGuardFile, 'utf8')) : null)
623
- if (g && Array.isArray(g.linkedChanges)) persistedLinked = g.linkedChanges
624
- } catch {}
625
- if (persistedLinked) {
626
- linkedChanges = persistedLinked
627
- } else {
628
- linkedChanges = await resolveQuickLinkedChanges({
629
- pm, cwd, specDir: specRoot, quickFiles,
630
- taskDescription: inputText || '',
631
- nonInteractive: isNonInteractive,
632
- })
633
- }
634
- }
635
-
636
- // execute 阶段必须带 --change:不允许自动检测或默认值,变更名必须由 agent 显式传入
637
- // --status 豁免(纯查看不需要指定变更)
638
- if (stageName === 'execute' && !changeName && !isStatus) {
639
- console.error('❌ execute 阶段必须用 --change <变更名> 指定要操作的变更。')
640
- console.error(' agent 必须传参,不设默认值、不做自动检测。')
641
- console.error(' 请加 --change <变更名> 重新执行。')
642
- process.exit(2) // 用法错(execute 必须显式 --change)→ exit 2
643
- }
644
-
645
- // worktree 副本漂移自动锚定守卫(坑 worktree-execute-spec-drift,D-03@v1):specBase 命中 worktree 内
646
- // .sillyspec checkout 副本 = agent 误 cd 进 worktree 跑 plan/execute/verify/archive(100% 误操作场景)。
647
- // 不 exit:自动把 specBase 锚回主仓 wt.mainSpecBase 后继续——进度/产出落主仓,不再写分裂副本(副本随
648
- // 工作树清理丢失)。必须在 validateChangeExists 之前:副本里 change 目录真实存在,存在性校验会被骗
649
- // 放行;锚定后用主仓 specBase 复查。覆盖 plan/execute/verify/archive(validateChangeExists 同 Set)。
650
- // 关键坑:连带重写 specBase/specRoot/specDir + 重建 pm——四者同源派生(pm._customSpecDir 持旧 specRoot),
651
- // 只改 specBase 会让下游 validateChangeExists(specBase) 与 pm.read(走 pm._customSpecDir) 仍指副本。
652
- // 平台模式/显式 --spec-dir 跳过(已明确指定,与 line~285 warn / quick 守卫条件对齐)。
653
- // 其他漂移(下方 changeMissing 守卫 / quick session drift 守卫)非副本场景,仍 exit(2) 不自动纠正。
654
- if (!platformOpts.specRoot && !specDir
655
- && ['plan', 'execute', 'verify', 'archive'].includes(stageName)) {
656
- const wt = detectWorktreeSpecDrift(specBase)
657
- if (wt) {
658
- specBase = wt.mainSpecBase
659
- specRoot = wt.mainSpecBase
660
- specDir = wt.mainSpecBase
661
- pm = new ProgressManager({ specDir: specRoot })
662
- // 【坑 execute-runs-isolation】下游 runtimeRoot 解析(execute-runs/stage-reviews 落点)经
663
- // platformOpts 透传读此锚点,落主仓 .runtime,不随 worktree cleanup 整目录删消失。
664
- // D-02:只参与 runtimeRoot 解析(resolveRuntimeRoot),绝不设 specRoot/runtimeRoot——
665
- // 否则触发平台 sentinel 副作用(triggerSync/checkApproval 跳过 + prompt 误进平台渲染分支)。
666
- platformOpts.specDriftAnchor = wt.mainSpecBase
667
- console.warn(`⚠️ 已自动锚定主仓 spec:${wt.mainSpecBase}(原 cwd 命中 worktree 副本 ${wt.changeName},已纠正,流程继续)`)
668
- }
669
- }
670
-
671
- // --change 变更名存在性校验(治 cwd 漂移误匹配,缺陷 execute-in-place-windows-pitfalls 坑5):
672
- // 必须在 pm.read/initChange 之前——initChange 会为 --change 指定的新名字创建 changes/ 目录,
673
- // 校验若在其后则目录已存在、永远通过。用原始 changeName(--change 参数),覆盖 plan/execute/
674
- // verify/archive;quick-<8hex> sessionId 与 brainstorm 新建豁免(见 validateChangeExists)。
675
- const changeMissing = validateChangeExists(specBase, stageName, changeName)
676
- if (changeMissing) {
677
- console.error(`❌ ${changeMissing.message}`)
678
- console.error(` 可能 cwd 漂移——当前 cwd=${cwd},命中的 spec=${specBase}。`)
679
- console.error(` 若意图操作别的项目,请 cd 到对应项目根,或用 --spec-dir 指定正确的 spec 目录。`)
680
- process.exit(2) // 环境错(cwd/spec 漂移)→ exit 2
681
- }
682
-
683
- // quick 专用 cwd 漂移 fail-fast 守卫(坑 quick-cwd-drift-splits-specdir):
684
- // quick 被 validateChangeExists 的 sessionId 豁免(quick-<8hex> 不在 changes/ 下),漂移时除上方
685
- // countAncestorSpecDirs 的 warn 外无硬守卫 → 无声分裂(progress/artifact/QUICKLOG 落子项目、根
686
- // 会话停滞)。这里补:当前 specBase 无本 session guard、但祖先链别处有 = 跨 specDir 漂移 → fail-fast。
687
- // 平台模式/显式 --spec-dir 跳过(specBase 已明确,与 line~285 warn 条件对齐)。
688
- if (stageName === 'quick' && changeName && /^quick-[0-9a-f]{8}$/.test(changeName)
689
- && !platformOpts.specRoot && !specDir) {
690
- const drift = detectQuickSessionDrift(cwd, specBase, changeName)
691
- if (drift) {
692
- console.error(`❌ ${drift.message}`)
693
- console.error(` 当前 cwd=${cwd},命中的 spec=${specBase}。`)
694
- process.exit(2) // 环境错(cwd/spec 漂移)→ exit 2
695
- }
696
- }
697
-
698
- let progress = pm.read(cwd, changeName)
699
-
700
- // task-03 (D-005@v2 / FR-04): READONLY_AUXILIARY_STAGES(status/doctor)查询只读短路。
701
- // 无显式写 flag 时在 registerChange / ensureStageSteps 之前拦截,零副作用:
702
- // - 目标 progress 不存在 → 提示「只读查询不建变更」exit 0(不 initChange、不建 default 行,治 8b)
703
- // - 目标 progress 存在 → 只读展示,不 seed steps、不刷新 lastActive、不 registerChange
704
- // (治 B7 多 agent 并发 lastActive 互相覆盖)
705
- // 显式写意图不短路:doctor 写操作 flag(--cleanup-remnant / --align-execute-progress)与
706
- // 步骤动作 flag(--done/--skip/--reset/--reopen/--wait/--continue)走原写路径;--status 本身
707
- // 是只读查询,纳入短路。--fix 是 worktree doctor 的 flag 不在此列(design.md Phase 4)。
708
- const READONLY_WRITE_ACTIONS = ['--cleanup-remnant', '--align-execute-progress', '--done', '--skip', '--reset', '--reopen', '--wait', '--continue']
709
- if (READONLY_AUXILIARY_STAGES.includes(stageName) && !flags.some(f => READONLY_WRITE_ACTIONS.includes(f))) {
710
- if (!progress) {
711
- console.log('ℹ️ 未找到进度数据(只读查询不建变更)')
712
- process.exit(0)
713
- }
714
- // 只读展示路径:复用阶段定义渲染当前步骤 prompt(outputStep 对 status/doctor 纯只读),
715
- // 不落盘任何 progress 改动。--status 走现有 showStatus 展示。
716
- const readOnlyChange = changeName || progress.currentChange || resolveChangeName(cwd, progress, specRoot)
717
- if (isStatus) {
718
- let nextSuggestion = null
719
- try { nextSuggestion = pm._getNextSuggestion(progress) } catch { /* 读建议失败不阻断展示 */ }
720
- return showStatus(progress, stageName, nextSuggestion)
721
- }
722
- const readonlySteps = await getStageSteps(stageName, cwd, progress, specRoot)
723
- if (readonlySteps && readonlySteps.length > 0) {
724
- // 已有进度(历史 seed 过)则渲染当前待办步;无进度从首步开始
725
- const existingSteps = progress.stages?.[stageName]?.steps
726
- const pendingIdx = existingSteps ? existingSteps.findIndex(s => s.status === 'pending' || s.status === 'in-progress') : -1
727
- const stepIdx = pendingIdx !== -1 ? pendingIdx : 0
728
- await outputStep(stageName, stepIdx, readonlySteps, cwd, readOnlyChange, progress.project || null, platformOpts)
729
- }
730
- return
731
- }
732
-
733
- if (!progress) {
734
- // 如果指定了变更名或有变更目录,自动初始化变更的 progress
735
- const autoChange = changeName || resolveChangeNameAuto(cwd, specRoot)
736
- if (autoChange) {
737
- // 创建时即写 title(与 name/KEY 同时落 db):--input 需求描述 sanitizeDesc 优先,无则用 name 兜底。
738
- // proposal 还没写、无权威标题来源,这是临时值;brainstorm/plan 完成 proposal/design 落盘后由
739
- // complete.js 通用完成路径 deriveTitleFromLinkedChange 刷新为真实 # 标题(与 quick 启动 title 同源)。
740
- progress = pm.initChange(cwd, autoChange, { title: inputText ? sanitizeDesc(inputText) : autoChange })
741
- } else if (isAuxiliary) {
742
- let autoName = changeName || resolveChangeNameAuto(cwd, specRoot) || 'default'
743
- // archive 特例:归档后变更从活跃列表排除(listChanges WHERE status='active'),
744
- // 不带 --change 回退 default 会读错变更。无活跃变更时取最新归档变更,读其现有 progress。
745
- if (stageName === 'archive' && autoName === 'default') {
746
- try {
747
- const archiveDir = join(specBase, 'changes', 'archive')
748
- if (existsSync(archiveDir)) {
749
- const latest = readdirSync(archiveDir)
750
- .filter(d => /^\d{4}-\d{2}-\d{2}-.+/.test(d))
751
- .sort()
752
- .pop()
753
- if (latest) {
754
- autoName = latest.replace(/^\d{4}-\d{2}-\d{2}-/, '')
755
- progress = pm.read(cwd, autoName)
756
- }
757
- }
758
- } catch {}
759
- }
760
- changeName = autoName
761
- if (!progress) {
762
- // auxiliary 创建也写 title(--input 优先 / name 兜底),同上完整流程语义。
763
- progress = pm.initChange(cwd, autoName, { title: inputText ? sanitizeDesc(inputText) : autoName })
764
- // initChange 可能因 project 表为空返回 null
765
- if (!progress) {
766
- progress = { currentStage: stageName, stages: {}, lastActive: new Date().toLocaleString('zh-CN', { hour12: false }), project: '' }
767
- }
768
- }
769
- } else {
770
- // brainstorm 作为流程入口,自动生成变更名并初始化
771
- if (stageName === 'brainstorm') {
772
- if (isDone) {
773
- console.error('❌ --done 找不到变更进度数据。')
774
- console.error(' 请用 --change <变更名> 指定要完成的变更,')
775
- console.error(' 或先运行 sillyspec run brainstorm --change <变更名> 初始化。')
776
- process.exit(2) // 用法错(--done 找不到变更,未传 --change)→ exit 2
777
- }
778
- // task-03 (D-006@v1 / FR-05): 无 --change 仅当无已存在活跃变更时 auto-create;
779
- // 多活跃变更仓强制 --change(exit 2 引导),防 B8 幽灵变更。活跃变更数用 pm.listChanges
780
- // (与 progress show 同源,DB changes 表 status='active')。
781
- const activeChanges = pm.listChanges(cwd)
782
- if (activeChanges.length > 0) {
783
- console.error(`❌ 已存在 ${activeChanges.length} 个活跃变更,run brainstorm 无 --change 不会自动创建新变更。`)
784
- console.error(` 活跃变更:${activeChanges.join('、')}`)
785
- console.error(' 请用 --change <变更名> 指定要操作的变更,')
786
- console.error(' 或先归档/收尾现有活跃变更后重试。')
787
- process.exit(2) // 用法错(多活跃变更未指定 --change)→ exit 2
788
- }
789
- const date = new Date().toISOString().slice(0, 10)
790
- const autoName = `${date}-new-change-${randomBytes(4).toString('hex')}`
791
- console.log(`🔄 自动创建变更:${autoName}`)
792
- console.log(` 提示:可以用 --change <名称> 指定自定义变更名`)
793
- console.log(` 或事后重命名:sillyspec change-rename ${autoName} <新名称>`)
794
- // brainstorm 自动创建变更也写 title(--input 需求描述优先 / 自动名兜底),proposal 落盘后刷新。
795
- progress = pm.initChange(cwd, autoName, { title: inputText ? sanitizeDesc(inputText) : autoName })
796
- changeName = autoName
797
- } else {
798
- console.error('❌ 未找到进度数据,请先运行 sillyspec init 或指定 --change <变更名>')
799
- process.exit(2) // 环境错(未 init / 未传 --change)→ exit 2
800
- }
801
- }
802
- }
803
-
804
- // 确保 progress 有 currentChange
805
- const effectiveChange = changeName || progress.currentChange || resolveChangeName(cwd, progress, specRoot)
806
-
807
- // ── Q7:quick --done 不带 --change 时 fallback 读 current-quick-run-id 可能命中他者会话 ──
808
- // 并发两 quick 会话:B 后启动覆盖 A 的 id(last-writer-wins),A 的 --done 不带 --change → 读到 B 的 sessionId
809
- // → 误操作 B 的 progress/QUICKLOG。fallback 命中的会话若已完成或无可推进步骤(id stale / 他者已收尾),
810
- // 拒绝推进并要求显式 --change。(live A/B race 需 per-session 锚 commit,见 review Q2/D2,本守卫只兜 stale/completed。)
811
- if (stageName === 'quick' && isDone && quickFallbackUsed) {
812
- const qs = progress.stages.quick
813
- const hasActionable = qs?.steps && qs.steps.some(s => s.status === 'pending' || s.status === 'waiting' || s.status === 'in-progress')
814
- if (!qs || qs.status === 'completed' || !hasActionable) {
815
- console.error(`\n❌ --done 未带 --change,回退读到的 quick 会话 ${changeName} 已不可推进(已完成或无待办步骤)。`)
816
- console.error(` 并发多 quick 会话时 .runtime/current-quick-run-id 可能指向他者会话(last-writer-wins)。`)
817
- console.error(` 请显式带 --change <quick-session-id> 指定要完成的会话(sillyspec run quick --status 查各会话进度)。`)
818
- process.exit(2) // 用法错(fallback 命中 stale/他者会话)→ exit 2
819
- }
820
- }
821
-
822
- // -- auto 模式:自动推进所有流程阶段
823
- if (stageName === 'auto') {
824
- return await runAutoMode(pm, progress, cwd, flags, effectiveChange, platformOpts)
825
- }
826
-
827
- // --change 只作为变更名标识,不再拦截流程
828
- // 注册变更到全局活跃列表(如果尚未注册)
829
- if (effectiveChange) {
830
- pm.registerChange(cwd, effectiveChange)
831
- }
832
-
833
- // --reset
834
- if (isReset) {
835
- return await resetStage(pm, progress, stageName, cwd, effectiveChange, platformOpts)
836
- }
837
-
838
- // ── 规则 1:completed 阶段直接 run,拒绝(但 --status 放行)──
839
- const stageStatus = progress.stages[stageName]?.status
840
- if (stageStatus === 'completed' && !isReopen && !isStatus) {
841
- console.error(`\n❌ ${stageName} 阶段已完成。`)
842
- console.error(` 使用 --reopen 进行修订,或 --reset 从头开始。`)
843
- console.error(` 修订示例: sillyspec run ${stageName} --reopen --from-step <步骤序号或名称>`)
844
- process.exit(1)
845
- }
846
-
847
- // ── 规则 5:stale 阶段直接 run,拒绝(但 --status / --reset 放行)──
848
- if (stageStatus === 'stale' && !isReopen && !isStatus && !isReset) {
849
- const staleReason = progress.stages[stageName]?.staleReason || '上游阶段已修订'
850
- console.error(`\n⚠️ ${stageName} 阶段已失效(stale)。`)
851
- console.error(` 原因:${staleReason}`)
852
- console.error(` 使用 --reopen --from-step <步骤> 进行修订,或 --reset 从头开始。`)
853
- process.exit(1)
854
- }
855
-
856
- // ── --reopen 处理 ──
857
- if (isReopen) {
858
- // stale/revising 阶段可能 steps 为空,或者 execute 阶段的 steps 需要从最新 plan.md 刷新
859
- const stageDataPre = progress.stages[stageName]
860
- const needsInit = !stageDataPre || !stageDataPre.steps || stageDataPre.steps.length === 0
861
- // execute 阶段在 reopen 时需要从最新 plan.md 重新解析 steps(plan 可能已变更)
862
- if (needsInit || stageName === 'execute') {
863
- const freshSteps = await getStageSteps(stageName, cwd, progress, specRoot)
864
- if (freshSteps && freshSteps.length > 0) {
865
- if (!progress.stages[stageName]) progress.stages[stageName] = { status: 'stale', steps: [] }
866
- progress.stages[stageName].steps = freshSteps.map(s => ({ name: s.name, status: 'pending' }))
867
- pm._write(cwd, progress, effectiveChange)
868
- progress = pm.read(cwd, effectiveChange) || progress
869
- }
870
- }
871
-
872
- const result = pm.reopenStage(cwd, stageName, {
873
- fromStep: fromStepValue,
874
- changeName: effectiveChange,
875
- })
876
- if (!result.ok) {
877
- console.error(`\n❌ ${result.error}`)
878
- if (stageStatus === 'completed') {
879
- console.error(`\n 提示:sillyspec run ${stageName} --reopen --from-step <步骤序号或名称>`)
880
- }
881
- process.exit(1)
882
- }
883
- console.log(`\n🔧 ${stageName} 阶段已重新打开(revision ${result.revision})`)
884
- console.log(` 从步骤「${result.fromStep}」开始修订`)
885
- console.log(` 该步骤及之后的产出需要重新生成。`)
886
- if (stageName === 'execute') console.log(` ⚡ execute 步骤已从最新 plan.md 重新解析。`)
887
- console.log('')
888
-
889
- // 重新读取 progress
890
- progress = pm.read(cwd, effectiveChange) || progress
891
-
892
- // 注入 revision context 到 platformOpts,供 outputStep 使用
893
- const stageData = progress.stages[stageName]
894
- if (stageData && stageData.revision > 0) {
895
- platformOpts._revision = {
896
- revision: stageData.revision,
897
- fromStep: stageData.reopenedFromStep,
898
- }
899
- }
900
- } else {
901
- // 非 reopen 的正常执行:如果阶段处于 revising 状态,也注入 revision context
902
- const revStageData = progress.stages[stageName]
903
- if (revStageData && revStageData.status === 'revising' && revStageData.revision > 0 && !platformOpts._revision) {
904
- platformOpts._revision = {
905
- revision: revStageData.revision,
906
- fromStep: revStageData.reopenedFromStep,
907
- }
908
- }
909
- }
910
-
911
- // quick 启动(非 --done):reset steps + 写 current-quick-run-id(本会话 sessionId,作 --done fallback)。
912
- // sessionId 已在参数解析阶段生成(quickSessionId == changeName == quick-<uuid8>),
913
- // 这里复用同一值写 current-quick-run-id,保证两处一致。
914
- // 旧 quick-YYYYMMDD-HHMMSS 时间戳已摒弃(D-003@v1:同秒并发撞)。
915
- if (stageName === 'quick' && !isDone && !isStatus && !isSkip && !isReset && !isReopen) {
916
- // 不再无条件 reset steps:原逻辑把任何 quick 非 --done 启动都重置为 pending,致 in-progress
917
- // 的 quick 中途查 prompt(sillyspec run quick)丢已 done 的 step 进度(报告
918
- // quick-state-reset-platform-mode)。现保留进度——completed 重跑由 runStage 内
919
- // currentIdx === -1 自动重置(~1944 行);in-progress 输出当前 step;全新由
920
- // ensureStageSteps 初始化;显式从头用 --reset(已由 !isReset 排除出本分支)。
921
- try {
922
- const runtimeRoot = resolveRuntimeRoot(platformOpts, specRoot)
923
- mkdirSync(runtimeRoot, { recursive: true })
924
- writeAtomicSync(join(runtimeRoot, 'current-quick-run-id'), quickSessionId + '\n')
925
- } catch (e) {
926
- // 写失败不能静默:--done 不带 --change 时靠这个文件做跨进程 fallback,写不成就必须显式带 --change
927
- console.warn(`⚠️ current-quick-run-id 写入失败(${e.message}),--done 必须显式带 --change ${quickSessionId}`)
928
- }
929
- // 显式告知 agent 本会话 sessionId + --done 需带 --change(CLI 短进程,run/done 独立进程,
930
- // sessionId 靠 --change 跨进程传递;不带 --change 时 fallback 读 current-quick-run-id,多会话不可靠)
931
- console.log(`📌 本 quick 会话 sessionId: ${quickSessionId}`)
932
- console.log(` 完成时用: sillyspec run quick --done --change ${quickSessionId} --output "..."`)
933
- }
934
-
935
- // 确保步骤已初始化
936
- const changed = await ensureStageSteps(progress, stageName, cwd, specRoot)
937
- if (changed && effectiveChange) {
938
- pm._write(cwd, progress, effectiveChange)
939
- triggerSync(cwd, effectiveChange, platformOpts)
940
- progress = pm.read(cwd, effectiveChange) || progress
941
- }
942
-
943
- // --status
944
- if (isStatus) {
945
- // D9:状态展示末尾附「下一步该跑什么」。pm 持有状态机,按 progress 实际进度算出精确命令;
946
- // 不传则 agent 只看到一堆 step 进度条,却不知道完成后/卡住时下一条命令是什么。
947
- let nextSuggestion = null
948
- try { nextSuggestion = pm._getNextSuggestion(progress) } catch { /* 读建议失败不阻断状态展示 */ }
949
- return showStatus(progress, stageName, nextSuggestion)
950
- }
951
-
952
- // --skip
953
- if (isSkip) {
954
- return await skipStep(pm, progress, stageName, cwd, effectiveChange, platformOpts)
955
- }
956
-
957
- // --wait: 将 step 设为 waiting(独立于 --done)
958
- if (isWait) {
959
- return await waitStep(pm, progress, stageName, cwd, outputText, waitReason, waitOptions, { changeName: effectiveChange, nonInteractive: isNonInteractive && !isInteractive, platformOpts })
960
- }
961
-
962
- // --continue: 从 waiting 恢复
963
- if (isContinue) {
964
- return await continueStep(pm, progress, stageName, cwd, continueAnswer, { changeName: effectiveChange, nonInteractive: isNonInteractive && !isInteractive, platformOpts, fromStep: fromStepValue })
965
- }
966
-
967
- // --done
968
- if (isDone) {
969
- // task-03 (D-004@v1 / FR-02): --done 与 runStage(stage.js:35-45)同源状态转换守卫,
970
- // 含 fromStageData 透传(让 scan failed_post_check 门控对 --done 同样生效)。
971
- // auxiliary 的 --done 不受影响(checkTransition 对 auxiliary toStage 放行,见 stage-contract.js)。
972
- // --skip-approval 绕过语义对齐 runStage(打错但放行)。
973
- const prevStage = progress.currentStage || ''
974
- const fromStageData = (progress.stages && prevStage && progress.stages[prevStage]) || undefined
975
- const transition = checkTransition(prevStage, stageName, fromStageData ? { fromStageData } : {})
976
- if (!transition.allowed) {
977
- console.error(`❌ 阶段转换不允许: ${prevStage || '(起始)'} → ${stageName}`)
978
- console.error(` 原因: ${transition.reason}`)
979
- console.error(` 提示: 使用 --skip-approval 绕过(需明确意图)`)
980
- if (!isSkipApproval) {
981
- process.exit(1)
982
- }
983
- }
984
- const doneAnswer = getFlagValue('--answer')
985
- return await completeStep(pm, progress, stageName, cwd, outputText, inputText, { confirm: isConfirm, changeName: effectiveChange, nonInteractive: isNonInteractive && !isInteractive, platformOpts, doneAnswer, isForceBaseline, isAllowNew, isAllowDelete })
986
- }
987
-
988
- // 默认:输出当前步骤
989
- return await runStage(pm, progress, stageName, cwd, effectiveChange, isSkipApproval, platformOpts, { quickFiles, isAllowNew, isAllowDelete, isForceBaseline, isForceRescan, linkedChanges, taskDescription: inputText })
990
- }
991
-
992
- /**
993
- * 自动推导变更名(不依赖 progress)
994
- */
995
- function resolveChangeNameAuto(cwd, specDir = null) {
996
- const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
997
- if (!existsSync(changesDir)) return null
998
- const entries = readdirSync(changesDir, { withFileTypes: true })
999
- .filter(e => e.isDirectory() && e.name !== 'archive')
1000
- if (entries.length === 1) return entries[0].name
1001
- return null
1002
- }
1003
-
1004
- function showStatus(progress, stageName, nextSuggestion = null) {
1005
- const stageData = progress.stages[stageName]
1006
- const stageDef = stageRegistry[stageName]
1007
-
1008
- if (!stageData || !stageData.steps || stageData.steps.length === 0) {
1009
- console.log(`阶段:${stageName}(${stageDef?.title || stageName})`)
1010
- console.log(`进度:未初始化`)
1011
- if (stageData?.status) {
1012
- console.log(`状态:${stageData.status}`)
1013
- if (stageData.staleReason) console.log(`⚠️ 失效原因:${stageData.staleReason}`)
1014
- }
1015
- return
1016
- }
1017
-
1018
- const steps = stageData.steps
1019
- const completed = steps.filter(s => s.status === 'completed' || s.status === 'skipped').length
1020
- const bar = '█'.repeat(completed) + '░'.repeat(steps.length - completed)
1021
-
1022
- console.log(`阶段:${stageName}(${stageDef?.title || stageName})`)
1023
- console.log(`进度:[${bar}] ${completed}/${steps.length}`)
1024
-
1025
- // ── Revision v1 信息 ──
1026
- if (stageData.status === 'revising') {
1027
- console.log(`\n🔧 修订中 (revision ${stageData.revision || 1})`)
1028
- if (stageData.reopenedFromStep) console.log(` 从步骤:${stageData.reopenedFromStep}`)
1029
- if (stageData.reopenedAt) console.log(` 重开时间:${stageData.reopenedAt}`)
1030
- }
1031
- if (stageData.status === 'stale') {
1032
- console.log(`\n⚠️ 已失效`)
1033
- if (stageData.staleReason) console.log(` 原因:${stageData.staleReason}`)
1034
- console.log(` 建议:sillyspec run ${stageName} --reopen --from-step 1`)
1035
- }
1036
- if (stageData.status === 'completed') {
1037
- console.log(`\n✅ 已完成`)
1038
- }
1039
-
1040
- console.log('')
1041
-
1042
- const firstPending = steps.findIndex(s => s.status === 'pending' || s.status === 'in-progress')
1043
-
1044
- if (progress.batchProgress) {
1045
- const bp = progress.batchProgress
1046
- const bpTotal = bp.total || 0
1047
- const bpCompleted = bp.completed || 0
1048
- const bpFailed = bp.failed || 0
1049
- const bpSkipped = bp.skipped || 0
1050
- const bpBarLen = 20
1051
- const bpFilled = Math.round((bpCompleted / Math.max(bpTotal, 1)) * bpBarLen)
1052
- const bpBar = '█'.repeat(bpFilled) + '░'.repeat(bpBarLen - bpFilled)
1053
- const bpParts = []
1054
- if (bpFailed > 0) bpParts.push(`${bpFailed} 失败`)
1055
- if (bpSkipped > 0) bpParts.push(`${bpSkipped} 跳过`)
1056
- const bpSuffix = bpParts.length ? ` (${bpParts.join(', ')})` : ''
1057
- console.log(`\n📊 批量进度: ${bpBar} ${bpCompleted}/${bpTotal}${bpSuffix}\n`)
1058
- }
1059
-
1060
- steps.forEach((step, i) => {
1061
- const icon = step.status === 'completed' ? '✅' : step.status === 'skipped' ? '⏭️' : step.status === 'waiting' ? '⏸️' : '⬜'
1062
- const isCurrent = (step.status === 'pending' || step.status === 'in-progress') && i === firstPending
1063
- const isWaiting = step.status === 'waiting'
1064
- console.log(`${icon} Step ${i + 1}: ${step.name}${isCurrent ? ' ← 当前' : ''}${isWaiting ? ' [WAITING]' : ''}`)
1065
- if (isWaiting) {
1066
- if (step.waitReason) console.log(` 原因:${step.waitReason}`)
1067
- if (step.waitOptions) console.log(` 选项:${formatWaitOptions(step.waitOptions)}`)
1068
- if (step.waitedAt) console.log(` 等待时间:${step.waitedAt}`)
1069
- }
1070
- })
1071
-
1072
- // D9:本阶段进度之后,给出全局「下一步该跑什么」——
1073
- // 否则 agent 看完进度条仍要自己推状态机(尤其阶段已完成 / 失效 / 修订中这类非线性状态)。
1074
- if (nextSuggestion && nextSuggestion.command) {
1075
- console.log(`\n👉 ${nextSuggestion.text}`)
1076
- console.log(` 下一步命令:${nextSuggestion.command}`)
1077
- }
1078
- }
1079
-
1080
- async function resetStage(pm, progress, stageName, cwd, changeName, platformOpts = {}) {
1081
- // execute 阶段 reset 时清理自建 worktree,否则下次 run execute 会因 existingMeta 存在
1082
- // 直接复用带脏状态的旧 worktree(启动逻辑:meta 存在即复用,不查健康状态)
1083
- if (stageName === 'execute' && changeName) {
1084
- try {
1085
- const { WorktreeManager } = await import('../worktree.js')
1086
- const wm = new WorktreeManager({ cwd })
1087
- const meta = wm.getMeta(changeName)
1088
- if (meta) {
1089
- const cleanResult = wm.cleanup(changeName, { force: true })
1090
- if (cleanResult.residual?.length > 0) {
1091
- console.warn(`⚠️ reset 清理 worktree 残留: ${cleanResult.residual.join('; ')}`)
1092
- console.warn(` 手动处理: sillyspec worktree cleanup ${changeName} --force`)
1093
- } else if (cleanResult.result === 'kept') {
1094
- console.log(`🔗 旧 worktree 保留 (${cleanResult.mode}: 外部隔离环境)`)
1095
- } else if (cleanResult.result !== 'skipped') {
1096
- console.log(`🧹 已清理旧 worktree (${cleanResult.result}, mode: ${cleanResult.mode}),下次 execute 将重建干净环境`)
1097
- }
1098
- }
1099
- } catch (e) {
1100
- console.warn(`⚠️ reset 清理 worktree 失败(不阻断 reset): ${e.message}`)
1101
- }
1102
- }
1103
- const defSteps = await getStageSteps(stageName, cwd, progress, platformOpts?.specRoot || null)
1104
- progress.stages[stageName] = {
1105
- status: 'in-progress',
1106
- startedAt: new Date().toLocaleString('zh-CN',{hour12:false}),
1107
- completedAt: null,
1108
- steps: defSteps ? defSteps.map(s => ({ name: s.name, status: 'pending' })) : []
1109
- }
1110
- progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
1111
- pm._write(cwd, progress, changeName)
1112
- triggerSync(cwd, changeName, platformOpts)
1113
- console.log(`🔄 ${stageName} 阶段已重置`)
1114
- }
1115
-
1116
- /**
1117
- * auto 模式:自动推进 brainstorm → plan → execute → verify
1118
- */
1119
- async function runAutoMode(pm, progress, cwd, flags, changeName, platformOpts = {}) {
1120
- const flowStages = ['brainstorm', 'plan', 'execute', 'verify', 'archive']
1121
- const isDone = flags.includes('--done')
1122
- const outputIdx = flags.indexOf('--output')
1123
- const outputText = outputIdx !== -1 && flags[outputIdx + 1] ? flags[outputIdx + 1] : null
1124
- const inputIdx = flags.indexOf('--input')
1125
- const inputText = inputIdx !== -1 && flags[inputIdx + 1] ? flags[inputIdx + 1] : null
1126
- const skipApproval = flags.includes('--skip-approval')
1127
- const explicitMode = (() => {
1128
- const m = flags.indexOf('--mode')
1129
- return m !== -1 && flags[m + 1] ? flags[m + 1] : null
1130
- })()
1131
- const specBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
1132
-
1133
- // Helper: 在 auto 模式下获取步骤定义
1134
- const getAutoSteps = async (stage) => {
1135
- if (stage === 'brainstorm') {
1136
- return brainstormAutoDef.steps
1137
- }
1138
- return getStageSteps(stage, cwd, progress, platformOpts?.specRoot || null)
1139
- }
1140
-
1141
- const nextInFlow = (stage) => {
1142
- const i = flowStages.indexOf(stage)
1143
- return i >= 0 && i < flowStages.length - 1 ? flowStages[i + 1] : null
1144
- }
1145
- const firstOpenStage = () => flowStages.find(s => progress.stages?.[s]?.status !== 'completed')
1146
- const ensureAutoStage = async (stage) => {
1147
- const stageChanged = progress.currentStage !== stage
1148
- progress.currentStage = stage
1149
- // Auto 模式下 brainstorm 使用 artifact-first 步骤
1150
- if (stage === 'brainstorm') {
1151
- const existingSteps = progress.stages?.brainstorm?.steps
1152
- const isAutoModeSteps = existingSteps?.length === 4 && existingSteps?.[0]?.name === '进度确认与上下文加载'
1153
- if (!isAutoModeSteps) {
1154
- if (!progress.stages) progress.stages = {}
1155
- progress.stages.brainstorm = {
1156
- status: 'in-progress',
1157
- startedAt: new Date().toLocaleString('zh-CN', { hour12: false }),
1158
- completedAt: null,
1159
- steps: brainstormAutoDef.steps.map(s => ({ name: s.name, status: 'pending' }))
1160
- }
1161
- pm._write(cwd, progress, changeName)
1162
- triggerSync(cwd, changeName, platformOpts)
1163
- progress = pm.read(cwd, changeName)
1164
- return progress
1165
- }
1166
- }
1167
- const changed = await ensureStageSteps(progress, stage, cwd)
1168
- if (stageChanged || changed) {
1169
- pm._write(cwd, progress, changeName)
1170
- triggerSync(cwd, changeName, platformOpts)
1171
- }
1172
- progress = pm.read(cwd, changeName)
1173
- return progress
1174
- }
1175
-
1176
- // ── Classify change on first entry ──
1177
- if (!progress.stages?.brainstorm?.status && !progress.stages?.plan?.status) {
1178
- const { classifyChange, readAutoModeFromLocalYaml } = await import('../classify-change.js')
1179
- // auto_mode 接线(2026-08-11):从 local.yaml 读 auto_mode 段传 localConfig,让 force_*_patterns 真生效。
1180
- const localConfig = readAutoModeFromLocalYaml(cwd)
1181
- const classification = classifyChange({ description: inputText || '', explicitMode, localConfig })
1182
- if (classification.mode === 'quick') {
1183
- console.log(`📊 auto 模式分类:${classification.mode}(${classification.reason})`)
1184
- console.log(` 此变更建议使用 quick 模式,运行:sillyspec run quick "${inputText || '需求'}"`)
1185
- return
1186
- }
1187
- console.log(`📊 auto 模式分类:${classification.mode}(${classification.reason})`)
1188
- }
1189
-
1190
- let currentStage = progress.currentStage
1191
- if (!currentStage || progress.stages?.[currentStage]?.status === 'completed') {
1192
- currentStage = firstOpenStage()
1193
- }
1194
- if (!currentStage) {
1195
- console.log('All auto flow stages are complete.')
1196
- return
1197
- }
1198
- if (!flowStages.includes(currentStage)) {
1199
- const openStage = firstOpenStage()
1200
- if (!openStage) {
1201
- console.log('All auto flow stages are complete.')
1202
- return
1203
- }
1204
- console.log(`⚠️ 当前阶段 ${currentStage} 不在 auto 流程中,自动跳转到 ${openStage}`)
1205
- currentStage = openStage
1206
- }
1207
- await ensureAutoStage(currentStage)
1208
-
1209
- if (!isDone) {
1210
- console.log('════════════════════════════════════════')
1211
- console.log(' SillySpec Auto Mode')
1212
- if (changeName) console.log(` Change: ${changeName}`)
1213
- console.log('════════════════════════════════════════')
1214
- console.log(` Flow: ${flowStages.join(' -> ')}`)
1215
- console.log(` Current: ${currentStage}`)
1216
- for (const stage of flowStages) {
1217
- const stageData = progress.stages?.[stage]
1218
- const total = stageData?.steps?.length || '?'
1219
- const completed = stageData?.steps?.filter(step => step.status === 'completed' || step.status === 'skipped').length || 0
1220
- const marker = stageData?.status === 'completed' ? 'done' : stage === currentStage ? 'active' : 'pending'
1221
- console.log(` ${marker} ${stage} (${completed}/${total})`)
1222
- }
1223
- console.log('')
1224
-
1225
- const defSteps = await getAutoSteps(currentStage)
1226
- const pendingIdx = progress.stages[currentStage]?.steps?.findIndex(step => step.status === 'pending' || step.status === 'in-progress') ?? -1
1227
- if (pendingIdx === -1) {
1228
- const wsIdx = progress.stages[currentStage]?.steps?.findIndex(step => step.status === 'waiting') ?? -1
1229
- if (wsIdx !== -1) {
1230
- const ws = progress.stages[currentStage].steps[wsIdx]
1231
- console.log(`⏸️ Step ${wsIdx + 1} 等待用户输入:${ws.name}`)
1232
- if (ws.waitReason) console.log(` 原因:${ws.waitReason}`)
1233
- console.log(` 继续:sillyspec run auto --continue --answer "..."`)
1234
- return
1235
- }
1236
- const next = nextInFlow(currentStage)
1237
- if (next) console.log(`${currentStage} is complete. Run: sillyspec run auto --done --output "${currentStage} complete"`)
1238
- else console.log('All auto flow stages are complete.')
1239
- return
1240
- }
1241
- // execute 阶段启动前检查审批
1242
- if (currentStage === 'execute' && !skipApproval) {
1243
- const approval = await checkApproval(cwd, changeName, platformOpts)
1244
- if (approval) {
1245
- if (approval.status === 'rejected') {
1246
- console.error(`❌ 变更 ${changeName} 的执行已被拒绝:${approval.reason || '无原因'}`)
1247
- process.exit(1)
1248
- }
1249
- if (approval.status === 'pending') {
1250
- console.log(`⏳ 变更 ${changeName} 的执行审批待处理中...`)
1251
- console.log(' 提示:使用 --skip-approval 跳过审批检查')
1252
- }
1253
- if (approval.status === 'unknown') {
1254
- console.warn(`⚠️ 变更 ${changeName} 的审批状态未知(${approval.reason || '请求失败'}),按本地模式放行(非审批中,无需等待)`)
1255
- }
1256
- }
1257
- }
1258
- await outputStep(currentStage, pendingIdx, defSteps, cwd, changeName, progress.project || null, platformOpts)
1259
- return
1260
- }
1261
-
1262
- if (!outputText) {
1263
- console.error('auto --done requires --output')
1264
- process.exit(2) // 用法错 → exit 2
1265
- }
1266
-
1267
- const result = await completeStep(pm, progress, currentStage, cwd, outputText, inputText, { printNext: false, changeName, platformOpts })
1268
- if (!result) return
1269
- progress = pm.read(cwd, changeName)
1270
-
1271
- const nextPendingIdx = progress.stages[currentStage]?.steps?.findIndex(step => step.status === 'pending' || step.status === 'in-progress') ?? -1
1272
- if (nextPendingIdx !== -1) {
1273
- const defSteps = await getAutoSteps(currentStage)
1274
- // execute 阶段启动前检查审批
1275
- if (currentStage === 'execute' && !skipApproval) {
1276
- const approval = await checkApproval(cwd, changeName, platformOpts)
1277
- if (approval) {
1278
- if (approval.status === 'rejected') {
1279
- console.error(`❌ 变更 ${changeName} 的执行已被拒绝:${approval.reason || '无原因'}`)
1280
- process.exit(1)
1281
- }
1282
- if (approval.status === 'pending') {
1283
- console.log(`⏳ 变更 ${changeName} 的执行审批待处理中...`)
1284
- console.log(' 提示:使用 --skip-approval 跳过审批检查')
1285
- }
1286
- if (approval.status === 'unknown') {
1287
- console.warn(`⚠️ 变更 ${changeName} 的审批状态未知(${approval.reason || '请求失败'}),按本地模式放行(非审批中,无需等待)`)
1288
- }
1289
- }
1290
- }
1291
- await outputStep(currentStage, nextPendingIdx, defSteps, cwd, changeName, progress.project || null, platformOpts)
1292
- return
1293
- }
1294
-
1295
- const next = nextInFlow(currentStage)
1296
- if (!next) {
1297
- console.log('\nAll auto flow stages are complete.')
1298
- return
1299
- }
1300
-
1301
- // ── next-action.json 驱动:brainstorm → plan 推进判断 ──
1302
- if (currentStage === 'brainstorm' && next === 'plan') {
1303
- const changeDir = resolveChangeDir(cwd, progress, platformOpts?.specRoot || null)
1304
- if (changeDir) {
1305
- const nextActionFile = join(changeDir, 'next-action.json')
1306
- try {
1307
- const nextAction = JSON.parse(readFileSync(nextActionFile, 'utf8'))
1308
- if (nextAction.has_blocking_questions === true) {
1309
- console.log(`\n⏸️ brainstorm 有阻塞问题,无法自动进入 plan:`)
1310
- for (const q of (nextAction.questions || [])) {
1311
- console.log(` Q-${q.id}: ${q.question}`)
1312
- if (q.options) console.log(` 选项:${q.options.join(' / ')}`)
1313
- if (q.recommended) console.log(` 推荐:${q.recommended}`)
1314
- }
1315
- console.log(`\n 请回答阻塞问题后继续:sillyspec run auto --done --output "已回答"`)
1316
- return
1317
- }
1318
- console.log(`\n✅ next-action.json: ${nextAction.status},自动进入 plan`)
1319
- } catch (e) {
1320
- // next-action.json 不存在或格式错误,继续推进(向后兼容)
1321
- console.log(`\n⚠️ next-action.json 未找到,继续进入 plan`)
1322
- }
1323
- }
1324
- }
1325
-
1326
- progress.currentStage = next
1327
- if (!progress.stages[next]) {
1328
- progress.stages[next] = { status: 'pending', steps: [], startedAt: null, completedAt: null }
1329
- }
1330
- if (progress.stages[next].status === 'pending' || !progress.stages[next].status) {
1331
- progress.stages[next].status = 'in-progress'
1332
- progress.stages[next].startedAt = new Date().toLocaleString('zh-CN',{hour12:false})
1333
- }
1334
- progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
1335
- await ensureStageSteps(progress, next, cwd)
1336
- pm._write(cwd, progress, changeName)
1337
- triggerSync(cwd, changeName, platformOpts)
1338
- progress = pm.read(cwd, changeName)
1339
-
1340
- console.log(`\n${currentStage} complete. Auto advanced to ${next}.`)
1341
- const nextSteps = await getAutoSteps(next)
1342
- const firstPending = progress.stages[next]?.steps?.findIndex(step => step.status === 'pending' || step.status === 'in-progress') ?? -1
1343
- if (firstPending !== -1) {
1344
- // execute 阶段启动前检查审批
1345
- if (next === 'execute' && !skipApproval) {
1346
- const approval = await checkApproval(cwd, changeName, platformOpts)
1347
- if (approval) {
1348
- if (approval.status === 'rejected') {
1349
- console.error(`❌ 变更 ${changeName} 的执行已被拒绝:${approval.reason || '无原因'}`)
1350
- process.exit(1)
1351
- }
1352
- if (approval.status === 'pending') {
1353
- console.log(`⏳ 变更 ${changeName} 的执行审批待处理中...`)
1354
- console.log(' 提示:使用 --skip-approval 跳过审批检查')
1355
- }
1356
- if (approval.status === 'unknown') {
1357
- console.warn(`⚠️ 变更 ${changeName} 的审批状态未知(${approval.reason || '请求失败'}),按本地模式放行(非审批中,无需等待)`)
1358
- }
1359
- }
1360
- }
1361
- await outputStep(next, firstPending, nextSteps, cwd, changeName, progress.project || null, platformOpts)
1362
- }
1363
- }
1364
-
1
+ /**
2
+ * run/command.js(W6 Step8c 从 run.js 抽出)。
3
+ *
4
+ * 命令分发层:runCommand(主入口,被 src/index.js + 6 个 test import)+ auto 模式 +
5
+ * ensureStageSteps(被 step-migration test import)+ 4 个 runCommand 私有 helper
6
+ * (resolveChangeName / resolveChangeNameAuto / showStatus / resetStage)。
7
+ *
8
+ * 调用图(单向,无环):runCommand → { runStage(stage.js), runAutoMode, resetStage, showStatus,
9
+ * ensureStageSteps, completeStep/skip/wait/continue(complete.js) };runAutoMode → { outputStep,
10
+ * completeStep, ensureStageSteps, checkApproval(shared) },不调 runStage(内联 outputStep)。
11
+ *
12
+ * 安全锚:run.js 始终 barrel。runCommand + ensureStageSteps 被 test 直接 import → run.js barrel
13
+ * re-export(契约保留);其余 5 函数 runCommand 私有,无 test 直接 import。
14
+ *
15
+ * 路径修正(相对 src/run/):
16
+ * - 动态 import './init.js' / './worktree.js' / './classify-change.js' → '../'(src/ 下退一层)
17
+ * - 'fs'(runCommand 内 await import('fs'))裸模块名不变
18
+ * - 静态 import './progress.js' / './stage-contract.js' / './stages/*' / './fs-atomic.js' → '../'
19
+ * './run/shared.js' / './run/quick-audit.js' / './run/prompt.js' / './run/complete.js' /
20
+ * './run/stage.js' → './shared.js' 等同级
21
+ */
22
+ import { basename, join, resolve, dirname } from 'node:path'
23
+ import { existsSync, readdirSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs'
24
+ import { randomBytes, randomUUID } from 'node:crypto'
25
+ import { writeAtomicSync } from '../fs-atomic.js'
26
+ import { resolveSpecDir, countAncestorSpecDirs, resolveChangeDir, triggerSync, getStageSteps, formatWaitOptions, checkApproval, didYouMean, assertSafeChangeName, detectQuickSessionDrift, detectWorktreeSpecDrift, resolveRuntimeRoot, writePlatformPointer, checkPlatformManaged, PLATFORM_MANAGED_FILENAME } from './shared.js'
27
+ import { resolveQuickLinkedChanges } from './quick-audit.js'
28
+ import { outputStep } from './prompt.js'
29
+ import { completeStep, skipStep, waitStep, continueStep } from './complete.js'
30
+ import { runStage } from './stage.js'
31
+ import { sanitizeDesc } from '../quicklog.js'
32
+ import { ProgressManager } from '../progress.js'
33
+ import { validateChangeExists, checkTransition } from '../stage-contract.js'
34
+ import { READONLY_AUXILIARY_STAGES } from '../constants.js'
35
+ import { stageRegistry, auxiliaryStages } from '../stages/index.js'
36
+ import { definition as brainstormAutoDef } from '../stages/brainstorm-auto.js'
37
+ import { setQuickFileNotes } from '../quicklog.js'
38
+
39
+ // F2/F4: 哪些 flag 吃下一个 token 作「值」(其余 --flag 都是布尔,不吞值)。
40
+ // 校验循环只对 VALUE_FLAGS 跳下一个 token(否则 --done 后跟 typo 会被当 --done 的值吞掉)。
41
+ // getFlagValue 也据此拒收「下一个 token 是另一个 flag 名」当值。
42
+ const VALUE_FLAGS = new Set([
43
+ '--reason', '--options', '--answer', '--confirm-mode',
44
+ '--output', '--input', '--change', '--linked-changes',
45
+ '--spec-dir', '--spec-root', '--runtime-root', '--workspace-id', '--scan-run-id',
46
+ '--files', '--file-notes', '--from-step', '--mode', '--dir', '--confirm-mode',
47
+ '--base', // scan diff 基线 commit(吃值;只在 run scan --diff 转发路径消费)
48
+ ])
49
+
50
+ /**
51
+ * 检测 `--files` 是否被空格分隔误用(坑 quick-files-space-separated-silently-drops)。
52
+ *
53
+ * --files 是单值 flag(VALUE_FLAGS:校验循环只跳一个 token、--k=v 只展开一个值),空格分隔的
54
+ * 多文件只有首个被当值,其余沦为位置参数被 `:482` 的 `startsWith('--')` 校验静默忽略 →
55
+ * guard.allowedFiles 只剩首个 → --done 边界审计误拦,边界保护形同虚设。
56
+ *
57
+ * 返回 --files 值及其后所有连续非 flag token(疑似被丢的多文件);length > 1 即误用,调用方
58
+ * fail-loud(process.exit 2,同 run --json :109 显式拒绝静默吞风格)。贪婪收集多值会破坏
59
+ * VALUE_FLAGS 单值框架(校验循环/等号展开/getFlagValue 都假设单值),故仅检测不改语义。
60
+ *
61
+ * 纯函数:无副作用、不读 process、不 mutate 入参,供 command.js 解析 + 单测复用。
62
+ * @param {string[]} flags runCommand 规范化后的 flags 数组(--k=v 已展开)
63
+ * @returns {string[]} --files 值 + 其后连续非 flag token;无 --files / 值是 flag 名 / 含逗号 → []
64
+ */
65
+ export function detectSpaceSeparatedFiles(flags) {
66
+ const idx = flags.indexOf('--files')
67
+ if (idx === -1) return []
68
+ const val = flags[idx + 1]
69
+ // 值缺失 / 值本身是 flag 名(--files --done 漏值)/ 逗号分隔(正确用法)→ 不检测
70
+ if (!val || val.startsWith('--') || val.includes(',')) return []
71
+ const suspects = [val]
72
+ for (let j = idx + 2; j < flags.length && !flags[j].startsWith('--'); j++) suspects.push(flags[j])
73
+ return suspects
74
+ }
75
+
76
+ /**
77
+ * 从 progress 或变更目录推导变更名
78
+ */
79
+ function resolveChangeName(cwd, progress, specDir = null) {
80
+ if (progress.currentChange) return progress.currentChange
81
+ const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
82
+ if (!existsSync(changesDir)) return null
83
+ const entries = readdirSync(changesDir, { withFileTypes: true })
84
+ .filter(e => e.isDirectory() && e.name !== 'archive')
85
+ if (entries.length === 1) return entries[0].name
86
+ return null
87
+ }
88
+
89
+ /**
90
+ * 确保阶段的 steps 已初始化到 progress
91
+ */
92
+ export async function ensureStageSteps(progress, stageName, cwd, specDir = null) {
93
+ if (!progress.stages) progress.stages = {}
94
+
95
+ const steps = await getStageSteps(stageName, cwd, progress, specDir)
96
+ if (!steps) return false
97
+
98
+ if (!progress.stages[stageName] || !progress.stages[stageName].steps || progress.stages[stageName].steps.length === 0) {
99
+ progress.stages[stageName] = {
100
+ status: 'in-progress',
101
+ startedAt: new Date().toLocaleString('zh-CN',{hour12:false}),
102
+ completedAt: null,
103
+ steps: steps.map(s => ({ name: s.name, status: 'pending' }))
104
+ }
105
+ return true // 需要写入
106
+ }
107
+
108
+ // 检查步骤数量是否匹配(execute 动态步骤可能变化)
109
+ if (progress.stages[stageName].steps.length !== steps.length) {
110
+ const oldSteps = progress.stages[stageName].steps
111
+ progress.stages[stageName].steps = steps.map(s => {
112
+ const old = oldSteps.find(step => step.name === s.name)
113
+ if (old) return old // 精确名命中 → 保留旧状态
114
+ // migratedFrom:新步骤是合并/重命名来的(如 brainstorm 13→8 折叠)。
115
+ // 吸收的旧步骤全部 completed → 新步骤标 completed,避免 completed 丢失导致 currentIdx 回跳。
116
+ if (Array.isArray(s.migratedFrom) && s.migratedFrom.length > 0) {
117
+ const migrated = oldSteps.filter(step => s.migratedFrom.includes(step.name))
118
+ if (migrated.length > 0 && migrated.every(step => step.status === 'completed')) {
119
+ return { name: s.name, status: 'completed', migratedFrom: true }
120
+ }
121
+ }
122
+ return { name: s.name, status: 'pending' }
123
+ })
124
+ return true
125
+ }
126
+
127
+ return false
128
+ }
129
+
130
+ /**
131
+ * run <stage> --help/-h 的用法帮助(runCommand 内 --help 短路调用)。
132
+ * 只打印不落盘:帮助查询不该有副作用(建会话/写 QUICKLOG)。
133
+ */
134
+ function printStageUsage(stageName) {
135
+ const stage = stageRegistry[stageName]
136
+ console.log(`
137
+ sillyspec run ${stageName}${stage && stage.title ? ` — ${stage.title}` : ''}${stage && stage.description ? `\n ${stage.description}` : ''}
138
+
139
+ 用法:
140
+ sillyspec run ${stageName} 开始/继续该阶段(输出下一步 prompt)
141
+ sillyspec run ${stageName} --status 查看阶段进度
142
+ sillyspec run ${stageName} --done --output "摘要" [--input "用户原话"] 完成当前步骤
143
+ sillyspec run ${stageName} --change <名> 指定变更(多活跃变更必填)
144
+
145
+ 通用参数: --done --output --input --status --skip --reset --reopen --from-step
146
+ --wait --continue --answer --change --spec-dir --non-interactive
147
+ --interactive --skip-approval --json(不支持)
148
+ quick 专属: --linked-changes none|a,b --files a.js,b.js --allow-new
149
+ --allow-delete --force-baseline --confirm --file-notes
150
+ scan 专属: --quick --standard --deep --force-rescan --diff [--base <commit>] [--full] [--report]
151
+ archive专属: --confirm
152
+ `)
153
+ }
154
+
155
+ /**
156
+ * sillyspec run <stage> 主命令
157
+ */
158
+ export async function runCommand(args, cwd, specDir = null, opts = {}) {
159
+ // W1-B: run <stage> 暂不支持 --json。之前 --json 进 knownFlags 白名单却从不读取(静默吞),
160
+ // agent 按 gate/derive 契约期望 envelope 实则拿到混合人类文本。显式 fail-fast 杜绝歧义;
161
+ // 完整 run envelope 待 outputStep 重构(W6)后支持(prompt + nextAction 结构化)。
162
+ if (opts.json) {
163
+ console.error('❌ run <stage> 暂不支持 --json(静默吞是 bug,故显式拒绝)。')
164
+ console.error(' 查事实用 gate/derive(支持 --json envelope);run 输出人类可读 prompt 供 agent 直接执行。')
165
+ process.exit(2) // 用法错 → exit 2
166
+ }
167
+ // 解析参数
168
+ const stageName = args[0]
169
+ let flags = args.slice(1) // let:下方规范化 --k=v 会改写
170
+
171
+ // F7: 规范化 --key=value → ['--key', 'value']。许多 CLI 通用等号语法此前被整 token 当未知参数拒绝。
172
+ // 只对值类 flag 展开(见 VALUE_FLAGS);布尔 flag 不吃值,--skip-approval=x 这种无意义,原样进校验报错。
173
+ flags = flags.flatMap(tok => {
174
+ if (typeof tok === 'string' && tok.startsWith('--') && tok.includes('=')) {
175
+ const eq = tok.indexOf('=')
176
+ const key = tok.slice(0, eq)
177
+ const val = tok.slice(eq + 1)
178
+ if (VALUE_FLAGS.has(key)) return [key, val]
179
+ }
180
+ return [tok]
181
+ })
182
+
183
+ if (!stageName) {
184
+ console.error('❌ 请指定阶段,例如: sillyspec run brainstorm')
185
+ console.error(`可选: ${Object.keys(stageRegistry).join(', ')}, auto`)
186
+ process.exit(2) // 用法错 → exit 2
187
+ }
188
+
189
+ if (!stageRegistry[stageName] && stageName !== 'auto') {
190
+ console.error(`❌ 未知阶段: ${stageName}`)
191
+ console.error(`可选: ${Object.keys(stageRegistry).join(', ')}, auto`)
192
+ process.exit(2) // 用法错 → exit 2
193
+ }
194
+
195
+ // ── cwd 纠正:向上查找真实项目根 ──
196
+ // 防止多 project 工作区中 cwd 停在子目录(如 backend/)时
197
+ // 状态写入子目录下误建的 .sillyspec,导致状态分裂
198
+ if (!specDir && !existsSync(join(cwd, '.sillyspec-platform.json'))) {
199
+ // 平台模式(cwd 有 .sillyspec-platform.json 指针)不做 cwd 纠正:指针已明确 specDir,
200
+ // 向上找 .sillyspec 反而会撞到无关项目(如用户 home 的 .sillyspec),导致 --done 恢复
201
+ // 读写 ~/.sillyspec-platform.json 出错的 specRoot。
202
+ const resolvedRoot = resolveSpecDir(cwd)
203
+ if (resolvedRoot && resolvedRoot !== join(cwd, '.sillyspec')) {
204
+ const realRoot = dirname(resolvedRoot)
205
+ if (realRoot !== cwd) {
206
+ cwd = realRoot
207
+ }
208
+ }
209
+ }
210
+
211
+ // 平台模式参数(供 SillyHub 等平台调用)
212
+ // --spec-dir 是统一参数名,--spec-root 保留为向后兼容别名
213
+ const getFlagValue = (name) => {
214
+ const idx = flags.indexOf(name)
215
+ if (idx === -1) return null
216
+ const next = flags[idx + 1]
217
+ // F4: 下一个 token 若是另一个 flag 名(--xxx),说明本 flag 漏值,
218
+ // 不能把 flag 名当值返回(否则 --change --done → changeName="--done" 一路污染)。
219
+ if (!next || (typeof next === 'string' && next.startsWith('--'))) return null
220
+ return next
221
+ }
222
+ const isDone = flags.includes('--done')
223
+ const isSkip = flags.includes('--skip')
224
+ const isStatus = flags.includes('--status')
225
+ const isReset = flags.includes('--reset')
226
+ const isReopen = flags.includes('--reopen')
227
+ const fromStepValue = getFlagValue('--from-step')
228
+ const isConfirm = flags.includes('--confirm')
229
+ const isSkipApproval = flags.includes('--skip-approval')
230
+ const isWait = flags.includes('--wait')
231
+ const isContinue = flags.includes('--continue')
232
+ const isNonInteractive = flags.includes('--non-interactive')
233
+ const isInteractive = flags.includes('--interactive')
234
+ // F3 冲突 flag 检测:步骤/阶段动作 flag 互斥——各自定义「对当前步骤做什么」,同时给 2+ 个
235
+ // 语义矛盾。旧实现按代码里 if 顺序静默取先命中的、其余被忽略,agent 以为生效的其实没生效
236
+ // (如 --done --reset 只 reset 不 done,agent 却以为完成了步骤)。显式报冲突让 agent 选一个。
237
+ const STEP_ACTIONS = [
238
+ ['--done', isDone, '完成当前步骤'],
239
+ ['--skip', isSkip, '跳过当前步骤'],
240
+ ['--reset', isReset, '重置整个阶段(从头开始)'],
241
+ ['--reopen', isReopen, '重新打开已完成阶段进入修订(配 --from-step)'],
242
+ ['--wait', isWait, '暂停等用户决策'],
243
+ ['--continue', isContinue, '恢复等待中的步骤'],
244
+ ['--status', isStatus, '查看进度(只读)'],
245
+ ]
246
+ const activeActions = STEP_ACTIONS.filter(([, v]) => v)
247
+ if (activeActions.length >= 2) {
248
+ console.error('❌ 步骤动作参数冲突(同时只能指定一个):')
249
+ for (const [name, , desc] of activeActions) console.error(` ${name} — ${desc}`)
250
+ console.error(' 这些动作互斥,请只保留其中一个再重试。')
251
+ process.exit(2)
252
+ }
253
+ // scan profile flag 互斥:--quick/--standard/--deep 同时给≥2 个语义矛盾(computeScanProfile
254
+ // 只取首个命中、其余静默忽略 → agent 以为生效的其实没生效,与 STEP_ACTIONS 同类风险)。
255
+ const PROFILE_FLAGS = [
256
+ ['--quick', flags.includes('--quick'), 'quick profile(快速接入,4 份核心文档)'],
257
+ ['--standard', flags.includes('--standard'), 'standard profile(压缩步骤)'],
258
+ ['--deep', flags.includes('--deep'), 'deep profile(完整扫描)'],
259
+ ]
260
+ const activeProfiles = PROFILE_FLAGS.filter(([, v]) => v)
261
+ if (activeProfiles.length >= 2) {
262
+ console.error('❌ scan profile 参数冲突(同时只能指定一个):')
263
+ for (const [name, , desc] of activeProfiles) console.error(` ${name} — ${desc}`)
264
+ console.error(' 这三档互斥,请只保留其中一个再重试。')
265
+ process.exit(2)
266
+ }
267
+ // 注:--non-interactive 与 --interactive 的冲突在 index.js 检测(--interactive 被 index.js
268
+ // 作为全局 flag 吞掉、不透传到此处,故 isInteractive 在此恒为 false)。
269
+ const waitReason = getFlagValue('--reason')
270
+ const waitOptions = getFlagValue('--options')
271
+ const continueAnswer = getFlagValue('--answer')
272
+ const resolvedSpecDir = specDir || getFlagValue('--spec-dir') || getFlagValue('--spec-root')
273
+ const platformOpts = {
274
+ specRoot: resolvedSpecDir ? resolve(resolvedSpecDir) : null,
275
+ runtimeRoot: getFlagValue('--runtime-root') ? resolve(getFlagValue('--runtime-root')) : null,
276
+ workspaceId: getFlagValue('--workspace-id'),
277
+ scanRunId: getFlagValue('--scan-run-id'),
278
+ }
279
+
280
+ // 跨 --done 生命周期:从 metadata 文件恢复 platformOpts
281
+ // 首次 scan 时写入,所有后续调用(包括 run、--done、--skip)都读取
282
+ // 优先在 specDir 下查找,否则回退到 cwd/.sillyspec/.runtime/
283
+ let specRoot = platformOpts.specRoot || resolveSpecDir(cwd)
284
+ // 平台参数恢复策略:
285
+ // 1. 优先检查 cwd/.sillyspec-platform.json(轻量指针文件,不污染 .sillyspec 结构)
286
+ // 2. 然后检查 specRoot/.runtime/platform-scan.json(首次 scan 写入)
287
+ const platformPointer = join(cwd, '.sillyspec-platform.json')
288
+ const platformScanFile = join(specRoot, '.runtime', 'platform-scan.json')
289
+ let platformOptsFile = existsSync(platformPointer) ? platformPointer : platformScanFile
290
+ let platformFileExists = existsSync(platformOptsFile)
291
+ // 如果命令行没传 spec-root,尝试从持久化文件恢复
292
+ if (!platformOpts.specRoot && !platformOpts.runtimeRoot) {
293
+ if (platformFileExists) {
294
+ try {
295
+ const { readFileSync } = await import('fs')
296
+ const saved = JSON.parse(readFileSync(platformOptsFile, 'utf8'))
297
+ if (saved.specRoot) platformOpts.specRoot = saved.specRoot
298
+ if (saved.runtimeRoot) platformOpts.runtimeRoot = saved.runtimeRoot
299
+ if (saved.workspaceId) platformOpts.workspaceId = saved.workspaceId
300
+ if (saved.scanRunId) platformOpts.scanRunId = saved.scanRunId
301
+ // 平台模式 fail-fast:文件存在但缺少 specRoot
302
+ if (!platformOpts.specRoot && !platformOpts.runtimeRoot) {
303
+ console.error(`❌ 平台模式参数文件存在但缺少 specRoot/runtimeRoot: ${platformOptsFile}`)
304
+ console.error(' 可能原因:platform-scan.json 损坏或写入不完整')
305
+ console.error(' 解决:重新运行首次 scan 并传入 --spec-root')
306
+ process.exit(2) // 环境错(平台文件损坏)→ exit 2
307
+ }
308
+ // 恢复成功:更新 specRoot(初始值可能是 cwd/.sillyspec,恢复后应为真实 specDir)
309
+ specRoot = platformOpts.specRoot || specRoot
310
+ } catch (e) {
311
+ console.error(`❌ 平台模式参数文件读取失败: ${platformOptsFile}`)
312
+ console.error(` 错误: ${e.message}`)
313
+ console.error(' 可能原因:文件损坏')
314
+ console.error(' 解决:删除该文件并重新运行首次 scan 传入 --spec-root')
315
+ process.exit(2) // 环境错(文件损坏)→ exit 2
316
+ }
317
+ }
318
+ }
319
+ // ── 平台接管声明 fail-closed(入口二,D-B@v2)──
320
+ // runCommand 有独立指针恢复链(不经 resolvePlatformSpecDir),指针缺失时若不在此
321
+ // 封堵,run/quick/scan 等全部 stage 命令会静默落本地库(与入口一行为分裂)。
322
+ // 触发条件:命令行没传平台参数 + 指针与 platform-scan.json 皆未命中 + 接管声明存在。
323
+ // 显式 --spec-dir/--spec-root 传参时 platformOpts.specRoot 已赋值,天然不进此分支(逃生口)。
324
+ if (!platformOpts.specRoot && !platformOpts.runtimeRoot && !platformFileExists) {
325
+ const decl = checkPlatformManaged(cwd)
326
+ if (decl) {
327
+ console.error(`❌ 平台接管声明生效:本项目已由平台托管(原 specRoot: ${decl.specRoot || '(未记录)'}),但恢复指针缺失,拒绝静默回退本地模式。`)
328
+ console.error(` 声明文件: ${join(cwd, PLATFORM_MANAGED_FILENAME)}`)
329
+ console.error(' 恢复:① 重跑平台 scan/init(带 --spec-root)重建指针;② 确认不再使用平台:sillyspec platform disconnect(删除接管声明);③ 显式 --spec-dir <路径> 临时指定目录。')
330
+ // exit(1) 而非邻近环境错的 exit(2):这是"状态保护阻断"(对齐 PointerUnreachableError
331
+ // 顶层 catch 语义),非"用法/环境错"——见 design.md §5.3 v2 复审观察 (a)
332
+ process.exit(1)
333
+ }
334
+ }
335
+ // 持久化 platformOpts
336
+ // 在 specRoot/.runtime/ 写主文件,同时在 cwd 下写恢复指针
337
+ // (writePlatformPointer 收敛双写逻辑,cmdInit 平台模式共用,防两处字段漂移)
338
+ if (platformOpts.specRoot || platformOpts.runtimeRoot) {
339
+ writePlatformPointer(cwd, platformOpts)
340
+ }
341
+
342
+ // 统一规范基路径:平台模式用 specRoot,本地模式用 cwd/.sillyspec
343
+ // runCommand 后续所有 .sillyspec/ 操作必须用 specBase
344
+ // let:下方 worktree 副本漂移守卫命中时锚回 wt.mainSpecBase(task-05/D-03)
345
+ let specBase = platformOpts.specRoot || join(cwd, '.sillyspec')
346
+
347
+ // 漂移提醒:cwd 祖先链 ≥2 个 .sillyspec = monorepo 多实例,当前命中的「最近」实例
348
+ // 可能不是用户意图的项目(如 cd 进被独立 scan 的子项目跑测试后忘回根)。
349
+ // 平台模式 / 显式 --spec-dir 跳过(已明确指定,无歧义)。仅提醒不阻断。
350
+ if (!platformOpts.specRoot && !specDir) {
351
+ const ancestorCount = countAncestorSpecDirs(cwd)
352
+ if (ancestorCount >= 2) {
353
+ console.warn(`⚠️ 检测到祖先链有 ${ancestorCount} 个 .sillyspec 实例(monorepo 多实例),当前使用: ${specBase}`)
354
+ console.warn(` 若意图是另一个项目:cd 回该项目根,或用 --spec-dir <根>/.sillyspec 显式指定。`)
355
+ }
356
+ }
357
+
358
+ // scan diff 转发(D-001@v1:command.js 只认 --diff flag,等价 `sillyspec scan diff` 子命令;
359
+ // 裸 token `run scan diff` 不在此解析——那是 index.js 子命令拦截的职责,防 command.js 静默吞)。
360
+ // 纯只读比较:零会话/QUICKLOG 副作用,仅解析 --base/--full/--report 后转发 scan-diff 退出码。
361
+ if (stageName === 'scan' && flags.includes('--diff')) {
362
+ const { runScanDiff } = await import('../scan-diff.js')
363
+ const diffBaseIdx = flags.indexOf('--base')
364
+ const diffBase = diffBaseIdx >= 0 && flags[diffBaseIdx + 1] ? flags[diffBaseIdx + 1] : null
365
+ process.exitCode = runScanDiff({
366
+ projectRoot: cwd,
367
+ specBase,
368
+ projectName: basename(cwd),
369
+ base: diffBase,
370
+ full: flags.includes('--full'),
371
+ report: flags.includes('--report'),
372
+ })
373
+ return
374
+ }
375
+
376
+ // 平台模式:首次接入时清理旧版本残留的 cwd/.sillyspec/(防止源码污染)。
377
+ // ⚠️ 同 init.js:必须保护真实资产(changes/、projects/、sillyspec.db)。
378
+ // 只在「首次」执行一次——用 cwd 下的 .sillyspec-platform-cleaned 标记文件记录已处理,
379
+ // 后续每次 run 直接跳过,避免重复检查 + 红叉噪声(此清理不阻塞流程、不动真实资产)。
380
+ if (platformOpts.specRoot) {
381
+ const legacyDir = join(cwd, '.sillyspec')
382
+ const cleanedMarker = join(cwd, '.sillyspec-platform-cleaned')
383
+ if (!existsSync(cleanedMarker)) {
384
+ if (existsSync(legacyDir)) {
385
+ let hasChanges = false;
386
+ try {
387
+ const cd = join(legacyDir, 'changes');
388
+ if (existsSync(cd)) hasChanges = readdirSync(cd).length > 0;
389
+ } catch {}
390
+ let hasProjects = false;
391
+ try {
392
+ const pd = join(legacyDir, 'projects');
393
+ if (existsSync(pd)) hasProjects = readdirSync(pd).length > 0;
394
+ } catch {}
395
+ const hasDb = existsSync(join(legacyDir, 'sillyspec.db'));
396
+
397
+ if (hasChanges || hasProjects || hasDb) {
398
+ // 真实资产存在:只清运行时残留(白名单保留 worktrees/进度),不整删
399
+ const { cleanupRuntimeResidue } = await import('../init.js')
400
+ cleanupRuntimeResidue(legacyDir);
401
+ console.log('ℹ️ [sillyspec] 源码目录 .sillyspec/ 含真实资产,已跳过整删,仅清理运行时残留(仅本次首次,后续不再提示)。');
402
+ } else {
403
+ try { rmSync(legacyDir, { recursive: true, force: true }) } catch {}
404
+ if (!existsSync(legacyDir)) console.log('🧹 已清理旧版本残留的源码 .sillyspec/ 目录');
405
+ }
406
+ }
407
+ // 标记本 cwd 已做平台残留清理决策,后续 run 跳过(即使之后 .sillyspec/ 被重建也不误清)
408
+ try { writeFileSync(cleanedMarker, new Date().toISOString() + '\n') } catch {}
409
+ }
410
+ }
411
+
412
+ // 解析 --output
413
+ let outputText = null
414
+ const outputIdx = flags.indexOf('--output')
415
+ if (outputIdx !== -1 && flags[outputIdx + 1]) {
416
+ outputText = flags[outputIdx + 1]
417
+ }
418
+
419
+ // 解析 --input
420
+ let inputText = null
421
+ const inputIdx = flags.indexOf('--input')
422
+ if (inputIdx !== -1 && flags[inputIdx + 1]) {
423
+ inputText = flags[inputIdx + 1]
424
+ }
425
+
426
+ // 解析 --linked-changes <a,b|none>(quick 专用:显式声明关联变更,CI/脚本友好)
427
+ // 与 --change 解耦:--linked-changes 语义清晰(关联变更),不与「指定变更名」混淆。
428
+ // null = 未指定(走持久化/交互/兼容回退);[] = 显式 none(不关联);[...] = 显式列表
429
+ let explicitLinked = null
430
+ const linkedIdx = flags.indexOf('--linked-changes')
431
+ if (linkedIdx !== -1 && flags[linkedIdx + 1]) {
432
+ const v = flags[linkedIdx + 1].trim()
433
+ explicitLinked = v.toLowerCase() === 'none' ? [] : v.split(',').map(s => s.trim()).filter(Boolean)
434
+ }
435
+
436
+ // 解析 --change <name>(quick 阶段向后兼容:逗号分隔作为「关联变更」;
437
+ // 历史写法,语义与「指定变更名」冲突,新用法建议改用 --linked-changes)
438
+ let changeName = null
439
+ let linkedChanges = []
440
+ const changeIdx = flags.indexOf('--change')
441
+ if (changeIdx !== -1 && flags[changeIdx + 1]) {
442
+ changeName = flags[changeIdx + 1]
443
+ if (stageName === 'quick') {
444
+ linkedChanges = changeName.split(',').map(s => s.trim()).filter(Boolean)
445
+ changeName = null
446
+ }
447
+ }
448
+ // --linked-changes 优先于 --change(显式 > 隐式兼容)
449
+ if (explicitLinked !== null) {
450
+ linkedChanges = explicitLinked
451
+ }
452
+ // F6 路径穿越消毒:change 名会被 join 进 .sillyspec/changes/<name>/ 当目录名,
453
+ // 含 ../ 或路径分隔符会逃出 changes/ 写到任意位置。quick 的 --change 复用为 sessionId
454
+ // (quick-<8hex>,正则已约束) 或 linkedChanges,故 quick 的 changeName 不在此校验。
455
+ try {
456
+ if (stageName !== 'quick' && changeName) assertSafeChangeName(changeName)
457
+ for (const lc of linkedChanges) {
458
+ if (lc && lc !== 'none') assertSafeChangeName(lc, '关联变更名(--linked-changes)')
459
+ }
460
+ } catch (e) {
461
+ console.error(`❌ ${e.message}`)
462
+ console.error(` 合法变更名示例:2026-07-27-add-login(仅字母/数字/._-,不含 / \\ ..)`)
463
+ process.exit(2)
464
+ }
465
+ // quick 会话隔离(D-001@v1 + D-003@v1 + §4.4 跨进程传递):每会话用 sessionId 作 changeName,
466
+ // DB 分行 progress.quick-<uuid8>,避免并行 quick 会话共享单行 progress.default.quick 互相覆盖。
467
+ // sessionId = crypto.randomUUID 前 8 hex(摒弃旧 quick-YYYYMMDD-HHMMSS 时间戳,同秒并发撞)。
468
+ // crypto.randomUUID 从 node:crypto import(兼容 engines node>=18,不依赖 Node 19+ 全局)。
469
+ //
470
+ // --done 跨进程恢复 sessionId 的优先级(§4.4):
471
+ // 1. --change quick-<uuid8>(单值且匹配 sessionId 形态)→ 精确指定本会话 sessionId
472
+ // (quick 的 --change 历史被复用为 linkedChanges 见上 1370-1377;此处对「恰好一个 quick-<8hex>」
473
+ // 特例识别为 sessionId,多值/不匹配仍走 linkedChanges 语义,向后兼容)
474
+ // 2. 未识别出 sessionId 且为 --done → fallback 读 .runtime/current-quick-run-id(单会话兼容;
475
+ // 多会话时可能拿到他者,文档声明建议带 --change)
476
+ // 3. 仍读不到 → 生成新 UUID(兼容旧行为;进度可能命中空行,由后续 pm.read 兜底)
477
+ const QUICK_SID_RE = /^quick-[0-9a-f]{8}$/
478
+ let quickSessionId = null
479
+ let quickFallbackUsed = false // Q7: --done 未带 --change 时 fallback 读 current-quick-run-id 命中(区别于显式 --change quick-<hex>)
480
+ if (stageName === 'quick') {
481
+ // 1373-1376 已把 quick 的 --change 值清进 linkedChanges、changeName 置 null。
482
+ // 此处回看 --change 原始值:若恰好是单个 quick-<8hex> → 识别为本会话 sessionId(精确恢复),
483
+ // 并撤销把它当 linkedChanges 的误判。多值或不匹配 → 维持 linkedChanges 语义(旧兼容)。
484
+ const rawChange = changeIdx !== -1 && flags[changeIdx + 1] ? flags[changeIdx + 1].trim() : null
485
+ const rawIsSingleSid = rawChange && rawChange.indexOf(',') === -1 && QUICK_SID_RE.test(rawChange)
486
+ if (rawIsSingleSid) {
487
+ // --done --change quick-<uuid8>:精确恢复(撤销 1373-1376 把它误当 linkedChanges)
488
+ quickSessionId = rawChange
489
+ changeName = rawChange
490
+ linkedChanges = []
491
+ } else if (!changeName) {
492
+ // 未精确指定:非 --done 必生成新 sessionId;--done 先 fallback current-quick-run-id,读不到再生成
493
+ const isDoneLike = isDone || isStatus || isSkip || isReset || isReopen
494
+ if (isDoneLike) {
495
+ try {
496
+ const runtimeRoot = resolveRuntimeRoot(platformOpts, specRoot)
497
+ const idFile = join(runtimeRoot, 'current-quick-run-id')
498
+ if (existsSync(idFile)) {
499
+ const v = readFileSync(idFile, 'utf8').trim()
500
+ if (QUICK_SID_RE.test(v)) { quickSessionId = v; quickFallbackUsed = true }
501
+ }
502
+ } catch {}
503
+ }
504
+ if (!quickSessionId) {
505
+ quickSessionId = 'quick-' + randomUUID().slice(0, 8)
506
+ }
507
+ changeName = quickSessionId
508
+ } else {
509
+ // 用户显式传了非 sessionId 形态的变更名 → 尊重,不生成 UUID(旧兼容路径)
510
+ quickSessionId = changeName
511
+ }
512
+ }
513
+
514
+ // quick 关联变更存在性守卫(坑 quick-change-phantom-linked):quick 的 --change/--linked-changes
515
+ // 被解析为关联变更后静默接受不存在的名字(quick 不建变更,链接幻影名必是笔误/语义误用——想给
516
+ // 会话起名却传了 --change),后果是 QUICKLOG 挂悬空关联污染 change 关联图谱 + --done 时 sessionId
517
+ // 走 fallback 可能命中他者会话。f70c9c3 只修了「建幻影目录」后果(appendTaskCheckbox 加
518
+ // existsSync 守卫),本守卫把误用拦在 flag 装载层。只校验 CLI 显式装载的 linkedChanges;
519
+ // 持久化 guard.json 复用(下方 run↔--done 之间变更可能被归档)与交互式选择(列表只列存在项)不检。
520
+ if (stageName === 'quick' && linkedChanges.length > 0) {
521
+ const missing = linkedChanges.filter(lc => lc !== 'none' && !existsSync(join(specRoot, 'changes', lc)))
522
+ if (missing.length > 0) {
523
+ console.error(`❌ quick 的 --change/--linked-changes 被当作「关联变更」处理,但以下变更不存在:${missing.join('、')}`)
524
+ console.error(' (quick 不创建变更,关联的变更必须预先存在)')
525
+ console.error(' - 想给会话起名:不要传 --change,sessionId 由 CLI 自动生成(后续 --done 用它)')
526
+ console.error(' - 想关联变更:修正拼写(.sillyspec/changes/ 下已存在的目录名),显式写法 --linked-changes <名>')
527
+ console.error(' - 想新建变更:quick 不建变更,走 brainstorm 完整流程')
528
+ process.exit(2)
529
+ }
530
+ }
531
+
532
+ // 解析 --files a.js,b.js(quick 专用:显式声明 allowedFiles)
533
+ // --files 是单值 flag,空格分隔的多文件只取首个致其余静默丢失(坑 quick-files-space-separated-silently-drops)。
534
+ // detectSpaceSeparatedFiles 检测误用 → fail-loud 报错指明逗号用法(同 run --json :109 风格)。
535
+ const spaceSuspects = detectSpaceSeparatedFiles(flags)
536
+ if (spaceSuspects.length > 1) {
537
+ console.error('❌ --files 检测到空格分隔的多文件:CLI 只识别首个,其余会被静默丢弃(边界保护失效)。')
538
+ console.error(` 疑似多文件:${spaceSuspects.join(' ')}`)
539
+ console.error(' --files 是单值参数,多文件请用逗号分隔(无空格):')
540
+ console.error(` --files ${spaceSuspects.join(',')}`)
541
+ process.exit(2) // 用法错 → exit 2
542
+ }
543
+ let quickFiles = []
544
+ const filesIdx = flags.indexOf('--files')
545
+ if (filesIdx !== -1 && flags[filesIdx + 1]) {
546
+ quickFiles = flags[filesIdx + 1].split(',').map(f => f.trim()).filter(Boolean)
547
+ }
548
+
549
+ // 解析 --file-notes "path::括注 || path::括注"(quick 专用:QUICKLOG「文件:」行落盘多行括注)。
550
+ // 旁路注入 quicklog.js(per-process setter),不经 complete 收尾路径透传(避碰多 agent 并发改的收尾热点)。
551
+ // completeQuicklogEntry 读后即清;不传 → '' → 回填审计到的实际文件单行(向后兼容)。
552
+ let quickFileNotes = ''
553
+ const fileNotesIdx = flags.indexOf('--file-notes')
554
+ if (fileNotesIdx !== -1 && flags[fileNotesIdx + 1]) {
555
+ quickFileNotes = flags[fileNotesIdx + 1]
556
+ }
557
+ setQuickFileNotes(quickFileNotes)
558
+
559
+ const isAllowNew = flags.includes('--allow-new')
560
+ const isAllowDelete = flags.includes('--allow-delete')
561
+ const isForceBaseline = flags.includes('--force-baseline')
562
+ const isForceRescan = flags.includes('--force-rescan')
563
+
564
+ // F10b(ql-20260818-010):语义别名定向提示。did-you-mean 按编辑距离猜形近 flag,猜中的常是
565
+ // 形近但语义错的(--title → --files,ql-20260818-003 负面③实证)。常见「语义别名」在此登记
566
+ // 定向指引:命中时替代 did-you-mean 打印,引导到真正承载该语义的 flag/机制。
567
+ const FLAG_SEMANTIC_HINTS = {
568
+ '--title': 'QUICKLOG 条目标题无独立参数——从 --output 的「需求:」字段自动提取(写成一句语义化短标题即可)',
569
+ '--message': '结果摘要用 --output(quick 末步须含 需求:/根因:/方案:/结果: 四字段)',
570
+ '--summary': '结果摘要用 --output(quick 末步须含 需求:/根因:/方案:/结果: 四字段)',
571
+ '--result': '结果摘要用 --output(quick 末步须含 需求:/根因:/方案:/结果: 四字段)',
572
+ '--name': 'quick 会话名由 CLI 自动分配(quick-<hash>),恢复会话用 --change <quick-session-id>;关联变更用 --linked-changes',
573
+ '--session': 'quick 会话名由 CLI 自动分配(quick-<hash>),恢复会话用 --change <quick-session-id>',
574
+ '--note': '文件括注用 --file-notes "path::注 || path::注";启动时任务描述用 --input',
575
+ '--notes': '文件括注用 --file-notes "path::注 || path::注"',
576
+ '--desc': '启动时任务描述用 --input;QUICKLOG 标题从 --output「需求:」自动提取',
577
+ '--description': '启动时任务描述用 --input;QUICKLOG 标题从 --output「需求:」自动提取',
578
+ }
579
+
580
+ // 未知参数 fail-fast
581
+ const knownFlags = new Set([
582
+ '--done', '--skip', '--status', '--reset', '--confirm', '--skip-approval',
583
+ '--wait', '--continue', '--non-interactive', '--interactive',
584
+ '--reason', '--options', '--answer', '--confirm-mode',
585
+ '--output', '--input', '--change', '--linked-changes',
586
+ '--spec-dir', '--spec-root', '--runtime-root', '--workspace-id', '--scan-run-id',
587
+ '--files', '--file-notes', '--allow-new', '--allow-delete', '--force-baseline', '--force-rescan',
588
+ '--json', '--dir', '--help',
589
+ '--reopen', '--from-step', '--mode',
590
+ '--deep', '--quick', '--standard', // scan profile 三档显式选择(scan-profile.js 从 argv 读;互斥见下方 PROFILE_FLAGS 检测)
591
+ '--diff', '--base', '--full', '--report', // scan diff(D-001:command.js 只补 flag,裸 token 解析归 index.js 子命令拦截)
592
+ '-h',
593
+ ])
594
+ for (let i = 0; i < flags.length; i++) {
595
+ const f = flags[i]
596
+ if (f.startsWith('--')) {
597
+ if (!knownFlags.has(f)) {
598
+ // F10: flag 级 did-you-mean(此前只命令级有);F10b:语义别名定向提示优先于形近猜测
599
+ const semanticHint = FLAG_SEMANTIC_HINTS[f]
600
+ console.error(`❌ 未知参数: ${f}`)
601
+ if (semanticHint) {
602
+ console.error(` ${semanticHint}`)
603
+ } else {
604
+ const suggestion = didYouMean(f, [...knownFlags])
605
+ if (suggestion) console.error(` 你是想输入「${suggestion}」吗?`)
606
+ else console.error(`已知参数: ${[...knownFlags].sort().join(', ')}`)
607
+ }
608
+ process.exit(2) // 用法错 → exit 2
609
+ }
610
+ // F2: 只有吃值的 flag 才跳下一个 token。布尔 flag(--done 等)不能 i++——
611
+ // 否则会把紧跟的 typo flag 当成 --done 的「值」吞掉,既不校验也不生效(静默忽略)。
612
+ if (VALUE_FLAGS.has(f)) i++
613
+ }
614
+ }
615
+
616
+ // ── --help/-h 短路:flag 校验通过后、任何副作用(cwd 纠正/会话创建/QUICKLOG 落盘)之前 ──
617
+ // --help 此前在 knownFlags 白名单里被静默吞掉,run quick --help 会误开 quick 会话+写骨架
618
+ // 条目(查询意图不该有副作用);-h 更是被当未知参数 exit 2。帮助查询 = 用法展示 = 退出 0。
619
+ if (flags.includes('--help') || flags.includes('-h')) {
620
+ printStageUsage(stageName)
621
+ process.exit(0)
622
+ }
623
+
624
+ const isAuxiliary = auxiliaryStages.includes(stageName)
625
+ // scan 元数据追踪(存储在 stageData.scanMeta 中,completeStep 通过 progress 访问)
626
+
627
+ // let:下方 worktree 副本漂移守卫命中时用主仓 specRoot 重建 pm(task-05/D-03)
628
+ let pm = new ProgressManager({ specDir: specRoot })
629
+
630
+ // quick 阶段:确定关联变更
631
+ // 优先级:--linked-changes / --change 显式 > 已持久化 quick-guard.json(--done 复用)> 交互式 > 非交互 fallback
632
+ // 关键:--done 收尾时复用首次 run 持久化的 linkedChanges,不在管道/CI 下重复弹交互 prompt。
633
+ // explicitLinked === null 且未传 --change 时才进入此分支(显式 --linked-changes none 不应触发交互)。
634
+ if (stageName === 'quick' && explicitLinked === null && linkedChanges.length === 0) {
635
+ // D-002:guard 按 session 存(.runtime/quick-sessions/<sessionId>/guard.json)。
636
+ // sessionId == changeName == quick-<uuid8>(上面参数解析已确定)。回退读旧单文件 quick-guard.json(task-03 前兼容)。
637
+ let persistedLinked = null
638
+ try {
639
+ const sessionGuardFile = join(specRoot, '.runtime', 'quick-sessions', changeName, 'guard.json')
640
+ const legacyGuardFile = join(specRoot, '.runtime', 'quick-guard.json')
641
+ const g = existsSync(sessionGuardFile)
642
+ ? JSON.parse(readFileSync(sessionGuardFile, 'utf8'))
643
+ : (existsSync(legacyGuardFile) ? JSON.parse(readFileSync(legacyGuardFile, 'utf8')) : null)
644
+ if (g && Array.isArray(g.linkedChanges)) persistedLinked = g.linkedChanges
645
+ } catch {}
646
+ if (persistedLinked) {
647
+ linkedChanges = persistedLinked
648
+ } else {
649
+ linkedChanges = await resolveQuickLinkedChanges({
650
+ pm, cwd, specDir: specRoot, quickFiles,
651
+ taskDescription: inputText || '',
652
+ nonInteractive: isNonInteractive,
653
+ })
654
+ }
655
+ }
656
+
657
+ // execute 阶段必须带 --change:不允许自动检测或默认值,变更名必须由 agent 显式传入
658
+ // --status 豁免(纯查看不需要指定变更)
659
+ if (stageName === 'execute' && !changeName && !isStatus) {
660
+ console.error('❌ execute 阶段必须用 --change <变更名> 指定要操作的变更。')
661
+ console.error(' agent 必须传参,不设默认值、不做自动检测。')
662
+ console.error(' 请加 --change <变更名> 重新执行。')
663
+ process.exit(2) // 用法错(execute 必须显式 --change)→ exit 2
664
+ }
665
+
666
+ // worktree 副本漂移自动锚定守卫(坑 worktree-execute-spec-drift,D-03@v1):specBase 命中 worktree 内
667
+ // .sillyspec checkout 副本 = agent 误 cd 进 worktree 跑 plan/execute/verify/archive(100% 误操作场景)。
668
+ // 不 exit:自动把 specBase 锚回主仓 wt.mainSpecBase 后继续——进度/产出落主仓,不再写分裂副本(副本随
669
+ // 工作树清理丢失)。必须在 validateChangeExists 之前:副本里 change 目录真实存在,存在性校验会被骗
670
+ // 放行;锚定后用主仓 specBase 复查。覆盖 plan/execute/verify/archive(validateChangeExists 同 Set)。
671
+ // 关键坑:连带重写 specBase/specRoot/specDir + 重建 pm——四者同源派生(pm._customSpecDir 持旧 specRoot),
672
+ // 只改 specBase 会让下游 validateChangeExists(specBase) 与 pm.read(走 pm._customSpecDir) 仍指副本。
673
+ // 平台模式/显式 --spec-dir 跳过(已明确指定,与 line~285 warn / quick 守卫条件对齐)。
674
+ // 其他漂移(下方 changeMissing 守卫 / quick session drift 守卫)非副本场景,仍 exit(2) 不自动纠正。
675
+ if (!platformOpts.specRoot && !specDir
676
+ && ['plan', 'execute', 'verify', 'archive'].includes(stageName)) {
677
+ const wt = detectWorktreeSpecDrift(specBase)
678
+ if (wt) {
679
+ specBase = wt.mainSpecBase
680
+ specRoot = wt.mainSpecBase
681
+ specDir = wt.mainSpecBase
682
+ pm = new ProgressManager({ specDir: specRoot })
683
+ // 【坑 execute-runs-isolation】下游 runtimeRoot 解析(execute-runs/stage-reviews 落点)经
684
+ // platformOpts 透传读此锚点,落主仓 .runtime,不随 worktree cleanup 整目录删消失。
685
+ // D-02:只参与 runtimeRoot 解析(resolveRuntimeRoot),绝不设 specRoot/runtimeRoot——
686
+ // 否则触发平台 sentinel 副作用(triggerSync/checkApproval 跳过 + prompt 误进平台渲染分支)。
687
+ platformOpts.specDriftAnchor = wt.mainSpecBase
688
+ console.warn(`⚠️ 已自动锚定主仓 spec:${wt.mainSpecBase}(原 cwd 命中 worktree 副本 ${wt.changeName},已纠正,流程继续)`)
689
+ }
690
+ }
691
+
692
+ // --change 变更名存在性校验(治 cwd 漂移误匹配,缺陷 execute-in-place-windows-pitfalls 坑5):
693
+ // 必须在 pm.read/initChange 之前——initChange 会为 --change 指定的新名字创建 changes/ 目录,
694
+ // 校验若在其后则目录已存在、永远通过。用原始 changeName(--change 参数),覆盖 plan/execute/
695
+ // verify/archive;quick-<8hex> sessionId 与 brainstorm 新建豁免(见 validateChangeExists)。
696
+ const changeMissing = validateChangeExists(specBase, stageName, changeName)
697
+ if (changeMissing) {
698
+ console.error(`❌ ${changeMissing.message}`)
699
+ console.error(` 可能 cwd 漂移——当前 cwd=${cwd},命中的 spec=${specBase}。`)
700
+ console.error(` 若意图操作别的项目,请 cd 到对应项目根,或用 --spec-dir 指定正确的 spec 目录。`)
701
+ process.exit(2) // 环境错(cwd/spec 漂移)→ exit 2
702
+ }
703
+
704
+ // quick 专用 cwd 漂移 fail-fast 守卫(坑 quick-cwd-drift-splits-specdir):
705
+ // quick 被 validateChangeExists 的 sessionId 豁免(quick-<8hex> 不在 changes/ 下),漂移时除上方
706
+ // countAncestorSpecDirs 的 warn 外无硬守卫 → 无声分裂(progress/artifact/QUICKLOG 落子项目、根
707
+ // 会话停滞)。这里补:当前 specBase 无本 session guard、但祖先链别处有 = 跨 specDir 漂移 → fail-fast。
708
+ // 平台模式/显式 --spec-dir 跳过(specBase 已明确,与 line~285 warn 条件对齐)。
709
+ if (stageName === 'quick' && changeName && /^quick-[0-9a-f]{8}$/.test(changeName)
710
+ && !platformOpts.specRoot && !specDir) {
711
+ const drift = detectQuickSessionDrift(cwd, specBase, changeName)
712
+ if (drift) {
713
+ console.error(`❌ ${drift.message}`)
714
+ console.error(` 当前 cwd=${cwd},命中的 spec=${specBase}。`)
715
+ process.exit(2) // 环境错(cwd/spec 漂移)→ exit 2
716
+ }
717
+ }
718
+
719
+ let progress = pm.read(cwd, changeName)
720
+
721
+ // task-03 (D-005@v2 / FR-04): READONLY_AUXILIARY_STAGES(status/doctor)查询只读短路。
722
+ // 无显式写 flag 时在 registerChange / ensureStageSteps 之前拦截,零副作用:
723
+ // - 目标 progress 不存在 → 提示「只读查询不建变更」exit 0(不 initChange、不建 default 行,治 8b)
724
+ // - 目标 progress 存在 → 只读展示,不 seed steps、不刷新 lastActive、不 registerChange
725
+ // (治 B7 多 agent 并发 lastActive 互相覆盖)
726
+ // 显式写意图不短路:doctor 写操作 flag(--cleanup-remnant / --align-execute-progress)与
727
+ // 步骤动作 flag(--done/--skip/--reset/--reopen/--wait/--continue)走原写路径;--status 本身
728
+ // 是只读查询,纳入短路。--fix 是 worktree doctor 的 flag 不在此列(design.md Phase 4)。
729
+ const READONLY_WRITE_ACTIONS = ['--cleanup-remnant', '--align-execute-progress', '--done', '--skip', '--reset', '--reopen', '--wait', '--continue']
730
+ if (READONLY_AUXILIARY_STAGES.includes(stageName) && !flags.some(f => READONLY_WRITE_ACTIONS.includes(f))) {
731
+ if (!progress) {
732
+ console.log('ℹ️ 未找到进度数据(只读查询不建变更)')
733
+ process.exit(0)
734
+ }
735
+ // 只读展示路径:复用阶段定义渲染当前步骤 prompt(outputStep 对 status/doctor 纯只读),
736
+ // 不落盘任何 progress 改动。--status 走现有 showStatus 展示。
737
+ const readOnlyChange = changeName || progress.currentChange || resolveChangeName(cwd, progress, specRoot)
738
+ if (isStatus) {
739
+ let nextSuggestion = null
740
+ try { nextSuggestion = pm._getNextSuggestion(progress) } catch { /* 读建议失败不阻断展示 */ }
741
+ return showStatus(progress, stageName, nextSuggestion)
742
+ }
743
+ const readonlySteps = await getStageSteps(stageName, cwd, progress, specRoot)
744
+ if (readonlySteps && readonlySteps.length > 0) {
745
+ // 已有进度(历史 seed 过)则渲染当前待办步;无进度从首步开始
746
+ const existingSteps = progress.stages?.[stageName]?.steps
747
+ const pendingIdx = existingSteps ? existingSteps.findIndex(s => s.status === 'pending' || s.status === 'in-progress') : -1
748
+ const stepIdx = pendingIdx !== -1 ? pendingIdx : 0
749
+ await outputStep(stageName, stepIdx, readonlySteps, cwd, readOnlyChange, progress.project || null, platformOpts)
750
+ }
751
+ return
752
+ }
753
+
754
+ if (!progress) {
755
+ // 如果指定了变更名或有变更目录,自动初始化变更的 progress
756
+ const autoChange = changeName || resolveChangeNameAuto(cwd, specRoot)
757
+ if (autoChange) {
758
+ // 创建时即写 title(与 name/KEY 同时落 db):--input 需求描述 sanitizeDesc 优先,无则用 name 兜底。
759
+ // proposal 还没写、无权威标题来源,这是临时值;brainstorm/plan 完成 proposal/design 落盘后由
760
+ // complete.js 通用完成路径 deriveTitleFromLinkedChange 刷新为真实 # 标题(与 quick 启动 title 同源)。
761
+ progress = pm.initChange(cwd, autoChange, { title: inputText ? sanitizeDesc(inputText) : autoChange })
762
+ } else if (isAuxiliary) {
763
+ let autoName = changeName || resolveChangeNameAuto(cwd, specRoot) || 'default'
764
+ // archive 特例:归档后变更从活跃列表排除(listChanges WHERE status='active'),
765
+ // 不带 --change 回退 default 会读错变更。无活跃变更时取最新归档变更,读其现有 progress。
766
+ if (stageName === 'archive' && autoName === 'default') {
767
+ try {
768
+ const archiveDir = join(specBase, 'changes', 'archive')
769
+ if (existsSync(archiveDir)) {
770
+ const latest = readdirSync(archiveDir)
771
+ .filter(d => /^\d{4}-\d{2}-\d{2}-.+/.test(d))
772
+ .sort()
773
+ .pop()
774
+ if (latest) {
775
+ autoName = latest.replace(/^\d{4}-\d{2}-\d{2}-/, '')
776
+ progress = pm.read(cwd, autoName)
777
+ }
778
+ }
779
+ } catch {}
780
+ }
781
+ changeName = autoName
782
+ if (!progress) {
783
+ // auxiliary 创建也写 title(--input 优先 / name 兜底),同上完整流程语义。
784
+ progress = pm.initChange(cwd, autoName, { title: inputText ? sanitizeDesc(inputText) : autoName })
785
+ // initChange 可能因 project 表为空返回 null
786
+ if (!progress) {
787
+ progress = { currentStage: stageName, stages: {}, lastActive: new Date().toLocaleString('zh-CN', { hour12: false }), project: '' }
788
+ }
789
+ }
790
+ } else {
791
+ // brainstorm 作为流程入口,自动生成变更名并初始化
792
+ if (stageName === 'brainstorm') {
793
+ if (isDone) {
794
+ console.error('❌ --done 找不到变更进度数据。')
795
+ console.error(' 请用 --change <变更名> 指定要完成的变更,')
796
+ console.error(' 或先运行 sillyspec run brainstorm --change <变更名> 初始化。')
797
+ process.exit(2) // 用法错(--done 找不到变更,未传 --change)→ exit 2
798
+ }
799
+ // task-03 (D-006@v1 / FR-05): 无 --change 仅当无已存在活跃变更时 auto-create;
800
+ // 多活跃变更仓强制 --change(exit 2 引导),防 B8 幽灵变更。活跃变更数用 pm.listChanges
801
+ // (与 progress show 同源,DB changes 表 status='active')。
802
+ const activeChanges = pm.listChanges(cwd)
803
+ if (activeChanges.length > 0) {
804
+ console.error(`❌ 已存在 ${activeChanges.length} 个活跃变更,run brainstorm 无 --change 不会自动创建新变更。`)
805
+ console.error(` 活跃变更:${activeChanges.join('、')}`)
806
+ console.error(' 请用 --change <变更名> 指定要操作的变更,')
807
+ console.error(' 或先归档/收尾现有活跃变更后重试。')
808
+ process.exit(2) // 用法错(多活跃变更未指定 --change)→ exit 2
809
+ }
810
+ const date = new Date().toISOString().slice(0, 10)
811
+ const autoName = `${date}-new-change-${randomBytes(4).toString('hex')}`
812
+ console.log(`🔄 自动创建变更:${autoName}`)
813
+ console.log(` 提示:可以用 --change <名称> 指定自定义变更名`)
814
+ console.log(` 或事后重命名:sillyspec change-rename ${autoName} <新名称>`)
815
+ // brainstorm 自动创建变更也写 title(--input 需求描述优先 / 自动名兜底),proposal 落盘后刷新。
816
+ progress = pm.initChange(cwd, autoName, { title: inputText ? sanitizeDesc(inputText) : autoName })
817
+ changeName = autoName
818
+ } else {
819
+ console.error('❌ 未找到进度数据,请先运行 sillyspec init 或指定 --change <变更名>')
820
+ process.exit(2) // 环境错(未 init / 未传 --change)→ exit 2
821
+ }
822
+ }
823
+ }
824
+
825
+ // 确保 progress 有 currentChange
826
+ const effectiveChange = changeName || progress.currentChange || resolveChangeName(cwd, progress, specRoot)
827
+
828
+ // ── Q7:quick --done 不带 --change 时 fallback 读 current-quick-run-id 可能命中他者会话 ──
829
+ // 并发两 quick 会话:B 后启动覆盖 A 的 id(last-writer-wins),A 的 --done 不带 --change → 读到 B 的 sessionId
830
+ // → 误操作 B 的 progress/QUICKLOG。fallback 命中的会话若已完成或无可推进步骤(id stale / 他者已收尾),
831
+ // 拒绝推进并要求显式 --change。(live A/B race 需 per-session 锚 commit,见 review Q2/D2,本守卫只兜 stale/completed。)
832
+ if (stageName === 'quick' && isDone && quickFallbackUsed) {
833
+ const qs = progress.stages.quick
834
+ const hasActionable = qs?.steps && qs.steps.some(s => s.status === 'pending' || s.status === 'waiting' || s.status === 'in-progress')
835
+ if (!qs || qs.status === 'completed' || !hasActionable) {
836
+ console.error(`\n❌ --done 未带 --change,回退读到的 quick 会话 ${changeName} 已不可推进(已完成或无待办步骤)。`)
837
+ console.error(` 并发多 quick 会话时 .runtime/current-quick-run-id 可能指向他者会话(last-writer-wins)。`)
838
+ console.error(` 请显式带 --change <quick-session-id> 指定要完成的会话(sillyspec run quick --status 查各会话进度)。`)
839
+ process.exit(2) // 用法错(fallback 命中 stale/他者会话)→ exit 2
840
+ }
841
+ }
842
+
843
+ // -- auto 模式:自动推进所有流程阶段
844
+ if (stageName === 'auto') {
845
+ return await runAutoMode(pm, progress, cwd, flags, effectiveChange, platformOpts)
846
+ }
847
+
848
+ // --change 只作为变更名标识,不再拦截流程
849
+ // 注册变更到全局活跃列表(如果尚未注册)
850
+ if (effectiveChange) {
851
+ pm.registerChange(cwd, effectiveChange)
852
+ }
853
+
854
+ // --reset
855
+ if (isReset) {
856
+ return await resetStage(pm, progress, stageName, cwd, effectiveChange, platformOpts)
857
+ }
858
+
859
+ // ── 规则 1:completed 阶段直接 run,拒绝(但 --status 放行)──
860
+ const stageStatus = progress.stages[stageName]?.status
861
+ if (stageStatus === 'completed' && !isReopen && !isStatus) {
862
+ console.error(`\n❌ ${stageName} 阶段已完成。`)
863
+ console.error(` 使用 --reopen 进行修订,或 --reset 从头开始。`)
864
+ console.error(` 修订示例: sillyspec run ${stageName} --reopen --from-step <步骤序号或名称>`)
865
+ process.exit(1)
866
+ }
867
+
868
+ // ── 规则 5:stale 阶段直接 run,拒绝(但 --status / --reset 放行)──
869
+ if (stageStatus === 'stale' && !isReopen && !isStatus && !isReset) {
870
+ const staleReason = progress.stages[stageName]?.staleReason || '上游阶段已修订'
871
+ console.error(`\n⚠️ ${stageName} 阶段已失效(stale)。`)
872
+ console.error(` 原因:${staleReason}`)
873
+ console.error(` 使用 --reopen --from-step <步骤> 进行修订,或 --reset 从头开始。`)
874
+ process.exit(1)
875
+ }
876
+
877
+ // ── --reopen 处理 ──
878
+ if (isReopen) {
879
+ // stale/revising 阶段可能 steps 为空,或者 execute 阶段的 steps 需要从最新 plan.md 刷新
880
+ const stageDataPre = progress.stages[stageName]
881
+ const needsInit = !stageDataPre || !stageDataPre.steps || stageDataPre.steps.length === 0
882
+ // execute 阶段在 reopen 时需要从最新 plan.md 重新解析 steps(plan 可能已变更)
883
+ if (needsInit || stageName === 'execute') {
884
+ const freshSteps = await getStageSteps(stageName, cwd, progress, specRoot)
885
+ if (freshSteps && freshSteps.length > 0) {
886
+ if (!progress.stages[stageName]) progress.stages[stageName] = { status: 'stale', steps: [] }
887
+ progress.stages[stageName].steps = freshSteps.map(s => ({ name: s.name, status: 'pending' }))
888
+ pm._write(cwd, progress, effectiveChange)
889
+ progress = pm.read(cwd, effectiveChange) || progress
890
+ }
891
+ }
892
+
893
+ const result = pm.reopenStage(cwd, stageName, {
894
+ fromStep: fromStepValue,
895
+ changeName: effectiveChange,
896
+ })
897
+ if (!result.ok) {
898
+ console.error(`\n❌ ${result.error}`)
899
+ if (stageStatus === 'completed') {
900
+ console.error(`\n 提示:sillyspec run ${stageName} --reopen --from-step <步骤序号或名称>`)
901
+ }
902
+ process.exit(1)
903
+ }
904
+ console.log(`\n🔧 ${stageName} 阶段已重新打开(revision ${result.revision})`)
905
+ console.log(` 从步骤「${result.fromStep}」开始修订`)
906
+ console.log(` 该步骤及之后的产出需要重新生成。`)
907
+ if (stageName === 'execute') console.log(` ⚡ execute 步骤已从最新 plan.md 重新解析。`)
908
+ console.log('')
909
+
910
+ // 重新读取 progress
911
+ progress = pm.read(cwd, effectiveChange) || progress
912
+
913
+ // 注入 revision context 到 platformOpts,供 outputStep 使用
914
+ const stageData = progress.stages[stageName]
915
+ if (stageData && stageData.revision > 0) {
916
+ platformOpts._revision = {
917
+ revision: stageData.revision,
918
+ fromStep: stageData.reopenedFromStep,
919
+ }
920
+ }
921
+ } else {
922
+ // 非 reopen 的正常执行:如果阶段处于 revising 状态,也注入 revision context
923
+ const revStageData = progress.stages[stageName]
924
+ if (revStageData && revStageData.status === 'revising' && revStageData.revision > 0 && !platformOpts._revision) {
925
+ platformOpts._revision = {
926
+ revision: revStageData.revision,
927
+ fromStep: revStageData.reopenedFromStep,
928
+ }
929
+ }
930
+ }
931
+
932
+ // quick 启动(非 --done):reset steps + 写 current-quick-run-id(本会话 sessionId,作 --done fallback)。
933
+ // sessionId 已在参数解析阶段生成(quickSessionId == changeName == quick-<uuid8>),
934
+ // 这里复用同一值写 current-quick-run-id,保证两处一致。
935
+ // 旧 quick-YYYYMMDD-HHMMSS 时间戳已摒弃(D-003@v1:同秒并发撞)。
936
+ if (stageName === 'quick' && !isDone && !isStatus && !isSkip && !isReset && !isReopen) {
937
+ // 不再无条件 reset steps:原逻辑把任何 quick 非 --done 启动都重置为 pending,致 in-progress
938
+ // 的 quick 中途查 prompt(sillyspec run quick)丢已 done 的 step 进度(报告
939
+ // quick-state-reset-platform-mode)。现保留进度——completed 重跑由 runStage 内
940
+ // currentIdx === -1 自动重置(~1944 行);in-progress 输出当前 step;全新由
941
+ // ensureStageSteps 初始化;显式从头用 --reset(已由 !isReset 排除出本分支)。
942
+ try {
943
+ const runtimeRoot = resolveRuntimeRoot(platformOpts, specRoot)
944
+ mkdirSync(runtimeRoot, { recursive: true })
945
+ writeAtomicSync(join(runtimeRoot, 'current-quick-run-id'), quickSessionId + '\n')
946
+ } catch (e) {
947
+ // 写失败不能静默:--done 不带 --change 时靠这个文件做跨进程 fallback,写不成就必须显式带 --change
948
+ console.warn(`⚠️ current-quick-run-id 写入失败(${e.message}),--done 必须显式带 --change ${quickSessionId}`)
949
+ }
950
+ // 显式告知 agent 本会话 sessionId + --done 需带 --change(CLI 短进程,run/done 独立进程,
951
+ // sessionId 靠 --change 跨进程传递;不带 --change 时 fallback 读 current-quick-run-id,多会话不可靠)
952
+ console.log(`📌 本 quick 会话 sessionId: ${quickSessionId}`)
953
+ console.log(` 完成时用: sillyspec run quick --done --change ${quickSessionId} --output "..."`)
954
+ }
955
+
956
+ // 确保步骤已初始化
957
+ const changed = await ensureStageSteps(progress, stageName, cwd, specRoot)
958
+ if (changed && effectiveChange) {
959
+ pm._write(cwd, progress, effectiveChange)
960
+ triggerSync(cwd, effectiveChange, platformOpts)
961
+ progress = pm.read(cwd, effectiveChange) || progress
962
+ }
963
+
964
+ // --status
965
+ if (isStatus) {
966
+ // D9:状态展示末尾附「下一步该跑什么」。pm 持有状态机,按 progress 实际进度算出精确命令;
967
+ // 不传则 agent 只看到一堆 step 进度条,却不知道完成后/卡住时下一条命令是什么。
968
+ let nextSuggestion = null
969
+ try { nextSuggestion = pm._getNextSuggestion(progress) } catch { /* 读建议失败不阻断状态展示 */ }
970
+ return showStatus(progress, stageName, nextSuggestion)
971
+ }
972
+
973
+ // --skip
974
+ if (isSkip) {
975
+ return await skipStep(pm, progress, stageName, cwd, effectiveChange, platformOpts)
976
+ }
977
+
978
+ // --wait: 将 step 设为 waiting(独立于 --done)
979
+ if (isWait) {
980
+ return await waitStep(pm, progress, stageName, cwd, outputText, waitReason, waitOptions, { changeName: effectiveChange, nonInteractive: isNonInteractive && !isInteractive, platformOpts })
981
+ }
982
+
983
+ // --continue: 从 waiting 恢复
984
+ if (isContinue) {
985
+ return await continueStep(pm, progress, stageName, cwd, continueAnswer, { changeName: effectiveChange, nonInteractive: isNonInteractive && !isInteractive, platformOpts, fromStep: fromStepValue })
986
+ }
987
+
988
+ // --done
989
+ if (isDone) {
990
+ // task-03 (D-004@v1 / FR-02): --done 与 runStage(stage.js:35-45)同源状态转换守卫,
991
+ // 含 fromStageData 透传(让 scan failed_post_check 门控对 --done 同样生效)。
992
+ // auxiliary 的 --done 不受影响(checkTransition 对 auxiliary toStage 放行,见 stage-contract.js)。
993
+ // --skip-approval 绕过语义对齐 runStage(打错但放行)。
994
+ const prevStage = progress.currentStage || ''
995
+ const fromStageData = (progress.stages && prevStage && progress.stages[prevStage]) || undefined
996
+ const transition = checkTransition(prevStage, stageName, fromStageData ? { fromStageData } : {})
997
+ if (!transition.allowed) {
998
+ console.error(`❌ 阶段转换不允许: ${prevStage || '(起始)'} → ${stageName}`)
999
+ console.error(` 原因: ${transition.reason}`)
1000
+ console.error(` 提示: 使用 --skip-approval 绕过(需明确意图)`)
1001
+ if (!isSkipApproval) {
1002
+ process.exit(1)
1003
+ }
1004
+ }
1005
+ const doneAnswer = getFlagValue('--answer')
1006
+ return await completeStep(pm, progress, stageName, cwd, outputText, inputText, { confirm: isConfirm, changeName: effectiveChange, nonInteractive: isNonInteractive && !isInteractive, platformOpts, doneAnswer, isForceBaseline, isAllowNew, isAllowDelete })
1007
+ }
1008
+
1009
+ // 默认:输出当前步骤
1010
+ return await runStage(pm, progress, stageName, cwd, effectiveChange, isSkipApproval, platformOpts, { quickFiles, isAllowNew, isAllowDelete, isForceBaseline, isForceRescan, linkedChanges, taskDescription: inputText })
1011
+ }
1012
+
1013
+ /**
1014
+ * 自动推导变更名(不依赖 progress)
1015
+ */
1016
+ function resolveChangeNameAuto(cwd, specDir = null) {
1017
+ const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
1018
+ if (!existsSync(changesDir)) return null
1019
+ const entries = readdirSync(changesDir, { withFileTypes: true })
1020
+ .filter(e => e.isDirectory() && e.name !== 'archive')
1021
+ if (entries.length === 1) return entries[0].name
1022
+ return null
1023
+ }
1024
+
1025
+ function showStatus(progress, stageName, nextSuggestion = null) {
1026
+ const stageData = progress.stages[stageName]
1027
+ const stageDef = stageRegistry[stageName]
1028
+
1029
+ if (!stageData || !stageData.steps || stageData.steps.length === 0) {
1030
+ console.log(`阶段:${stageName}(${stageDef?.title || stageName})`)
1031
+ console.log(`进度:未初始化`)
1032
+ if (stageData?.status) {
1033
+ console.log(`状态:${stageData.status}`)
1034
+ if (stageData.staleReason) console.log(`⚠️ 失效原因:${stageData.staleReason}`)
1035
+ }
1036
+ return
1037
+ }
1038
+
1039
+ const steps = stageData.steps
1040
+ const completed = steps.filter(s => s.status === 'completed' || s.status === 'skipped').length
1041
+ const bar = '█'.repeat(completed) + '░'.repeat(steps.length - completed)
1042
+
1043
+ console.log(`阶段:${stageName}(${stageDef?.title || stageName})`)
1044
+ console.log(`进度:[${bar}] ${completed}/${steps.length}`)
1045
+
1046
+ // ── Revision v1 信息 ──
1047
+ if (stageData.status === 'revising') {
1048
+ console.log(`\n🔧 修订中 (revision ${stageData.revision || 1})`)
1049
+ if (stageData.reopenedFromStep) console.log(` 从步骤:${stageData.reopenedFromStep}`)
1050
+ if (stageData.reopenedAt) console.log(` 重开时间:${stageData.reopenedAt}`)
1051
+ }
1052
+ if (stageData.status === 'stale') {
1053
+ console.log(`\n⚠️ 已失效`)
1054
+ if (stageData.staleReason) console.log(` 原因:${stageData.staleReason}`)
1055
+ console.log(` 建议:sillyspec run ${stageName} --reopen --from-step 1`)
1056
+ }
1057
+ if (stageData.status === 'completed') {
1058
+ console.log(`\n✅ 已完成`)
1059
+ }
1060
+
1061
+ console.log('')
1062
+
1063
+ const firstPending = steps.findIndex(s => s.status === 'pending' || s.status === 'in-progress')
1064
+
1065
+ if (progress.batchProgress) {
1066
+ const bp = progress.batchProgress
1067
+ const bpTotal = bp.total || 0
1068
+ const bpCompleted = bp.completed || 0
1069
+ const bpFailed = bp.failed || 0
1070
+ const bpSkipped = bp.skipped || 0
1071
+ const bpBarLen = 20
1072
+ const bpFilled = Math.round((bpCompleted / Math.max(bpTotal, 1)) * bpBarLen)
1073
+ const bpBar = '█'.repeat(bpFilled) + '░'.repeat(bpBarLen - bpFilled)
1074
+ const bpParts = []
1075
+ if (bpFailed > 0) bpParts.push(`${bpFailed} 失败`)
1076
+ if (bpSkipped > 0) bpParts.push(`${bpSkipped} 跳过`)
1077
+ const bpSuffix = bpParts.length ? ` (${bpParts.join(', ')})` : ''
1078
+ console.log(`\n📊 批量进度: ${bpBar} ${bpCompleted}/${bpTotal}${bpSuffix}\n`)
1079
+ }
1080
+
1081
+ steps.forEach((step, i) => {
1082
+ const icon = step.status === 'completed' ? '✅' : step.status === 'skipped' ? '⏭️' : step.status === 'waiting' ? '⏸️' : '⬜'
1083
+ const isCurrent = (step.status === 'pending' || step.status === 'in-progress') && i === firstPending
1084
+ const isWaiting = step.status === 'waiting'
1085
+ console.log(`${icon} Step ${i + 1}: ${step.name}${isCurrent ? ' ← 当前' : ''}${isWaiting ? ' [WAITING]' : ''}`)
1086
+ if (isWaiting) {
1087
+ if (step.waitReason) console.log(` 原因:${step.waitReason}`)
1088
+ if (step.waitOptions) console.log(` 选项:${formatWaitOptions(step.waitOptions)}`)
1089
+ if (step.waitedAt) console.log(` 等待时间:${step.waitedAt}`)
1090
+ }
1091
+ })
1092
+
1093
+ // D9:本阶段进度之后,给出全局「下一步该跑什么」——
1094
+ // 否则 agent 看完进度条仍要自己推状态机(尤其阶段已完成 / 失效 / 修订中这类非线性状态)。
1095
+ if (nextSuggestion && nextSuggestion.command) {
1096
+ console.log(`\n👉 ${nextSuggestion.text}`)
1097
+ console.log(` 下一步命令:${nextSuggestion.command}`)
1098
+ }
1099
+ }
1100
+
1101
+ async function resetStage(pm, progress, stageName, cwd, changeName, platformOpts = {}) {
1102
+ // execute 阶段 reset 时清理自建 worktree,否则下次 run execute 会因 existingMeta 存在
1103
+ // 直接复用带脏状态的旧 worktree(启动逻辑:meta 存在即复用,不查健康状态)
1104
+ if (stageName === 'execute' && changeName) {
1105
+ try {
1106
+ const { WorktreeManager } = await import('../worktree.js')
1107
+ const wm = new WorktreeManager({ cwd })
1108
+ const meta = wm.getMeta(changeName)
1109
+ if (meta) {
1110
+ const cleanResult = wm.cleanup(changeName, { force: true })
1111
+ if (cleanResult.residual?.length > 0) {
1112
+ console.warn(`⚠️ reset 清理 worktree 残留: ${cleanResult.residual.join('; ')}`)
1113
+ console.warn(` 手动处理: sillyspec worktree cleanup ${changeName} --force`)
1114
+ } else if (cleanResult.result === 'kept') {
1115
+ console.log(`🔗 旧 worktree 保留 (${cleanResult.mode}: 外部隔离环境)`)
1116
+ } else if (cleanResult.result !== 'skipped') {
1117
+ console.log(`🧹 已清理旧 worktree (${cleanResult.result}, mode: ${cleanResult.mode}),下次 execute 将重建干净环境`)
1118
+ }
1119
+ }
1120
+ } catch (e) {
1121
+ console.warn(`⚠️ reset 清理 worktree 失败(不阻断 reset): ${e.message}`)
1122
+ }
1123
+ }
1124
+ const defSteps = await getStageSteps(stageName, cwd, progress, platformOpts?.specRoot || null)
1125
+ progress.stages[stageName] = {
1126
+ status: 'in-progress',
1127
+ startedAt: new Date().toLocaleString('zh-CN',{hour12:false}),
1128
+ completedAt: null,
1129
+ steps: defSteps ? defSteps.map(s => ({ name: s.name, status: 'pending' })) : []
1130
+ }
1131
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
1132
+ pm._write(cwd, progress, changeName)
1133
+ triggerSync(cwd, changeName, platformOpts)
1134
+ console.log(`🔄 ${stageName} 阶段已重置`)
1135
+ }
1136
+
1137
+ /**
1138
+ * auto 模式:自动推进 brainstorm → plan → execute → verify
1139
+ */
1140
+ async function runAutoMode(pm, progress, cwd, flags, changeName, platformOpts = {}) {
1141
+ const flowStages = ['brainstorm', 'plan', 'execute', 'verify', 'archive']
1142
+ const isDone = flags.includes('--done')
1143
+ const outputIdx = flags.indexOf('--output')
1144
+ const outputText = outputIdx !== -1 && flags[outputIdx + 1] ? flags[outputIdx + 1] : null
1145
+ const inputIdx = flags.indexOf('--input')
1146
+ const inputText = inputIdx !== -1 && flags[inputIdx + 1] ? flags[inputIdx + 1] : null
1147
+ const skipApproval = flags.includes('--skip-approval')
1148
+ const explicitMode = (() => {
1149
+ const m = flags.indexOf('--mode')
1150
+ return m !== -1 && flags[m + 1] ? flags[m + 1] : null
1151
+ })()
1152
+ const specBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
1153
+
1154
+ // Helper: 在 auto 模式下获取步骤定义
1155
+ const getAutoSteps = async (stage) => {
1156
+ if (stage === 'brainstorm') {
1157
+ return brainstormAutoDef.steps
1158
+ }
1159
+ return getStageSteps(stage, cwd, progress, platformOpts?.specRoot || null)
1160
+ }
1161
+
1162
+ const nextInFlow = (stage) => {
1163
+ const i = flowStages.indexOf(stage)
1164
+ return i >= 0 && i < flowStages.length - 1 ? flowStages[i + 1] : null
1165
+ }
1166
+ const firstOpenStage = () => flowStages.find(s => progress.stages?.[s]?.status !== 'completed')
1167
+ const ensureAutoStage = async (stage) => {
1168
+ const stageChanged = progress.currentStage !== stage
1169
+ progress.currentStage = stage
1170
+ // Auto 模式下 brainstorm 使用 artifact-first 步骤
1171
+ if (stage === 'brainstorm') {
1172
+ const existingSteps = progress.stages?.brainstorm?.steps
1173
+ const isAutoModeSteps = existingSteps?.length === 4 && existingSteps?.[0]?.name === '进度确认与上下文加载'
1174
+ if (!isAutoModeSteps) {
1175
+ if (!progress.stages) progress.stages = {}
1176
+ progress.stages.brainstorm = {
1177
+ status: 'in-progress',
1178
+ startedAt: new Date().toLocaleString('zh-CN', { hour12: false }),
1179
+ completedAt: null,
1180
+ steps: brainstormAutoDef.steps.map(s => ({ name: s.name, status: 'pending' }))
1181
+ }
1182
+ pm._write(cwd, progress, changeName)
1183
+ triggerSync(cwd, changeName, platformOpts)
1184
+ progress = pm.read(cwd, changeName)
1185
+ return progress
1186
+ }
1187
+ }
1188
+ const changed = await ensureStageSteps(progress, stage, cwd)
1189
+ if (stageChanged || changed) {
1190
+ pm._write(cwd, progress, changeName)
1191
+ triggerSync(cwd, changeName, platformOpts)
1192
+ }
1193
+ progress = pm.read(cwd, changeName)
1194
+ return progress
1195
+ }
1196
+
1197
+ // ── Classify change on first entry ──
1198
+ if (!progress.stages?.brainstorm?.status && !progress.stages?.plan?.status) {
1199
+ const { classifyChange, readAutoModeFromLocalYaml } = await import('../classify-change.js')
1200
+ // auto_mode 接线(2026-08-11):从 local.yaml 读 auto_mode 段传 localConfig,让 force_*_patterns 真生效。
1201
+ const localConfig = readAutoModeFromLocalYaml(cwd)
1202
+ const classification = classifyChange({ description: inputText || '', explicitMode, localConfig })
1203
+ if (classification.mode === 'quick') {
1204
+ console.log(`📊 auto 模式分类:${classification.mode}(${classification.reason})`)
1205
+ console.log(` 此变更建议使用 quick 模式,运行:sillyspec run quick "${inputText || '需求'}"`)
1206
+ return
1207
+ }
1208
+ console.log(`📊 auto 模式分类:${classification.mode}(${classification.reason})`)
1209
+ }
1210
+
1211
+ let currentStage = progress.currentStage
1212
+ if (!currentStage || progress.stages?.[currentStage]?.status === 'completed') {
1213
+ currentStage = firstOpenStage()
1214
+ }
1215
+ if (!currentStage) {
1216
+ console.log('All auto flow stages are complete.')
1217
+ return
1218
+ }
1219
+ if (!flowStages.includes(currentStage)) {
1220
+ const openStage = firstOpenStage()
1221
+ if (!openStage) {
1222
+ console.log('All auto flow stages are complete.')
1223
+ return
1224
+ }
1225
+ console.log(`⚠️ 当前阶段 ${currentStage} 不在 auto 流程中,自动跳转到 ${openStage}`)
1226
+ currentStage = openStage
1227
+ }
1228
+ await ensureAutoStage(currentStage)
1229
+
1230
+ if (!isDone) {
1231
+ console.log('════════════════════════════════════════')
1232
+ console.log(' SillySpec Auto Mode')
1233
+ if (changeName) console.log(` Change: ${changeName}`)
1234
+ console.log('════════════════════════════════════════')
1235
+ console.log(` Flow: ${flowStages.join(' -> ')}`)
1236
+ console.log(` Current: ${currentStage}`)
1237
+ for (const stage of flowStages) {
1238
+ const stageData = progress.stages?.[stage]
1239
+ const total = stageData?.steps?.length || '?'
1240
+ const completed = stageData?.steps?.filter(step => step.status === 'completed' || step.status === 'skipped').length || 0
1241
+ const marker = stageData?.status === 'completed' ? 'done' : stage === currentStage ? 'active' : 'pending'
1242
+ console.log(` ${marker} ${stage} (${completed}/${total})`)
1243
+ }
1244
+ console.log('')
1245
+
1246
+ const defSteps = await getAutoSteps(currentStage)
1247
+ const pendingIdx = progress.stages[currentStage]?.steps?.findIndex(step => step.status === 'pending' || step.status === 'in-progress') ?? -1
1248
+ if (pendingIdx === -1) {
1249
+ const wsIdx = progress.stages[currentStage]?.steps?.findIndex(step => step.status === 'waiting') ?? -1
1250
+ if (wsIdx !== -1) {
1251
+ const ws = progress.stages[currentStage].steps[wsIdx]
1252
+ console.log(`⏸️ Step ${wsIdx + 1} 等待用户输入:${ws.name}`)
1253
+ if (ws.waitReason) console.log(` 原因:${ws.waitReason}`)
1254
+ console.log(` 继续:sillyspec run auto --continue --answer "..."`)
1255
+ return
1256
+ }
1257
+ const next = nextInFlow(currentStage)
1258
+ if (next) console.log(`${currentStage} is complete. Run: sillyspec run auto --done --output "${currentStage} complete"`)
1259
+ else console.log('All auto flow stages are complete.')
1260
+ return
1261
+ }
1262
+ // execute 阶段启动前检查审批
1263
+ if (currentStage === 'execute' && !skipApproval) {
1264
+ const approval = await checkApproval(cwd, changeName, platformOpts)
1265
+ if (approval) {
1266
+ if (approval.status === 'rejected') {
1267
+ console.error(`❌ 变更 ${changeName} 的执行已被拒绝:${approval.reason || '无原因'}`)
1268
+ process.exit(1)
1269
+ }
1270
+ if (approval.status === 'pending') {
1271
+ console.log(`⏳ 变更 ${changeName} 的执行审批待处理中...`)
1272
+ console.log(' 提示:使用 --skip-approval 跳过审批检查')
1273
+ }
1274
+ if (approval.status === 'unknown') {
1275
+ console.warn(`⚠️ 变更 ${changeName} 的审批状态未知(${approval.reason || '请求失败'}),按本地模式放行(非审批中,无需等待)`)
1276
+ }
1277
+ }
1278
+ }
1279
+ await outputStep(currentStage, pendingIdx, defSteps, cwd, changeName, progress.project || null, platformOpts)
1280
+ return
1281
+ }
1282
+
1283
+ if (!outputText) {
1284
+ console.error('auto --done requires --output')
1285
+ process.exit(2) // 用法错 → exit 2
1286
+ }
1287
+
1288
+ const result = await completeStep(pm, progress, currentStage, cwd, outputText, inputText, { printNext: false, changeName, platformOpts })
1289
+ if (!result) return
1290
+ progress = pm.read(cwd, changeName)
1291
+
1292
+ const nextPendingIdx = progress.stages[currentStage]?.steps?.findIndex(step => step.status === 'pending' || step.status === 'in-progress') ?? -1
1293
+ if (nextPendingIdx !== -1) {
1294
+ const defSteps = await getAutoSteps(currentStage)
1295
+ // execute 阶段启动前检查审批
1296
+ if (currentStage === 'execute' && !skipApproval) {
1297
+ const approval = await checkApproval(cwd, changeName, platformOpts)
1298
+ if (approval) {
1299
+ if (approval.status === 'rejected') {
1300
+ console.error(`❌ 变更 ${changeName} 的执行已被拒绝:${approval.reason || '无原因'}`)
1301
+ process.exit(1)
1302
+ }
1303
+ if (approval.status === 'pending') {
1304
+ console.log(`⏳ 变更 ${changeName} 的执行审批待处理中...`)
1305
+ console.log(' 提示:使用 --skip-approval 跳过审批检查')
1306
+ }
1307
+ if (approval.status === 'unknown') {
1308
+ console.warn(`⚠️ 变更 ${changeName} 的审批状态未知(${approval.reason || '请求失败'}),按本地模式放行(非审批中,无需等待)`)
1309
+ }
1310
+ }
1311
+ }
1312
+ await outputStep(currentStage, nextPendingIdx, defSteps, cwd, changeName, progress.project || null, platformOpts)
1313
+ return
1314
+ }
1315
+
1316
+ const next = nextInFlow(currentStage)
1317
+ if (!next) {
1318
+ console.log('\nAll auto flow stages are complete.')
1319
+ return
1320
+ }
1321
+
1322
+ // ── next-action.json 驱动:brainstorm → plan 推进判断 ──
1323
+ if (currentStage === 'brainstorm' && next === 'plan') {
1324
+ const changeDir = resolveChangeDir(cwd, progress, platformOpts?.specRoot || null)
1325
+ if (changeDir) {
1326
+ const nextActionFile = join(changeDir, 'next-action.json')
1327
+ try {
1328
+ const nextAction = JSON.parse(readFileSync(nextActionFile, 'utf8'))
1329
+ if (nextAction.has_blocking_questions === true) {
1330
+ console.log(`\n⏸️ brainstorm 有阻塞问题,无法自动进入 plan:`)
1331
+ for (const q of (nextAction.questions || [])) {
1332
+ console.log(` Q-${q.id}: ${q.question}`)
1333
+ if (q.options) console.log(` 选项:${q.options.join(' / ')}`)
1334
+ if (q.recommended) console.log(` 推荐:${q.recommended}`)
1335
+ }
1336
+ console.log(`\n 请回答阻塞问题后继续:sillyspec run auto --done --output "已回答"`)
1337
+ return
1338
+ }
1339
+ console.log(`\n✅ next-action.json: ${nextAction.status},自动进入 plan`)
1340
+ } catch (e) {
1341
+ // next-action.json 不存在或格式错误,继续推进(向后兼容)
1342
+ console.log(`\n⚠️ next-action.json 未找到,继续进入 plan`)
1343
+ }
1344
+ }
1345
+ }
1346
+
1347
+ progress.currentStage = next
1348
+ if (!progress.stages[next]) {
1349
+ progress.stages[next] = { status: 'pending', steps: [], startedAt: null, completedAt: null }
1350
+ }
1351
+ if (progress.stages[next].status === 'pending' || !progress.stages[next].status) {
1352
+ progress.stages[next].status = 'in-progress'
1353
+ progress.stages[next].startedAt = new Date().toLocaleString('zh-CN',{hour12:false})
1354
+ }
1355
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
1356
+ await ensureStageSteps(progress, next, cwd)
1357
+ pm._write(cwd, progress, changeName)
1358
+ triggerSync(cwd, changeName, platformOpts)
1359
+ progress = pm.read(cwd, changeName)
1360
+
1361
+ console.log(`\n${currentStage} complete. Auto advanced to ${next}.`)
1362
+ const nextSteps = await getAutoSteps(next)
1363
+ const firstPending = progress.stages[next]?.steps?.findIndex(step => step.status === 'pending' || step.status === 'in-progress') ?? -1
1364
+ if (firstPending !== -1) {
1365
+ // execute 阶段启动前检查审批
1366
+ if (next === 'execute' && !skipApproval) {
1367
+ const approval = await checkApproval(cwd, changeName, platformOpts)
1368
+ if (approval) {
1369
+ if (approval.status === 'rejected') {
1370
+ console.error(`❌ 变更 ${changeName} 的执行已被拒绝:${approval.reason || '无原因'}`)
1371
+ process.exit(1)
1372
+ }
1373
+ if (approval.status === 'pending') {
1374
+ console.log(`⏳ 变更 ${changeName} 的执行审批待处理中...`)
1375
+ console.log(' 提示:使用 --skip-approval 跳过审批检查')
1376
+ }
1377
+ if (approval.status === 'unknown') {
1378
+ console.warn(`⚠️ 变更 ${changeName} 的审批状态未知(${approval.reason || '请求失败'}),按本地模式放行(非审批中,无需等待)`)
1379
+ }
1380
+ }
1381
+ }
1382
+ await outputStep(next, firstPending, nextSteps, cwd, changeName, progress.project || null, platformOpts)
1383
+ }
1384
+ }
1385
+