sillyspec 3.20.3 → 3.20.5

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 (225) hide show
  1. package/.claude/skills/sillyspec-archive/SKILL.md +21 -17
  2. package/.claude/skills/sillyspec-auto/SKILL.md +83 -77
  3. package/.claude/skills/sillyspec-brainstorm/SKILL.md +44 -17
  4. package/.claude/skills/sillyspec-commit/SKILL.md +106 -105
  5. package/.claude/skills/sillyspec-continue/SKILL.md +45 -44
  6. package/.claude/skills/sillyspec-doctor/SKILL.md +31 -22
  7. package/.claude/skills/sillyspec-execute/SKILL.md +30 -17
  8. package/.claude/skills/sillyspec-explore/SKILL.md +109 -96
  9. package/.claude/skills/sillyspec-knowledge/SKILL.md +270 -0
  10. package/.claude/skills/sillyspec-plan/SKILL.md +21 -52
  11. package/.claude/skills/sillyspec-propose/SKILL.md +21 -17
  12. package/.claude/skills/sillyspec-quick/SKILL.md +21 -17
  13. package/.claude/skills/sillyspec-resume/SKILL.md +68 -111
  14. package/.claude/skills/sillyspec-scan/SKILL.md +21 -17
  15. package/.claude/skills/sillyspec-state/SKILL.md +54 -54
  16. package/.claude/skills/sillyspec-status/SKILL.md +21 -17
  17. package/.claude/skills/sillyspec-verify/SKILL.md +21 -17
  18. package/.claude/skills/sillyspec-workspace/SKILL.md +157 -149
  19. package/.husky/pre-push +13 -0
  20. package/CLAUDE.md +18 -0
  21. package/README.md +198 -186
  22. package/SKILL.md +90 -87
  23. package/bin/sillyspec.js +2 -2
  24. package/docs/brainstorm-plan-contract.md +64 -0
  25. package/docs/plan-execute-contract.md +123 -0
  26. package/docs/platform-scan-protocol.md +298 -0
  27. package/docs/revision-mode.md +115 -0
  28. package/docs/sillyspec/file-lifecycle/known-implementation-gaps.md +99 -0
  29. package/docs/sillyspec/file-lifecycle/platform-workflows-sync.md +218 -0
  30. package/docs/sillyspec/file-lifecycle/stage-artifacts.md +167 -0
  31. package/docs/sillyspec/file-lifecycle/storage-and-state.md +148 -0
  32. package/docs/sillyspec/file-lifecycle/worktree-and-guard.md +211 -0
  33. package/docs/sillyspec/file-lifecycle.md +131 -0
  34. package/docs/workflow-contract-regression.md +106 -0
  35. package/docs/worktree-isolation.md +252 -0
  36. package/package.json +40 -34
  37. package/packages/dashboard/dist/assets/{index-D1EVTLmc.js → index-Bq_Z2hne.js} +7446 -7446
  38. package/packages/dashboard/dist/assets/index-O2W5RV4z.css +1 -0
  39. package/packages/dashboard/dist/index.html +16 -16
  40. package/packages/dashboard/dist/prototype-dashboard.html +836 -0
  41. package/packages/dashboard/dist/prototype-overview.html +256 -0
  42. package/packages/dashboard/index.html +15 -15
  43. package/packages/dashboard/package-lock.json +2384 -2384
  44. package/packages/dashboard/package.json +25 -25
  45. package/packages/dashboard/public/prototype-dashboard.html +836 -0
  46. package/packages/dashboard/public/prototype-overview.html +256 -0
  47. package/packages/dashboard/server/executor.js +86 -86
  48. package/packages/dashboard/server/index.js +588 -508
  49. package/packages/dashboard/server/parser.js +526 -458
  50. package/packages/dashboard/server/watcher.js +350 -342
  51. package/packages/dashboard/src/App.vue +558 -325
  52. package/packages/dashboard/src/components/ActionBar.vue +93 -84
  53. package/packages/dashboard/src/components/CommandPalette.vue +96 -92
  54. package/packages/dashboard/src/components/DetailPanel.vue +137 -137
  55. package/packages/dashboard/src/components/DocPreview.vue +105 -8
  56. package/packages/dashboard/src/components/DocTree.vue +75 -19
  57. package/packages/dashboard/src/components/HResizeHandle.vue +48 -0
  58. package/packages/dashboard/src/components/LogStream.vue +65 -65
  59. package/packages/dashboard/src/components/PipelineStage.vue +95 -75
  60. package/packages/dashboard/src/components/PipelineView.vue +156 -129
  61. package/packages/dashboard/src/components/ProjectCard.vue +187 -0
  62. package/packages/dashboard/src/components/ProjectList.vue +210 -210
  63. package/packages/dashboard/src/components/ProjectOverview.vue +113 -139
  64. package/packages/dashboard/src/components/StageBadge.vue +67 -53
  65. package/packages/dashboard/src/components/StepCard.vue +94 -89
  66. package/packages/dashboard/src/components/VResizeHandle.vue +61 -0
  67. package/packages/dashboard/src/components/detail/DocsDetail.vue +48 -48
  68. package/packages/dashboard/src/components/detail/GitDetail.vue +61 -61
  69. package/packages/dashboard/src/components/detail/TechDetail.vue +43 -43
  70. package/packages/dashboard/src/composables/useDashboard.js +192 -164
  71. package/packages/dashboard/src/composables/useKeyboard.js +119 -119
  72. package/packages/dashboard/src/composables/useLayout.js +131 -0
  73. package/packages/dashboard/src/composables/useWebSocket.js +129 -129
  74. package/packages/dashboard/src/main.js +8 -8
  75. package/packages/dashboard/src/style.css +132 -132
  76. package/packages/dashboard/vite.config.js +18 -18
  77. package/src/brainstorm-postcheck.js +158 -0
  78. package/src/change-list.js +52 -0
  79. package/src/change-risk-profile.js +352 -0
  80. package/src/classify-change.js +73 -0
  81. package/src/constants.js +70 -0
  82. package/src/contract-matrix.js +278 -0
  83. package/src/db.js +201 -0
  84. package/src/endpoint-extractor.js +315 -0
  85. package/src/hooks/claude-pre-tool-use.cjs +125 -0
  86. package/src/hooks/worktree-guard.js +761 -0
  87. package/src/index.js +922 -252
  88. package/src/init.js +470 -375
  89. package/src/knowledge-match.js +130 -0
  90. package/src/migrate.js +117 -117
  91. package/src/modules.js +482 -0
  92. package/src/progress.js +1734 -508
  93. package/src/run.js +3465 -652
  94. package/src/scan-postcheck.js +387 -0
  95. package/src/setup.js +398 -460
  96. package/src/stage-contract.js +700 -0
  97. package/src/stages/archive.js +160 -54
  98. package/src/stages/brainstorm-auto.js +229 -0
  99. package/src/stages/brainstorm.js +645 -239
  100. package/src/stages/doctor.js +365 -312
  101. package/src/stages/execute.js +634 -264
  102. package/src/stages/explore.js +34 -0
  103. package/src/stages/index.js +29 -35
  104. package/src/stages/knowledge.js +498 -0
  105. package/src/stages/plan-postcheck.js +518 -0
  106. package/src/stages/plan.js +582 -279
  107. package/src/stages/propose.js +174 -115
  108. package/src/stages/quick.js +102 -63
  109. package/src/stages/scan.js +558 -141
  110. package/src/stages/status.js +65 -65
  111. package/src/stages/verify.js +322 -135
  112. package/src/sync.js +497 -0
  113. package/src/task-review.js +346 -0
  114. package/src/workflow.js +785 -0
  115. package/src/worktree-apply.js +549 -0
  116. package/src/worktree-deps.js +185 -0
  117. package/src/worktree.js +982 -0
  118. package/templates/workflows/archive-impact.yaml +79 -0
  119. package/templates/workflows/scan-docs.yaml +132 -0
  120. package/test/brainstorm-plan-contract.test.mjs +273 -0
  121. package/test/check-syntax.mjs +26 -0
  122. package/test/cli-top-level-aliases.test.mjs +174 -0
  123. package/test/contract-artifacts.test.mjs +323 -0
  124. package/test/decision-supersede.test.mjs +277 -0
  125. package/test/knowledge-match.test.mjs +231 -0
  126. package/test/plan-execute-contract.test.mjs +357 -0
  127. package/test/plan-optimization.test.mjs +572 -0
  128. package/test/platform-artifacts.test.mjs +190 -0
  129. package/test/platform-failure-samples.test.mjs +199 -0
  130. package/test/platform-recovery-chain.test.mjs +179 -0
  131. package/test/platform-recovery.test.mjs +167 -0
  132. package/test/platform-scan-p0.test.mjs +175 -0
  133. package/test/revision-v1.test.mjs +1145 -0
  134. package/test/run-sanitize-project-name.test.mjs +51 -0
  135. package/test/run-scan-postcheck-fail.test.mjs +64 -0
  136. package/test/run-scan-project-parse.test.mjs +200 -0
  137. package/test/run-tests.mjs +48 -0
  138. package/test/runtime-cleanup-keeps-worktree.test.mjs +107 -0
  139. package/test/scan-docs-yaml-placeholders.test.mjs +84 -0
  140. package/test/scan-knowledge.test.mjs +175 -0
  141. package/test/scan-paths.test.mjs +68 -0
  142. package/test/scan-postcheck-project-priority.test.mjs +85 -0
  143. package/test/scan-postcheck.test.mjs +197 -0
  144. package/test/scan-workflow-anyfailed-block.test.mjs +52 -0
  145. package/test/spec-dir.test.mjs +206 -0
  146. package/test/stage-contract-failed-post-check.test.mjs +102 -0
  147. package/test/stage-contract.test.mjs +299 -0
  148. package/test/stage-definitions.test.mjs +39 -0
  149. package/test/wait-gates.test.mjs +501 -0
  150. package/test/workflow-spec-base.test.mjs +142 -0
  151. package/test/worktree-deps-provision.test.mjs +148 -0
  152. package/test/worktree-guard.test.mjs +136 -0
  153. package/test/worktree-native-overlay.test.mjs +188 -0
  154. package/.sillyspec/changes/archive/2026-04-08-derive-state/design.md +0 -97
  155. package/.sillyspec/changes/archive/2026-04-08-derive-state/plan.md +0 -51
  156. package/.sillyspec/changes/archive/2026-04-08-derive-state/proposal.md +0 -29
  157. package/.sillyspec/changes/archive/2026-04-08-derive-state/requirements.md +0 -34
  158. package/.sillyspec/changes/archive/2026-04-08-derive-state/tasks.md +0 -13
  159. package/.sillyspec/changes/archive/2026-04-08-derive-state/verify-result.md +0 -43
  160. package/.sillyspec/changes/auto-mode/design.md +0 -50
  161. package/.sillyspec/changes/auto-mode/proposal.md +0 -19
  162. package/.sillyspec/changes/auto-mode/requirements.md +0 -21
  163. package/.sillyspec/changes/auto-mode/tasks.md +0 -7
  164. package/.sillyspec/changes/brainstorm-archive/2026-04-05-dashboard-design.md +0 -206
  165. package/.sillyspec/changes/brainstorm-archive/2026-04-05-unified-docs-design.md +0 -199
  166. package/.sillyspec/changes/dashboard/design.md +0 -219
  167. package/.sillyspec/changes/dashboard/design.md.braindraft +0 -206
  168. package/.sillyspec/changes/run-command-design/design.md +0 -1230
  169. package/.sillyspec/changes/unified-docs-design/design.md +0 -199
  170. package/.sillyspec/docs/sillyspec/scan/.gitkeep +0 -0
  171. package/.sillyspec/knowledge/INDEX.md +0 -8
  172. package/.sillyspec/knowledge/uncategorized.md +0 -3
  173. package/.sillyspec/plans/2026-04-05-dashboard.md +0 -737
  174. package/.sillyspec/projects/sillyspec.yaml +0 -3
  175. package/dist/steps/brainstorm/01-load-context.md +0 -30
  176. package/dist/steps/brainstorm/02-reuse-check.md +0 -6
  177. package/dist/steps/brainstorm/03-prototype-analysis.md +0 -11
  178. package/dist/steps/brainstorm/04-module-split.md +0 -23
  179. package/dist/steps/brainstorm/05-dialog-explore.md +0 -8
  180. package/dist/steps/brainstorm/06-propose-approaches.md +0 -3
  181. package/dist/steps/brainstorm/07-present-design.md +0 -3
  182. package/dist/steps/brainstorm/08-write-design.md +0 -21
  183. package/dist/steps/brainstorm/09-self-review.md +0 -15
  184. package/dist/steps/brainstorm/10-user-confirm.md +0 -3
  185. package/dist/steps/brainstorm/11-output-spec.md +0 -7
  186. package/dist/steps/brainstorm/manifest.yaml +0 -26
  187. package/dist/steps/execute/01-load-context.md +0 -41
  188. package/dist/steps/execute/02-scan-conventions.md +0 -47
  189. package/dist/steps/execute/03-skill-mcp.md +0 -19
  190. package/dist/steps/execute/04-assign-task.md +0 -22
  191. package/dist/steps/execute/04b-prompt-template.md +0 -54
  192. package/dist/steps/execute/05-write-test.md +0 -7
  193. package/dist/steps/execute/06-write-code.md +0 -8
  194. package/dist/steps/execute/07-run-test.md +0 -26
  195. package/dist/steps/execute/08-fix-issues.md +0 -28
  196. package/dist/steps/execute/09-next-task.md +0 -33
  197. package/dist/steps/execute/manifest.yaml +0 -28
  198. package/dist/steps/plan/01-load-context.md +0 -22
  199. package/dist/steps/plan/02-anchor-confirm.md +0 -1
  200. package/dist/steps/plan/03-expand-tasks.md +0 -33
  201. package/dist/steps/plan/04-mark-order.md +0 -15
  202. package/dist/steps/plan/05-e2e-planning.md +0 -17
  203. package/dist/steps/plan/06-self-check.md +0 -16
  204. package/dist/steps/plan/07-save.md +0 -1
  205. package/dist/steps/plan/manifest.yaml +0 -18
  206. package/dist/steps/scan/01-env-detect.md +0 -51
  207. package/dist/steps/scan/02-tech-stack.md +0 -16
  208. package/dist/steps/scan/03-conventions.md +0 -16
  209. package/dist/steps/scan/04-structure.md +0 -19
  210. package/dist/steps/scan/05-quality.md +0 -18
  211. package/dist/steps/scan/06-complete.md +0 -49
  212. package/dist/steps/scan/manifest.yaml +0 -16
  213. package/dist/steps/verify/01-load-specs.md +0 -28
  214. package/dist/steps/verify/02-check-tasks.md +0 -1
  215. package/dist/steps/verify/03-check-design.md +0 -6
  216. package/dist/steps/verify/04-run-tests.md +0 -7
  217. package/dist/steps/verify/05-e2e-tests.md +0 -27
  218. package/dist/steps/verify/05b-e2e-fix.md +0 -33
  219. package/dist/steps/verify/06-code-quality.md +0 -25
  220. package/dist/steps/verify/07-lint-check.md +0 -27
  221. package/dist/steps/verify/08-output-report.md +0 -14
  222. package/dist/steps/verify/manifest.yaml +0 -22
  223. package/packages/dashboard/dist/assets/index-DGe8CqeP.css +0 -1
  224. package/src/derive.js +0 -147
  225. package/src/step.js +0 -543
package/src/init.js CHANGED
@@ -1,375 +1,470 @@
1
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, statSync } from 'fs';
2
- import { join, resolve, dirname, basename } from 'path';
3
- import { fileURLToPath } from 'url';
4
- import { homedir } from 'os';
5
- import { checkbox, confirm, input } from '@inquirer/prompts';
6
- import { ProgressManager } from './progress.js';
7
- import chalk from 'chalk';
8
-
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = dirname(__filename);
11
-
12
- // ── 递归复制目录 ──
13
- function copyDirSync(src, dst) {
14
- mkdirSync(dst, { recursive: true });
15
- for (const entry of readdirSync(src, { withFileTypes: true })) {
16
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
17
- const srcPath = join(src, entry.name);
18
- const dstPath = join(dst, entry.name);
19
- if (entry.isDirectory()) {
20
- copyDirSync(srcPath, dstPath);
21
- } else if (entry.name.endsWith('.md')) {
22
- writeFileSync(dstPath, readFileSync(srcPath));
23
- }
24
- }
25
- }
26
-
27
- // ── 元数据映射 ──
28
-
29
-
30
-
31
- const VALID_TOOLS = ['claude', 'claude_skills', 'cursor', 'openclaw', 'codex', 'gemini', 'opencode'];
32
-
33
- const TOOL_LABELS = {
34
- claude: 'Claude Code',
35
- claude_skills: 'Claude Skills',
36
- cursor: 'Cursor',
37
- openclaw: 'OpenClaw',
38
- codex: 'OpenAI Codex (通过 AGENTS.md)',
39
- gemini: 'Gemini CLI (通过 GEMINI.md)',
40
- opencode: 'OpenCode (通过 INSTRUCTIONS.md)',
41
- };
42
-
43
- const INSTRUCTION_TOOLS = ['codex', 'gemini', 'opencode'];
44
-
45
- const INSTRUCTION_FILE_MAP = {
46
- codex: 'AGENTS.md',
47
- gemini: 'GEMINI.md',
48
- opencode: 'INSTRUCTIONS.md',
49
- };
50
-
51
- const INJECTION_CONTENT = `## SillySpec — 规范驱动开发
52
-
53
- 在执行开发任务时,遵循以下规范:
54
-
55
- ### 代码规范
56
- - 写代码前先读取 \`.sillyspec/docs/<project>/scan/CONVENTIONS.md\`(代码风格)和 \`.sillyspec/docs/<project>/scan/ARCHITECTURE.md\`(架构)
57
- - 调用已有方法前,用 grep 确认方法存在,不许编造
58
- - 遵循 \`.sillyspec/docs/<project>/scan/CONVENTIONS.md\` 中的代码风格
59
-
60
- ### 工作流程
61
- - 读取 \`.sillyspec/.runtime/progress.json\` 确认当前阶段(使用 \`sillyspec progress show\`)
62
- - 各阶段产出文件位于 \`.sillyspec/changes/<变更名>/\`
63
- `;
64
-
65
- // ── 注入指令文件 ──
66
-
67
- function injectInstructions(tool, projectDir) {
68
- const fileName = INSTRUCTION_FILE_MAP[tool];
69
- if (!fileName) return;
70
- const filePath = join(projectDir, fileName);
71
-
72
- // 文件不存在则创建
73
- if (!existsSync(filePath)) {
74
- writeFileSync(filePath, INJECTION_CONTENT);
75
- return;
76
- }
77
-
78
- // 已存在 SillySpec 标记则跳过
79
- const content = readFileSync(filePath, 'utf8');
80
- if (content.includes('## SillySpec')) return;
81
-
82
- // 追加到末尾
83
- writeFileSync(filePath, content.trimEnd() + '\n\n' + INJECTION_CONTENT);
84
- }
85
-
86
- // ── 检测工具 ──
87
-
88
- function detectTools(projectDir) {
89
- const found = [];
90
- if (existsSync(join(projectDir, '.claude'))) found.push('claude');
91
- if (existsSync(join(projectDir, '.claude', 'skills'))) found.push('claude_skills');
92
- if (existsSync(join(projectDir, '.cursor'))) found.push('cursor');
93
- if (existsSync(join(projectDir, '.openclaw'))) found.push('openclaw');
94
- if (existsSync(join(projectDir, 'AGENTS.md'))) found.push('codex');
95
- if (existsSync(join(projectDir, 'GEMINI.md'))) found.push('gemini');
96
- if (existsSync(join(projectDir, 'INSTRUCTIONS.md'))) found.push('opencode');
97
- if (found.length === 0) found.push('claude');
98
- return found;
99
- }
100
-
101
- // ── TTY 工具函数 ──
102
-
103
- function isTTY() {
104
- return process.stdin.isTTY && process.stdout.isTTY;
105
- }
106
-
107
- // ── 核心安装逻辑 ──
108
-
109
- async function doInstall(projectDir, tools, subprojects = []) {
110
- // 创建基础目录
111
- // .sillyspec/projects/ → 项目注册表
112
- // .sillyspec/docs/<name>/ → 统一文档中心
113
- // .sillyspec/knowledge/ → 跨项目共享知识库
114
- // .sillyspec/.runtime/ progress (gitignored)
115
-
116
- // 注册当前项目到 projects/
117
- const projectName = basename(projectDir) || 'project';
118
- const projectsDir = join(projectDir, '.sillyspec', 'projects');
119
- mkdirSync(projectsDir, { recursive: true });
120
- const projectYamlPath = join(projectsDir, `${projectName}.yaml`);
121
- if (!existsSync(projectYamlPath)) {
122
- writeFileSync(projectYamlPath, `name: ${projectName}\npath: .\nstatus: active\n`);
123
- }
124
-
125
- // 创建 docs/<projectName>/scan/ 子目录(代码扫描结果)
126
- const scanDir = join(projectDir, '.sillyspec', 'docs', projectName, 'scan');
127
- mkdirSync(scanDir, { recursive: true });
128
- const gitkeepPath = join(scanDir, '.gitkeep');
129
- if (!existsSync(gitkeepPath)) writeFileSync(gitkeepPath, '');
130
-
131
- // 创建 shared/workspace 目录
132
- mkdirSync(join(projectDir, '.sillyspec', 'shared'), { recursive: true });
133
- mkdirSync(join(projectDir, '.sillyspec', 'workspace'), { recursive: true });
134
-
135
- // 创建知识库骨架
136
- const knowledgeDir = join(projectDir, '.sillyspec', 'knowledge');
137
- mkdirSync(knowledgeDir, { recursive: true });
138
- const indexPath = join(knowledgeDir, 'INDEX.md');
139
- if (!existsSync(indexPath)) {
140
- writeFileSync(indexPath, `# Knowledge Index\n\n> 子代理任务开始前查询此文件,按关键词匹配,只读命中的知识文件。\n> execute/quick 执行中发现的坑自动追加到 uncategorized.md,经用户确认后归类到对应文件。\n\n<!-- 格式:关键词1|关键词2|关键词3 → 文件路径 -->\n<!-- 示例:mybatis-plus|分页|Page → pagination.md -->\n<!-- 示例:跨域|CORS|preflight → cors.md -->\n`);
141
- }
142
- const uncatPath = join(knowledgeDir, 'uncategorized.md');
143
- if (!existsSync(uncatPath)) {
144
- writeFileSync(uncatPath, `# 未分类知识\n\n> execute/quick 执行中发现的坑暂存于此,用户审阅后归类到对应文件并更新 INDEX.md。\n`);
145
- }
146
-
147
- // 创建 .sillyspec/.runtime/ 目录结构
148
- const runtimeDir = join(projectDir, '.sillyspec', '.runtime');
149
- for (const sub of ['artifacts', 'history', 'logs', 'templates']) {
150
- mkdirSync(join(runtimeDir, sub), { recursive: true });
151
- }
152
-
153
- // 创建初始 progress.json
154
- const progressPath = join(runtimeDir, 'progress.json');
155
- if (!existsSync(progressPath)) {
156
- const pm = new ProgressManager();
157
- pm.init(projectDir);
158
- }
159
-
160
- // 创建初始 user-inputs.md
161
- const inputsPath = join(runtimeDir, 'user-inputs.md');
162
- if (!existsSync(inputsPath)) {
163
- writeFileSync(inputsPath, '# 用户输入记录\n\n> 每步完成时由 AI 自动追加,记录用户所有原话。\n\n');
164
- }
165
-
166
- const gitignorePath = join(projectDir, '.gitignore');
167
- const ignoreRules = ['.sillyspec/codebase/SCAN-RAW.md', '.sillyspec/local.yaml', '.sillyspec/.runtime/'];
168
- if (existsSync(gitignorePath)) {
169
- const content = readFileSync(gitignorePath, 'utf8');
170
- let updated = content.trimEnd();
171
- for (const rule of ignoreRules) {
172
- if (!updated.includes(rule)) {
173
- updated += '\n' + rule;
174
- }
175
- }
176
- writeFileSync(gitignorePath, updated + '\n');
177
- } else {
178
- writeFileSync(gitignorePath, ignoreRules.join('\n') + '\n');
179
- }
180
-
181
- // 注入指令文件(codex/gemini/opencode)
182
- for (let i = 0; i < tools.length; i++) {
183
- const toolName = tools[i];
184
- if (INSTRUCTION_TOOLS.includes(toolName)) {
185
- injectInstructions(toolName, projectDir);
186
- }
187
- }
188
-
189
- // 复制 skills 到 .claude/skills/(给 Claude Code 使用)
190
- const claudeSkillsDir = join(projectDir, '.claude', 'skills');
191
- // 优先从 npm 包自带位置复制,其次从 ~/.agents/skills/
192
- const npmSkillsDir = join(__dirname, '..', '.claude', 'skills');
193
- const localSkillsDir = join(homedir(), '.agents', 'skills');
194
- const skillsSource = existsSync(npmSkillsDir) ? npmSkillsDir : existsSync(localSkillsDir) ? localSkillsDir : null;
195
- if (skillsSource) {
196
- const sillyspecSkills = readdirSync(skillsSource).filter(f => f.startsWith('sillyspec-') && statSync(join(skillsSource, f)).isDirectory());
197
- if (sillyspecSkills.length > 0) {
198
- mkdirSync(claudeSkillsDir, { recursive: true });
199
- for (const skill of sillyspecSkills) {
200
- copyDirSync(join(skillsSource, skill), join(claudeSkillsDir, skill));
201
- }
202
- console.log(chalk.green(' ✓ Claude Code skills 已同步 (' + sillyspecSkills.length + ' 个)'));
203
- }
204
- } else {
205
- console.log(chalk.yellow(' ⚠ 未找到 skills 目录,跳过 Claude Code skills 同步'));
206
- }
207
- }
208
-
209
- // ── 安装完成总结 ──
210
-
211
- function showSummary(version, tools) {
212
- const toolLabels = tools.map(t => TOOL_LABELS[t] || t);
213
-
214
- console.log('');
215
- console.log(chalk.green(' ═══════════════════════════════════════'));
216
- console.log(chalk.green(` ✅ SillySpec v${version} 安装完成!`));
217
- console.log(chalk.green(' ═══════════════════════════════════════'));
218
- console.log('');
219
- console.log(` 已安装工具: ${chalk.cyan(toolLabels.join(', '))}`);
220
- console.log(' 📁 .sillyspec/ — 项目规范目录');
221
- console.log('');
222
- console.log(' 下一步:使用 AI 技能开始工作');
223
- console.log(' OpenClaw: ' + chalk.bold('/sillyspec:brainstorm'));
224
- console.log(' Claude Code: ' + chalk.bold('/sillyspec:brainstorm'));
225
- console.log('');
226
- console.log(chalk.dim(' 💡 推荐安装 MCP 工具增强 AI 能力:sillyspec setup'));
227
- console.log('');
228
- }
229
-
230
- // ── 读取版本号 ──
231
-
232
- export function getVersion() {
233
- try {
234
- const pkg = JSON.parse(readFileSync(resolve(__dirname, '..', 'package.json'), 'utf8'));
235
- return pkg.version;
236
- } catch {
237
- return '?.?.?';
238
- }
239
- }
240
-
241
- // ── 主命令 ──
242
-
243
- export async function cmdInit(projectDir, options = {}) {
244
- const { tool, interactive } = options;
245
- const version = getVersion();
246
-
247
- // ── 交互式模式(--interactive 或 -i)──
248
- if (interactive && isTTY()) {
249
- // 欢迎画面
250
- console.log('');
251
- console.log(chalk.cyan('🤪 SillySpec v' + version + ' — 规范驱动开发'));
252
- console.log(chalk.cyan(' ===================================='));
253
- console.log('');
254
- console.log(' 让 AI 像高级工程师一样工作:');
255
- console.log(' 先思考、先规划、先验证,再写代码。');
256
- console.log('');
257
- console.log(chalk.gray(' 支持的 AI 工具:'));
258
- console.log(chalk.gray(' Claude Code · Claude Skills · Cursor · Codex CLI · OpenCode · OpenClaw'));
259
- console.log('');
260
-
261
- // 工具多选
262
- const detected = detectTools(projectDir);
263
-
264
- const toolChoices = VALID_TOOLS.map(v => ({
265
- name: `${TOOL_LABELS[v]}${v === 'claude' ? ' (推荐)' : ''}`,
266
- value: v,
267
- checked: detected.includes(v),
268
- }));
269
-
270
- const selectedTools = await checkbox({
271
- message: '选择要安装的 AI 工具(空格选择,回车确认)',
272
- choices: toolChoices,
273
- validate: (answer) => answer.length > 0 || '至少选择一个工具',
274
- });
275
-
276
- // 子项目引导(始终执行)
277
- let subprojects = [];
278
- {
279
- console.log('');
280
- console.log(chalk.yellow('📋 添加子项目'));
281
- console.log(chalk.dim(' 子项目是工作区中的独立项目目录(如 frontend/、backend/)'));
282
- console.log('');
283
-
284
- const addMore = await confirm({ message: '现在添加子项目?', default: true });
285
- if (addMore) {
286
- let suggestions = [];
287
- try {
288
- const entries = readdirSync(projectDir, { withFileTypes: true });
289
- suggestions = entries
290
- .filter(e => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')
291
- .map(e => e.name)
292
- .sort();
293
- } catch {}
294
-
295
- if (suggestions.length > 0) {
296
- console.log('');
297
- console.log(chalk.dim(` 检测到以下目录:${suggestions.join(', ')}`));
298
- console.log('');
299
- }
300
-
301
- let adding = true;
302
- while (adding) {
303
- const name = await input({
304
- message: '子项目名称(如 frontend,留空结束)',
305
- default: suggestions.find(s => !subprojects.find(p => p.name === s)) || '',
306
- });
307
-
308
- if (!name.trim()) {
309
- adding = false;
310
- break;
311
- }
312
-
313
- const pathHint = suggestions.includes(name.trim()) ? `./${name.trim()}` : '';
314
- const subPath = await input({
315
- message: '子项目目录路径',
316
- default: pathHint,
317
- });
318
-
319
- const role = await input({
320
- message: '子项目描述(如 前端 - Vue3 + TypeScript)',
321
- default: '',
322
- });
323
-
324
- let repo = '';
325
- try {
326
- const { execSync } = await import('child_process');
327
- const absPath = resolve(projectDir, subPath.trim() || `./${name.trim()}`);
328
- repo = execSync('git remote get-url origin', { cwd: absPath, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
329
- } catch {}
330
-
331
- subprojects.push({ name: name.trim(), path: subPath.trim() || `./${name.trim()}`, role: role.trim(), repo });
332
-
333
- const idx = suggestions.indexOf(name.trim());
334
- if (idx >= 0) suggestions.splice(idx, 1);
335
-
336
- const again = await confirm({ message: '继续添加子项目?', default: subprojects.length < suggestions.length });
337
- if (!again) adding = false;
338
- }
339
- }
340
- }
341
-
342
- console.log('');
343
- await doInstall(projectDir, selectedTools, subprojects);
344
- showSummary(version, selectedTools);
345
- return;
346
- }
347
-
348
- // ── 默认快速模式:检测 → 安装 → 结束 ──
349
-
350
- let tools = [];
351
- if (tool) {
352
- if (!VALID_TOOLS.includes(tool)) {
353
- console.error(`❌ 未知工具: ${tool}`);
354
- console.error(`支持的工具: ${VALID_TOOLS.join(', ')}`);
355
- process.exit(1);
356
- }
357
- tools = [tool];
358
- } else {
359
- tools = detectTools(projectDir);
360
- }
361
-
362
- await doInstall(projectDir, tools);
363
-
364
- console.log('');
365
- console.log(chalk.green(` ✅ SillySpec v${version} 安装完成!`));
366
- console.log('');
367
- console.log(' 📁 .sillyspec/ 项目规范目录');
368
- console.log('');
369
- console.log(' 下一步:使用 AI 技能开始工作');
370
- console.log(` OpenClaw: ${chalk.bold('/sillyspec:brainstorm')}`);
371
- console.log(` Claude Code: ${chalk.bold('/sillyspec:brainstorm')}`);
372
- console.log('');
373
- console.log(chalk.dim(' 💡 增强能力:sillyspec setup(安装 MCP 工具)'));
374
- console.log('');
375
- }
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
2
+ import { join, resolve, dirname, basename } from 'path';
3
+ import { fileURLToPath } from 'url';
4
+ import { checkbox, confirm, input } from '@inquirer/prompts';
5
+ import { ProgressManager } from './progress.js';
6
+ import chalk from 'chalk';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ // ── .runtime/ 残留清理(平台模式防源码污染) ──
12
+ // 平台模式(specRoot 指向外部)下,源码目录的 .sillyspec/.runtime/ 是旧残留,
13
+ // 应让 specRoot 成为唯一运行时根。但若源码目录的 .sillyspec/ 本身就是该项目
14
+ // specDir(含真实资产),其 .runtime/ 里的 worktrees/、sillyspec.db、
15
+ // global.json、gate-status.json 是真实工作状态,整删会摧毁 worktree meta、
16
+ // 导致 depsStatus 恒为 unknown、branch already exists 死循环。
17
+ // 详见 docs/sillyspec/runtime-cleanup-destroys-worktree-meta.md
18
+ //
19
+ // 策略:白名单保留权威状态,逐项删除可重建的缓存子项;未知子项默认保留(安全侧倾斜)。
20
+ const RUNTIME_KEEP = new Set([
21
+ 'worktrees', // worktree 目录 + meta.json(worktree.js:17)
22
+ 'sillyspec.db', // SQLite 进度库(权威状态源,progress.js:7)
23
+ 'global.json', // 项目名/活跃变更缓存(progress.js:8)
24
+ 'gate-status.json', // worktree-guard 门禁状态(progress.js:9)
25
+ 'contract-artifacts', // execute endpoint 契约(verify 阶段读取)
26
+ 'execute-runs', // task review 结果(task-review.js)
27
+ ]);
28
+
29
+ /**
30
+ * 清理 .sillyspec/ 下的运行时残留,保留权威状态。
31
+ * 同时清理 local.yaml、codebase/(这些非权威,整删安全)。
32
+ * @param {string} legacyDir - 源码目录的 .sillyspec/ 路径
33
+ */
34
+ export function cleanupRuntimeResidue(legacyDir) {
35
+ // local.yaml、codebase/ 非权威,整删
36
+ for (const residue of ['local.yaml', 'codebase']) {
37
+ const p = join(legacyDir, residue);
38
+ if (existsSync(p)) { try { rmSync(p, { recursive: true, force: true }) } catch {} }
39
+ }
40
+ // .runtime/ 逐项清理,白名单保留
41
+ const runtimeDir = join(legacyDir, '.runtime');
42
+ if (existsSync(runtimeDir)) {
43
+ let entries = [];
44
+ try { entries = readdirSync(runtimeDir, { withFileTypes: true }); } catch {}
45
+ for (const entry of entries) {
46
+ if (RUNTIME_KEEP.has(entry.name)) continue;
47
+ const p = join(runtimeDir, entry.name);
48
+ try { rmSync(p, { recursive: true, force: true }) } catch {}
49
+ }
50
+ }
51
+ }
52
+
53
+ // ── 递归复制目录 ──
54
+ function copyDirSync(src, dst) {
55
+ mkdirSync(dst, { recursive: true });
56
+ for (const entry of readdirSync(src, { withFileTypes: true })) {
57
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
58
+ const srcPath = join(src, entry.name);
59
+ const dstPath = join(dst, entry.name);
60
+ if (entry.isDirectory()) {
61
+ copyDirSync(srcPath, dstPath);
62
+ } else if (entry.name.endsWith('.md')) {
63
+ writeFileSync(dstPath, readFileSync(srcPath));
64
+ }
65
+ }
66
+ }
67
+
68
+ // ── 元数据映射 ──
69
+
70
+
71
+
72
+ const VALID_TOOLS = ['claude', 'cursor', 'openclaw', 'codex', 'gemini', 'opencode'];
73
+
74
+ const TOOL_LABELS = {
75
+ claude: 'Claude Code',
76
+ cursor: 'Cursor',
77
+ openclaw: 'OpenClaw',
78
+ codex: 'OpenAI Codex (通过 AGENTS.md)',
79
+ gemini: 'Gemini CLI (通过 GEMINI.md)',
80
+ opencode: 'OpenCode (通过 INSTRUCTIONS.md)',
81
+ };
82
+
83
+ const INSTRUCTION_TOOLS = ['codex', 'gemini', 'opencode'];
84
+
85
+ const INSTRUCTION_FILE_MAP = {
86
+ codex: 'AGENTS.md',
87
+ gemini: 'GEMINI.md',
88
+ opencode: 'INSTRUCTIONS.md',
89
+ };
90
+
91
+ const INJECTION_CONTENT = `## SillySpec — 规范驱动开发
92
+
93
+ 在执行开发任务时,遵循以下规范:
94
+
95
+ ### 代码规范
96
+ - 写代码前先读取 \`.sillyspec/docs/<project>/scan/CONVENTIONS.md\`(代码风格)和 \`.sillyspec/docs/<project>/scan/ARCHITECTURE.md\`(架构)
97
+ - 调用已有方法前,用 grep 确认方法存在,不许编造
98
+ - 遵循 \`.sillyspec/docs/<project>/scan/CONVENTIONS.md\` 中的代码风格
99
+
100
+ ### 工作流程
101
+ - 读取 sillyspec.db 确认当前阶段(使用 \`sillyspec progress show\`)
102
+ - 各阶段产出文件位于 \`.sillyspec/changes/<变更名>/\` 下
103
+ `;
104
+
105
+ // ── 注入指令文件 ──
106
+
107
+ function injectInstructions(tool, projectDir) {
108
+ const fileName = INSTRUCTION_FILE_MAP[tool];
109
+ if (!fileName) return;
110
+ const filePath = join(projectDir, fileName);
111
+
112
+ // 文件不存在则创建
113
+ if (!existsSync(filePath)) {
114
+ writeFileSync(filePath, INJECTION_CONTENT);
115
+ return;
116
+ }
117
+
118
+ // 已存在 SillySpec 标记则跳过
119
+ const content = readFileSync(filePath, 'utf8');
120
+ if (content.includes('## SillySpec')) return;
121
+
122
+ // 追加到末尾
123
+ writeFileSync(filePath, content.trimEnd() + '\n\n' + INJECTION_CONTENT);
124
+ }
125
+
126
+ // ── 检测工具 ──
127
+
128
+ function detectTools(projectDir) {
129
+ const found = [];
130
+ if (existsSync(join(projectDir, '.claude'))) found.push('claude');
131
+ if (existsSync(join(projectDir, '.cursor'))) found.push('cursor');
132
+ if (existsSync(join(projectDir, '.openclaw'))) found.push('openclaw');
133
+ if (existsSync(join(projectDir, 'AGENTS.md'))) found.push('codex');
134
+ if (existsSync(join(projectDir, 'GEMINI.md'))) found.push('gemini');
135
+ if (existsSync(join(projectDir, 'INSTRUCTIONS.md'))) found.push('opencode');
136
+ if (found.length === 0) found.push('claude');
137
+ return found;
138
+ }
139
+
140
+ // ── TTY 工具函数 ──
141
+
142
+ function isTTY() {
143
+ return process.stdin.isTTY && process.stdout.isTTY;
144
+ }
145
+
146
+ // ── 核心安装逻辑 ──
147
+
148
+ async function doInstall(projectDir, tools, subprojects = [], specDir = null) {
149
+ // specDir: 规范目录(默认 projectDir/.sillyspec)
150
+ // projectDir: 源码项目根目录(用于工具检测、指令注入、.gitignore)
151
+ const spec = specDir || join(projectDir, '.sillyspec');
152
+
153
+ // 外部 specDir 时清理旧版本残留的 cwd/.sillyspec/(防止源码污染)。
154
+ // ⚠️ 必须保护真实资产:若本地 .sillyspec 含 changes/(非空)、projects/(非空)
155
+ // sillyspec.db(进度库),说明该项目本身就用 SillySpec 管理,整体删除会丢资产。
156
+ // 此时只清运行时残留,拒绝整删;确无资产时才视为旧残留清理。
157
+ const legacyDir = join(projectDir, '.sillyspec');
158
+ if (specDir && existsSync(legacyDir)) {
159
+ let hasChanges = false;
160
+ try {
161
+ const changesDir = join(legacyDir, 'changes');
162
+ if (existsSync(changesDir)) hasChanges = readdirSync(changesDir).length > 0;
163
+ } catch {}
164
+ let hasProjects = false;
165
+ try {
166
+ const projectsDir = join(legacyDir, 'projects');
167
+ if (existsSync(projectsDir)) hasProjects = readdirSync(projectsDir).length > 0;
168
+ } catch {}
169
+ const hasDb = existsSync(join(legacyDir, 'sillyspec.db'));
170
+
171
+ if (hasChanges || hasProjects || hasDb) {
172
+ // 真实资产存在:拒绝整体删除,仅清理运行时残留
173
+ console.error('❌ [sillyspec] 拒绝删除源码目录的 .sillyspec/:检测到真实资产(changes/、projects/ 或 sillyspec.db)。');
174
+ console.error(' 该项目似乎本身就用 SillySpec 管理。如需改用外部 spec 目录,请先手动迁移/备份。');
175
+ console.error(' 本次仅清理运行时残留(.runtime/ 缓存、local.yaml、codebase/),保留 worktrees 与进度状态。');
176
+ cleanupRuntimeResidue(legacyDir);
177
+ } else {
178
+ // 无真实资产:确属旧版本残留,安全删除
179
+ try { rmSync(legacyDir, { recursive: true, force: true }) } catch {}
180
+ if (!existsSync(legacyDir)) console.log('🧹 已清理旧版本残留的源码 .sillyspec/ 目录');
181
+ else console.error('⚠️ 清理残留 .sillyspec/ 失败');
182
+ }
183
+ }
184
+
185
+ // 创建基础目录
186
+ // spec/projects/ → 项目注册表
187
+ // spec/docs/<name>/ → 统一文档中心
188
+ // spec/knowledge/ → 跨项目共享知识库
189
+ // spec/.runtime/ progress (gitignored)
190
+
191
+ // 注册当前项目到 projects/
192
+ const projectName = basename(projectDir) || 'project';
193
+ const projectsDir = join(spec, 'projects');
194
+ mkdirSync(projectsDir, { recursive: true });
195
+ const projectYamlPath = join(projectsDir, `${projectName}.yaml`);
196
+ if (!existsSync(projectYamlPath)) {
197
+ // path 相对于 specDir,跨平台可寻址
198
+ writeFileSync(projectYamlPath, `name: ${projectName}\npath: ${projectDir}\nstatus: active\n`);
199
+ }
200
+
201
+ // 创建 docs/<projectName>/scan/ 子目录(代码扫描结果)
202
+ const scanDir = join(spec, 'docs', projectName, 'scan');
203
+ mkdirSync(scanDir, { recursive: true });
204
+ const gitkeepPath = join(scanDir, '.gitkeep');
205
+ if (!existsSync(gitkeepPath)) writeFileSync(gitkeepPath, '');
206
+
207
+ // 复制 workflow 模板到 workflows/
208
+ const workflowsDir = join(spec, 'workflows');
209
+ const templatesDir = join(__dirname, '..', 'templates', 'workflows');
210
+ if (existsSync(templatesDir)) {
211
+ mkdirSync(workflowsDir, { recursive: true });
212
+ for (const file of readdirSync(templatesDir)) {
213
+ if (file.endsWith('.yaml')) {
214
+ const srcPath = join(templatesDir, file);
215
+ const dstPath = join(workflowsDir, file);
216
+ if (!existsSync(dstPath)) {
217
+ writeFileSync(dstPath, readFileSync(srcPath));
218
+ }
219
+ }
220
+ }
221
+ }
222
+
223
+ // 创建 shared/workspace 目录
224
+ mkdirSync(join(spec, 'shared'), { recursive: true });
225
+ mkdirSync(join(spec, 'workspace'), { recursive: true });
226
+
227
+ // 创建知识库骨架
228
+ const knowledgeDir = join(spec, 'knowledge');
229
+ mkdirSync(knowledgeDir, { recursive: true });
230
+ const indexPath = join(knowledgeDir, 'INDEX.md');
231
+ if (!existsSync(indexPath)) {
232
+ writeFileSync(indexPath, `# Knowledge Index\n\n> 子代理任务开始前查询此文件,按关键词匹配,只读命中的知识文件。\n> execute/quick 执行中发现的坑自动追加到 uncategorized.md,经用户确认后归类到对应文件。\n\n<!-- 格式:关键词1|关键词2|关键词3 → 文件路径 -->\n<!-- 示例:mybatis-plus|分页|Page → pagination.md -->\n<!-- 示例:跨域|CORS|preflight → cors.md -->\n`);
233
+ }
234
+ const uncatPath = join(knowledgeDir, 'uncategorized.md');
235
+ if (!existsSync(uncatPath)) {
236
+ writeFileSync(uncatPath, `# 未分类知识\n\n> execute/quick 执行中发现的坑暂存于此,用户审阅后归类到对应文件并更新 INDEX.md。\n`);
237
+ }
238
+
239
+ // 创建 .runtime/ 目录结构(全局状态)
240
+ const runtimeDir = join(spec, '.runtime');
241
+ for (const sub of ['artifacts', 'history', 'logs', 'templates']) {
242
+ mkdirSync(join(runtimeDir, sub), { recursive: true });
243
+ }
244
+
245
+ // 初始化 SQLite 数据库
246
+ const pm = new ProgressManager({ specDir: spec });
247
+ await pm.init(projectDir);
248
+
249
+ // .gitignore 只在 specDir 在项目内时才修改
250
+ const isExternalSpec = specDir && resolve(spec) !== resolve(projectDir, '.sillyspec');
251
+ if (!isExternalSpec) {
252
+ const gitignorePath = join(projectDir, '.gitignore');
253
+ const ignoreRules = ['.sillyspec/codebase/SCAN-RAW.md', '.sillyspec/local.yaml', '.sillyspec/.runtime/'];
254
+ if (existsSync(gitignorePath)) {
255
+ const content = readFileSync(gitignorePath, 'utf8');
256
+ let updated = content.trimEnd();
257
+ for (const rule of ignoreRules) {
258
+ if (!updated.includes(rule)) {
259
+ updated += '\n' + rule;
260
+ }
261
+ }
262
+ writeFileSync(gitignorePath, updated + '\n');
263
+ } else {
264
+ writeFileSync(gitignorePath, ignoreRules.join('\n') + '\n');
265
+ }
266
+ }
267
+
268
+ // 注入指令文件(codex/gemini/opencode)
269
+ for (let i = 0; i < tools.length; i++) {
270
+ const toolName = tools[i];
271
+ if (INSTRUCTION_TOOLS.includes(toolName)) {
272
+ injectInstructions(toolName, projectDir);
273
+ }
274
+ }
275
+
276
+ // 复制 skills 到各工具目录
277
+ const skillToolDirs = {
278
+ claude: '.claude/skills',
279
+ codex: '.codex/skills',
280
+ openclaw: '.openclaw/skills',
281
+ opencode: '.opencode/skills',
282
+ }
283
+ const skillsSource = join(__dirname, '..', '.claude', 'skills');
284
+ if (existsSync(skillsSource)) {
285
+ const sillyspecSkills = readdirSync(skillsSource).filter(f => f.startsWith('sillyspec-') && statSync(join(skillsSource, f)).isDirectory());
286
+ if (sillyspecSkills.length > 0) {
287
+ for (const [tool, dir] of Object.entries(skillToolDirs)) {
288
+ if (!tools.includes(tool)) continue
289
+ const targetDir = join(projectDir, dir)
290
+ mkdirSync(targetDir, { recursive: true })
291
+ for (const skill of sillyspecSkills) {
292
+ copyDirSync(join(skillsSource, skill), join(targetDir, skill))
293
+ }
294
+ console.log(chalk.green(` ✓ ${TOOL_LABELS[tool]} skills 已同步 (${sillyspecSkills.length} 个)`))
295
+ }
296
+ }
297
+ } else {
298
+ console.log(chalk.yellow(' ⚠ 未找到 skills 目录(npm 包内无 .claude/skills/),跳过同步'));
299
+ }
300
+ }
301
+
302
+ // ── 安装完成总结 ──
303
+
304
+ function showSummary(version, tools, specDir) {
305
+ const toolLabels = tools.map(t => TOOL_LABELS[t] || t);
306
+
307
+ console.log('');
308
+ console.log(chalk.green(' ═══════════════════════════════════════'));
309
+ console.log(chalk.green(` ✅ SillySpec v${version} 安装完成!`));
310
+ console.log(chalk.green(' ═══════════════════════════════════════'));
311
+ console.log('');
312
+ console.log(` 已安装工具: ${chalk.cyan(toolLabels.join(', '))}`);
313
+ console.log(` 📁 规范目录: ${chalk.cyan(specDir || '.sillyspec')}`);
314
+ console.log('');
315
+ console.log(' 下一步:使用 AI 技能开始工作');
316
+ console.log(' OpenClaw: ' + chalk.bold('/sillyspec:brainstorm'));
317
+ console.log(' Claude Code: ' + chalk.bold('/sillyspec:brainstorm'));
318
+ console.log('');
319
+ console.log(chalk.dim(' 💡 推荐安装 MCP 工具增强 AI 能力:sillyspec setup'));
320
+ console.log('');
321
+ }
322
+
323
+ // ── 读取版本号 ──
324
+
325
+ export function getVersion() {
326
+ try {
327
+ const pkg = JSON.parse(readFileSync(resolve(__dirname, '..', 'package.json'), 'utf8'));
328
+ return pkg.version;
329
+ } catch {
330
+ return '?.?.?';
331
+ }
332
+ }
333
+
334
+ // ── 主命令 ──
335
+
336
+ export async function cmdInit(projectDir, options = {}) {
337
+ const { tool, interactive, specDir } = options;
338
+ const version = getVersion();
339
+ const resolvedSpecDir = specDir ? resolve(specDir) : null;
340
+
341
+ // ── 交互式模式(--interactive 或 -i)──
342
+ if (interactive && isTTY()) {
343
+ // 欢迎画面
344
+ console.log('');
345
+ console.log(chalk.cyan('🤪 SillySpec v' + version + ' — 规范驱动开发'));
346
+ console.log(chalk.cyan(' ===================================='));
347
+ console.log('');
348
+ console.log(' AI 像高级工程师一样工作:');
349
+ console.log(' 先思考、先规划、先验证,再写代码。');
350
+ console.log('');
351
+ console.log(chalk.gray(' 支持的 AI 工具:'));
352
+ console.log(chalk.gray(' Claude Code · Claude Skills · Cursor · Codex CLI · OpenCode · OpenClaw'));
353
+ console.log('');
354
+
355
+ // 工具多选
356
+ const detected = detectTools(projectDir);
357
+
358
+ const toolChoices = VALID_TOOLS.map(v => ({
359
+ name: `${TOOL_LABELS[v]}${v === 'claude' ? ' (推荐)' : ''}`,
360
+ value: v,
361
+ checked: detected.includes(v),
362
+ }));
363
+
364
+ const selectedTools = await checkbox({
365
+ message: '选择要安装的 AI 工具(空格选择,回车确认)',
366
+ choices: toolChoices,
367
+ validate: (answer) => answer.length > 0 || '至少选择一个工具',
368
+ });
369
+
370
+ // 子项目引导(仅交互模式)
371
+ let subprojects = [];
372
+ {
373
+ console.log('');
374
+ console.log(chalk.yellow('📋 添加子项目'));
375
+ console.log(chalk.dim(' 子项目是工作区中的独立项目目录(如 frontend/、backend/)'));
376
+ console.log('');
377
+
378
+ const addMore = await confirm({ message: '现在添加子项目?', default: true });
379
+ if (addMore) {
380
+ let suggestions = [];
381
+ try {
382
+ const entries = readdirSync(projectDir, { withFileTypes: true });
383
+ suggestions = entries
384
+ .filter(e => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')
385
+ .map(e => e.name)
386
+ .sort();
387
+ } catch {}
388
+
389
+ if (suggestions.length > 0) {
390
+ console.log('');
391
+ console.log(chalk.dim(` 检测到以下目录:${suggestions.join(', ')}`));
392
+ console.log('');
393
+ }
394
+
395
+ let adding = true;
396
+ while (adding) {
397
+ const name = await input({
398
+ message: '子项目名称(如 frontend,留空结束)',
399
+ default: suggestions.find(s => !subprojects.find(p => p.name === s)) || '',
400
+ });
401
+
402
+ if (!name.trim()) {
403
+ adding = false;
404
+ break;
405
+ }
406
+
407
+ const pathHint = suggestions.includes(name.trim()) ? `./${name.trim()}` : '';
408
+ const subPath = await input({
409
+ message: '子项目目录路径',
410
+ default: pathHint,
411
+ });
412
+
413
+ const role = await input({
414
+ message: '子项目描述(如 前端 - Vue3 + TypeScript)',
415
+ default: '',
416
+ });
417
+
418
+ let repo = '';
419
+ try {
420
+ const { execSync } = await import('child_process');
421
+ const absPath = resolve(projectDir, subPath.trim() || `./${name.trim()}`);
422
+ repo = execSync('git remote get-url origin', { cwd: absPath, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
423
+ } catch {}
424
+
425
+ subprojects.push({ name: name.trim(), path: subPath.trim() || `./${name.trim()}`, role: role.trim(), repo });
426
+
427
+ const idx = suggestions.indexOf(name.trim());
428
+ if (idx >= 0) suggestions.splice(idx, 1);
429
+
430
+ const again = await confirm({ message: '继续添加子项目?', default: subprojects.length < suggestions.length });
431
+ if (!again) adding = false;
432
+ }
433
+ }
434
+ }
435
+
436
+ console.log('');
437
+ await doInstall(projectDir, selectedTools, subprojects, resolvedSpecDir);
438
+ showSummary(version, selectedTools, resolvedSpecDir);
439
+ return;
440
+ }
441
+
442
+ // ── 默认快速模式:检测 → 安装 → 结束 ──
443
+
444
+ let tools = [];
445
+ if (tool) {
446
+ if (!VALID_TOOLS.includes(tool)) {
447
+ console.error(`❌ 未知工具: ${tool}`);
448
+ console.error(`支持的工具: ${VALID_TOOLS.join(', ')}`);
449
+ process.exit(1);
450
+ }
451
+ tools = [tool];
452
+ } else {
453
+ tools = detectTools(projectDir);
454
+ }
455
+
456
+ await doInstall(projectDir, tools, [], resolvedSpecDir);
457
+
458
+ console.log('');
459
+ console.log(chalk.green(` ✅ SillySpec v${version} 安装完成!`));
460
+ console.log('');
461
+ const specDisplay = resolvedSpecDir || '.sillyspec';
462
+ console.log(` 📁 规范目录: ${chalk.cyan(specDisplay)}`);
463
+ console.log('');
464
+ console.log(' 下一步:使用 AI 技能开始工作');
465
+ console.log(` OpenClaw: ${chalk.bold('/sillyspec:brainstorm')}`);
466
+ console.log(` Claude Code: ${chalk.bold('/sillyspec:brainstorm')}`);
467
+ console.log('');
468
+ console.log(chalk.dim(' 💡 增强能力:sillyspec setup(安装 MCP 工具)'));
469
+ console.log('');
470
+ }