sillyspec 3.20.2 → 3.20.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/.claude/skills/sillyspec-archive/SKILL.md +1 -5
  2. package/.claude/skills/sillyspec-auto/SKILL.md +2 -8
  3. package/.claude/skills/sillyspec-brainstorm/SKILL.md +1 -28
  4. package/.claude/skills/sillyspec-commit/SKILL.md +3 -4
  5. package/.claude/skills/sillyspec-continue/SKILL.md +4 -5
  6. package/.claude/skills/sillyspec-doctor/SKILL.md +3 -12
  7. package/.claude/skills/sillyspec-execute/SKILL.md +2 -15
  8. package/.claude/skills/sillyspec-explore/SKILL.md +1 -14
  9. package/.claude/skills/sillyspec-plan/SKILL.md +36 -5
  10. package/.claude/skills/sillyspec-propose/SKILL.md +0 -4
  11. package/.claude/skills/sillyspec-quick/SKILL.md +1 -5
  12. package/.claude/skills/sillyspec-resume/SKILL.md +66 -23
  13. package/.claude/skills/sillyspec-scan/SKILL.md +1 -5
  14. package/.claude/skills/sillyspec-state/SKILL.md +8 -8
  15. package/.claude/skills/sillyspec-status/SKILL.md +1 -5
  16. package/.claude/skills/sillyspec-verify/SKILL.md +1 -5
  17. package/.claude/skills/sillyspec-workspace/SKILL.md +3 -11
  18. package/.sillyspec/changes/archive/2026-04-08-derive-state/design.md +97 -0
  19. package/.sillyspec/changes/archive/2026-04-08-derive-state/plan.md +51 -0
  20. package/.sillyspec/changes/archive/2026-04-08-derive-state/proposal.md +29 -0
  21. package/.sillyspec/changes/archive/2026-04-08-derive-state/requirements.md +34 -0
  22. package/.sillyspec/changes/archive/2026-04-08-derive-state/tasks.md +13 -0
  23. package/.sillyspec/changes/archive/2026-04-08-derive-state/verify-result.md +43 -0
  24. package/.sillyspec/changes/auto-mode/design.md +50 -0
  25. package/.sillyspec/changes/auto-mode/proposal.md +19 -0
  26. package/.sillyspec/changes/auto-mode/requirements.md +21 -0
  27. package/.sillyspec/changes/auto-mode/tasks.md +7 -0
  28. package/.sillyspec/changes/brainstorm-archive/2026-04-05-dashboard-design.md +206 -0
  29. package/.sillyspec/changes/brainstorm-archive/2026-04-05-unified-docs-design.md +199 -0
  30. package/.sillyspec/changes/dashboard/design.md +219 -0
  31. package/.sillyspec/changes/dashboard/design.md.braindraft +206 -0
  32. package/.sillyspec/changes/run-command-design/design.md +1230 -0
  33. package/.sillyspec/changes/unified-docs-design/design.md +199 -0
  34. package/.sillyspec/docs/sillyspec/scan/.gitkeep +0 -0
  35. package/.sillyspec/knowledge/INDEX.md +8 -0
  36. package/.sillyspec/knowledge/uncategorized.md +3 -0
  37. package/.sillyspec/plans/2026-04-05-dashboard.md +737 -0
  38. package/.sillyspec/projects/sillyspec.yaml +3 -0
  39. package/README.md +11 -13
  40. package/SKILL.md +40 -44
  41. package/dist/steps/brainstorm/01-load-context.md +30 -0
  42. package/dist/steps/brainstorm/02-reuse-check.md +6 -0
  43. package/dist/steps/brainstorm/03-prototype-analysis.md +11 -0
  44. package/dist/steps/brainstorm/04-module-split.md +23 -0
  45. package/dist/steps/brainstorm/05-dialog-explore.md +8 -0
  46. package/dist/steps/brainstorm/06-propose-approaches.md +3 -0
  47. package/dist/steps/brainstorm/07-present-design.md +3 -0
  48. package/dist/steps/brainstorm/08-write-design.md +21 -0
  49. package/dist/steps/brainstorm/09-self-review.md +15 -0
  50. package/dist/steps/brainstorm/10-user-confirm.md +3 -0
  51. package/dist/steps/brainstorm/11-output-spec.md +7 -0
  52. package/dist/steps/brainstorm/manifest.yaml +26 -0
  53. package/dist/steps/execute/01-load-context.md +41 -0
  54. package/dist/steps/execute/02-scan-conventions.md +47 -0
  55. package/dist/steps/execute/03-skill-mcp.md +19 -0
  56. package/dist/steps/execute/04-assign-task.md +22 -0
  57. package/dist/steps/execute/04b-prompt-template.md +54 -0
  58. package/dist/steps/execute/05-write-test.md +7 -0
  59. package/dist/steps/execute/06-write-code.md +8 -0
  60. package/dist/steps/execute/07-run-test.md +26 -0
  61. package/dist/steps/execute/08-fix-issues.md +28 -0
  62. package/dist/steps/execute/09-next-task.md +33 -0
  63. package/dist/steps/execute/manifest.yaml +28 -0
  64. package/dist/steps/plan/01-load-context.md +22 -0
  65. package/dist/steps/plan/02-anchor-confirm.md +1 -0
  66. package/dist/steps/plan/03-expand-tasks.md +33 -0
  67. package/dist/steps/plan/04-mark-order.md +15 -0
  68. package/dist/steps/plan/05-e2e-planning.md +17 -0
  69. package/dist/steps/plan/06-self-check.md +16 -0
  70. package/dist/steps/plan/07-save.md +1 -0
  71. package/dist/steps/plan/manifest.yaml +18 -0
  72. package/dist/steps/scan/01-env-detect.md +51 -0
  73. package/dist/steps/scan/02-tech-stack.md +16 -0
  74. package/dist/steps/scan/03-conventions.md +16 -0
  75. package/dist/steps/scan/04-structure.md +19 -0
  76. package/dist/steps/scan/05-quality.md +18 -0
  77. package/dist/steps/scan/06-complete.md +49 -0
  78. package/dist/steps/scan/manifest.yaml +16 -0
  79. package/dist/steps/verify/01-load-specs.md +28 -0
  80. package/dist/steps/verify/02-check-tasks.md +1 -0
  81. package/dist/steps/verify/03-check-design.md +6 -0
  82. package/dist/steps/verify/04-run-tests.md +7 -0
  83. package/dist/steps/verify/05-e2e-tests.md +27 -0
  84. package/dist/steps/verify/05b-e2e-fix.md +33 -0
  85. package/dist/steps/verify/06-code-quality.md +25 -0
  86. package/dist/steps/verify/07-lint-check.md +27 -0
  87. package/dist/steps/verify/08-output-report.md +14 -0
  88. package/dist/steps/verify/manifest.yaml +22 -0
  89. package/package.json +1 -7
  90. package/packages/dashboard/dist/assets/{index-Bq_Z2hne.js → index-D1EVTLmc.js} +1264 -1264
  91. package/packages/dashboard/dist/assets/index-DGe8CqeP.css +1 -0
  92. package/packages/dashboard/dist/index.html +2 -2
  93. package/packages/dashboard/package-lock.json +6 -6
  94. package/packages/dashboard/server/executor.js +1 -1
  95. package/packages/dashboard/server/index.js +18 -98
  96. package/packages/dashboard/server/parser.js +71 -139
  97. package/packages/dashboard/server/watcher.js +6 -14
  98. package/packages/dashboard/src/App.vue +185 -418
  99. package/packages/dashboard/src/components/ActionBar.vue +1 -10
  100. package/packages/dashboard/src/components/CommandPalette.vue +1 -5
  101. package/packages/dashboard/src/components/DocPreview.vue +8 -105
  102. package/packages/dashboard/src/components/DocTree.vue +19 -75
  103. package/packages/dashboard/src/components/PipelineStage.vue +2 -22
  104. package/packages/dashboard/src/components/PipelineView.vue +5 -32
  105. package/packages/dashboard/src/components/ProjectOverview.vue +139 -113
  106. package/packages/dashboard/src/components/StageBadge.vue +3 -17
  107. package/packages/dashboard/src/components/StepCard.vue +2 -7
  108. package/packages/dashboard/src/composables/useDashboard.js +0 -28
  109. package/src/derive.js +147 -0
  110. package/src/index.js +40 -688
  111. package/src/init.js +63 -119
  112. package/src/migrate.js +7 -7
  113. package/src/progress.js +248 -1474
  114. package/src/run.js +302 -3008
  115. package/src/setup.js +64 -2
  116. package/src/stages/archive.js +17 -123
  117. package/src/stages/brainstorm.js +48 -454
  118. package/src/stages/doctor.js +46 -99
  119. package/src/stages/execute.js +59 -420
  120. package/src/stages/index.js +18 -12
  121. package/src/stages/plan.js +189 -492
  122. package/src/stages/propose.js +11 -70
  123. package/src/stages/quick.js +13 -52
  124. package/src/stages/scan.js +68 -485
  125. package/src/stages/status.js +1 -1
  126. package/src/stages/verify.js +16 -203
  127. package/src/step.js +543 -0
  128. package/.claude/skills/sillyspec-knowledge/SKILL.md +0 -270
  129. package/.husky/pre-push +0 -13
  130. package/CLAUDE.md +0 -18
  131. package/docs/brainstorm-plan-contract.md +0 -64
  132. package/docs/plan-execute-contract.md +0 -123
  133. package/docs/platform-scan-protocol.md +0 -298
  134. package/docs/revision-mode.md +0 -115
  135. package/docs/sillyspec/file-lifecycle/known-implementation-gaps.md +0 -99
  136. package/docs/sillyspec/file-lifecycle/platform-workflows-sync.md +0 -218
  137. package/docs/sillyspec/file-lifecycle/stage-artifacts.md +0 -167
  138. package/docs/sillyspec/file-lifecycle/storage-and-state.md +0 -148
  139. package/docs/sillyspec/file-lifecycle/worktree-and-guard.md +0 -193
  140. package/docs/sillyspec/file-lifecycle.md +0 -125
  141. package/docs/workflow-contract-regression.md +0 -106
  142. package/docs/worktree-isolation.md +0 -252
  143. package/packages/dashboard/dist/assets/index-O2W5RV4z.css +0 -1
  144. package/packages/dashboard/dist/prototype-dashboard.html +0 -836
  145. package/packages/dashboard/dist/prototype-overview.html +0 -256
  146. package/packages/dashboard/public/prototype-dashboard.html +0 -836
  147. package/packages/dashboard/public/prototype-overview.html +0 -256
  148. package/packages/dashboard/src/components/HResizeHandle.vue +0 -48
  149. package/packages/dashboard/src/components/ProjectCard.vue +0 -187
  150. package/packages/dashboard/src/components/VResizeHandle.vue +0 -61
  151. package/packages/dashboard/src/composables/useLayout.js +0 -131
  152. package/src/brainstorm-postcheck.js +0 -158
  153. package/src/change-list.js +0 -52
  154. package/src/change-risk-profile.js +0 -352
  155. package/src/classify-change.js +0 -73
  156. package/src/constants.js +0 -70
  157. package/src/contract-matrix.js +0 -278
  158. package/src/db.js +0 -201
  159. package/src/endpoint-extractor.js +0 -315
  160. package/src/hooks/claude-pre-tool-use.cjs +0 -125
  161. package/src/hooks/worktree-guard.js +0 -761
  162. package/src/knowledge-match.js +0 -130
  163. package/src/modules.js +0 -482
  164. package/src/scan-postcheck.js +0 -383
  165. package/src/stage-contract.js +0 -700
  166. package/src/stages/brainstorm-auto.js +0 -229
  167. package/src/stages/explore.js +0 -34
  168. package/src/stages/knowledge.js +0 -498
  169. package/src/stages/plan-postcheck.js +0 -513
  170. package/src/sync.js +0 -497
  171. package/src/task-review.js +0 -346
  172. package/src/workflow.js +0 -785
  173. package/src/worktree-apply.js +0 -549
  174. package/src/worktree.js +0 -932
  175. package/templates/workflows/archive-impact.yaml +0 -79
  176. package/templates/workflows/scan-docs.yaml +0 -132
  177. package/test/brainstorm-plan-contract.test.mjs +0 -273
  178. package/test/check-syntax.mjs +0 -26
  179. package/test/cli-top-level-aliases.test.mjs +0 -174
  180. package/test/contract-artifacts.test.mjs +0 -323
  181. package/test/decision-supersede.test.mjs +0 -277
  182. package/test/knowledge-match.test.mjs +0 -231
  183. package/test/plan-execute-contract.test.mjs +0 -330
  184. package/test/plan-optimization.test.mjs +0 -572
  185. package/test/platform-artifacts.test.mjs +0 -190
  186. package/test/platform-failure-samples.test.mjs +0 -199
  187. package/test/platform-recovery-chain.test.mjs +0 -179
  188. package/test/platform-recovery.test.mjs +0 -167
  189. package/test/platform-scan-p0.test.mjs +0 -175
  190. package/test/revision-v1.test.mjs +0 -1145
  191. package/test/run-sanitize-project-name.test.mjs +0 -51
  192. package/test/run-scan-postcheck-fail.test.mjs +0 -64
  193. package/test/run-scan-project-parse.test.mjs +0 -200
  194. package/test/run-tests.mjs +0 -48
  195. package/test/scan-docs-yaml-placeholders.test.mjs +0 -84
  196. package/test/scan-knowledge.test.mjs +0 -175
  197. package/test/scan-paths.test.mjs +0 -68
  198. package/test/scan-postcheck-project-priority.test.mjs +0 -85
  199. package/test/scan-postcheck.test.mjs +0 -197
  200. package/test/scan-workflow-anyfailed-block.test.mjs +0 -52
  201. package/test/spec-dir.test.mjs +0 -206
  202. package/test/stage-contract-failed-post-check.test.mjs +0 -102
  203. package/test/stage-contract.test.mjs +0 -299
  204. package/test/stage-definitions.test.mjs +0 -39
  205. package/test/wait-gates.test.mjs +0 -501
  206. package/test/workflow-spec-base.test.mjs +0 -142
  207. package/test/worktree-guard.test.mjs +0 -136
  208. package/test/worktree-native-overlay.test.mjs +0 -188
@@ -1,549 +0,0 @@
1
- /**
2
- * SillySpec applyWorktree — 将 worktree 中的变更应用到主工作区
3
- *
4
- * 流程:
5
- * 1. 读取 meta.json 获取 baseHash
6
- * 2. git diff --name-only baseHash 获取 worktree 中所有变更文件
7
- * 3. 从 design.md 解析文件变更清单(无清单 = 允许所有)
8
- * 4. 校验:变更文件 ⊆ 清单
9
- * 5. 校验:主工作区文件 base hash 一致
10
- * 6. --check-only 模式只输出检查结果
11
- * 7. 非 checkOnly:生成 patch → apply --check → apply --3way
12
- * 8. 成功后自动 cleanup
13
- */
14
-
15
- import { execSync } from 'child_process';
16
- import { existsSync, unlinkSync, writeFileSync, mkdtempSync, rmSync } from 'fs';
17
- import { join, resolve } from 'path';
18
- import { tmpdir } from 'os';
19
- import { createHash } from 'crypto';
20
- import { WorktreeManager } from './worktree.js';
21
- import { parseFileChangeList } from './change-list.js';
22
-
23
- const CHANGES_REL = '.sillyspec/changes';
24
-
25
- function git(cwd, args) {
26
- return execSync(`git ${args}`, { cwd, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
27
- }
28
-
29
- function gitQuiet(cwd, args) {
30
- try {
31
- return execSync(`git ${args}`, { cwd, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
32
- } catch {
33
- return null;
34
- }
35
- }
36
-
37
- /**
38
- * 获取文件在 git 中的 blob hash(基于某个 commit/tree)
39
- * @param {string} cwd - git 工作区路径
40
- * @param {string} treeish - commit hash、分支等
41
- * @param {string} filePath - 相对路径
42
- * @returns {string|null} blob hash,文件不存在返回 null
43
- */
44
- function getFileBlobHash(cwd, treeish, filePath) {
45
- return gitQuiet(cwd, `rev-parse ${treeish}:${filePath}`);
46
- }
47
-
48
- /**
49
- * apply worktree 变更到主工作区
50
- *
51
- * @param {string} changeName - 变更名
52
- * @param {{ cwd?: string, checkOnly?: boolean }} opts
53
- * @returns {{
54
- * ok: boolean,
55
- * changedFiles: string[],
56
- * extraFiles: string[],
57
- * hashMismatchFiles: string[],
58
- * patchPath: string|null,
59
- * errors: string[]
60
- * }}
61
- */
62
- export function applyWorktree(changeName, { cwd, checkOnly = false } = {}) {
63
- const projectRoot = cwd || process.cwd();
64
- const wm = new WorktreeManager({ cwd: projectRoot });
65
- const meta = wm.getMeta(changeName);
66
- const result = {
67
- ok: false,
68
- changedFiles: [],
69
- extraFiles: [],
70
- hashMismatchFiles: [],
71
- patchPath: null,
72
- errors: [],
73
- };
74
-
75
- // --- 1. 校验 worktree 存在 + meta.json 有效 ---
76
- if (!meta) {
77
- result.errors.push(`worktree not found: ${changeName}。meta.json 不存在或已损坏。`);
78
- return result;
79
- }
80
-
81
- const { worktreePath, baseHash, baselineCommit } = meta;
82
- // diff 起始点:有 baseline checkpoint 用它(只合子代理改动),否则 fallback 到 baseHash
83
- const diffBase = baselineCommit || baseHash;
84
-
85
- if (!existsSync(worktreePath)) {
86
- result.errors.push(`worktree 目录不存在: ${worktreePath}`);
87
- return result;
88
- }
89
-
90
- // --- 2. 获取变更文件列表 ---
91
- // worktree 内修改可能没有 commit,用 git diff <baseHash>(比较 baseHash 到工作区内容)
92
- // 同时检测 untracked 新文件(git diff 不包含 untracked)
93
- let changedFiles;
94
- try {
95
- // 用 --name-status 捕获 rename/delete(--name-only 会丢失 rename 源文件)
96
- const statusRaw = git(worktreePath, `diff --name-status ${diffBase}`);
97
- const statusFiles = new Set();
98
- if (statusRaw) {
99
- for (const line of statusRaw.split('\n').filter(Boolean)) {
100
- const parts = line.split('\t');
101
- // R100 old.txt new.txt → 提取两个文件
102
- if (parts.length >= 2) statusFiles.add(parts[parts.length - 1]);
103
- if (parts.length >= 3) statusFiles.add(parts[parts.length - 2]);
104
- }
105
- }
106
-
107
- // untracked 新文件(diffBase 中不存在的文件)
108
- const untrackedRaw = gitQuiet(worktreePath, `ls-files --others --exclude-standard`);
109
- const untrackedFiles = untrackedRaw
110
- ? untrackedRaw.split('\n').filter(Boolean).filter(f => !f.startsWith('.sillyspec/') && f !== 'meta.json')
111
- : [];
112
-
113
- changedFiles = [...new Set([...statusFiles, ...untrackedFiles])];
114
- } catch (e) {
115
- result.errors.push(`获取变更文件列表失败: ${e.message}`);
116
- return result;
117
- }
118
-
119
- result.changedFiles = changedFiles;
120
-
121
- if (changedFiles.length === 0) {
122
- // 没有变更
123
- if (!checkOnly) {
124
- wm.cleanup(changeName);
125
- }
126
- result.ok = true;
127
- return result;
128
- }
129
-
130
- // --- 3. 解析 design.md 文件变更清单 ---
131
- const designPath = join(projectRoot, CHANGES_REL, changeName, 'design.md');
132
- const allowSet = parseFileChangeList(designPath);
133
- const hasAllowList = allowSet.size > 0;
134
-
135
- // --- 4. 校验:变更文件 ⊆ 清单(无清单则跳过)---
136
- if (hasAllowList) {
137
- for (const f of changedFiles) {
138
- if (!allowSet.has(f)) {
139
- result.extraFiles.push(f);
140
- }
141
- }
142
- if (result.extraFiles.length > 0) {
143
- result.errors.push(
144
- `文件清单校验失败:以下变更文件不在 design.md 清单中:\n ${result.extraFiles.join('\n ')}`
145
- );
146
- return result;
147
- }
148
- }
149
-
150
- // --- 4.5 校验:主工作区 baseline 是否变化(防 execute 期间主工作区被修改)---
151
- // 注意:必须和 computeBaselineHash (worktree.js) 使用相同的排除规则
152
- if (meta.baselineHash) {
153
- const exclude = '-- . ":(exclude).sillyspec/"';
154
- const staged = gitQuiet(projectRoot, `diff --cached ${exclude}`) || '';
155
- const unstaged = gitQuiet(projectRoot, `diff ${exclude}`) || '';
156
- const untracked = gitQuiet(projectRoot, `ls-files --others --exclude-standard ${exclude}`) || '';
157
- const raw = `staged:${staged}\nunstaged:${unstaged}\nuntracked:${untracked}`;
158
- const currentHash = createHash('sha256').update(raw).digest('hex').slice(0, 16);
159
- if (currentHash !== meta.baselineHash) {
160
- result.errors.push(
161
- `主工作区 baseline 已变化(execute 前后不一致),不能直接 apply task.patch。\n` +
162
- `建议:重新创建 worktree 或手动检查冲突。\n` +
163
- `execute 前 baseline: ${meta.baselineHash}\n` +
164
- `当前 baseline: ${currentHash}`
165
- );
166
- return result;
167
- }
168
- }
169
-
170
- // --- 5. 校验:主工作区文件 base hash 一致 ---
171
- // 5a. 检查主工作区是否有未 commit 的脏文件(会影响 apply)
172
- const mainDirtyRaw = gitQuiet(projectRoot, 'diff --name-only HEAD');
173
- const mainDirtyFiles = mainDirtyRaw ? mainDirtyRaw.split('\n').filter(Boolean) : [];
174
- if (mainDirtyFiles.length > 0) {
175
- // 如果脏文件和本次 apply 的文件有交集 → 报错
176
- const conflictDirty = mainDirtyFiles.filter(f => changedFiles.includes(f));
177
- if (conflictDirty.length > 0) {
178
- result.errors.push(
179
- `主工作区有以下未 commit 的变更,会影响 apply:\n ${conflictDirty.join('\n ')}\n请先 commit 或 stash 这些变更。`
180
- );
181
- return result;
182
- }
183
- }
184
-
185
- // 5b. 对比 worktree 的 baseHash 和主工作区 HEAD 中每个清单文件的 blob hash
186
- const targetFiles = hasAllowList ? [...allowSet] : changedFiles;
187
- for (const f of targetFiles) {
188
- const wtBlob = getFileBlobHash(worktreePath, baseHash, f);
189
- const mainBlob = getFileBlobHash(projectRoot, 'HEAD', f);
190
-
191
- // 两者都为 null(文件在 base 时不存在)→ OK
192
- if (wtBlob === null && mainBlob === null) continue;
193
- // 两者一致 → OK
194
- if (wtBlob === mainBlob) continue;
195
- // 不一致 → 主工作区已被修改
196
- result.hashMismatchFiles.push(f);
197
- }
198
-
199
- if (result.hashMismatchFiles.length > 0) {
200
- result.errors.push(
201
- `base hash 不一致:以下文件在主工作区已被修改:\n ${result.hashMismatchFiles.join('\n ')}`
202
- );
203
- return result;
204
- }
205
-
206
- // --- 6. checkOnly 模式:到此返回 ---
207
- if (checkOnly) {
208
- result.ok = true;
209
- return result;
210
- }
211
-
212
- // --- 7. 生成 patch 并 apply ---
213
- // 确定要包含在 patch 中的文件:有清单用清单交集,无清单用全部变更
214
- const patchFiles = hasAllowList
215
- ? [...allowSet].filter(f => changedFiles.includes(f))
216
- : changedFiles;
217
- const fileArgs = patchFiles.length > 0 ? `-- ${patchFiles.join(' ')}` : '';
218
-
219
- // 创建临时文件
220
- const tmpDir = mkdtempSync(join(tmpdir(), 'sillyspec-patch-'));
221
- const patchPath = join(tmpDir, 'apply.patch');
222
- result.patchPath = patchPath;
223
-
224
- try {
225
- let patchContent = '';
226
-
227
- // 分 tracked 变更和 untracked 新文件生成 patch
228
- const trackedFiles = patchFiles.filter(f => {
229
- // 文件在 diffBase 的 tree 中存在 → tracked(包括 rename 目标可能的情况)
230
- if (gitQuiet(worktreePath, `cat-file -e ${diffBase}:${f}`) !== null) return true;
231
- // 文件在工作区 index 中已存在(比如被 git mv 处理过)→ 也视为 tracked
232
- if (gitQuiet(worktreePath, `ls-files --error-unmatch ${f}`) !== null) return true;
233
- return false;
234
- });
235
- const untrackedPatchFiles = patchFiles.filter(f => !trackedFiles.includes(f));
236
-
237
- // tracked 文件:git diff baseHash
238
- if (trackedFiles.length > 0) {
239
- const trackedArgs = trackedFiles.length > 0 ? `-- ${trackedFiles.join(' ')}` : '';
240
- patchContent += execSync(
241
- `git diff --binary ${diffBase} ${trackedArgs}`,
242
- { cwd: worktreePath, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }
243
- );
244
- }
245
-
246
- // untracked 新文件:git add 到 index,git diff --cached,然后 reset
247
- if (untrackedPatchFiles.length > 0) {
248
- const addArgs = untrackedPatchFiles.length > 0 ? `-- ${untrackedPatchFiles.join(' ')}` : '';
249
- git(worktreePath, `add ${addArgs}`);
250
- try {
251
- const diffCachedArgs = untrackedPatchFiles.length > 0 ? `-- ${untrackedPatchFiles.join(' ')}` : '';
252
- patchContent += execSync(
253
- `git diff --binary --cached ${diffCachedArgs}`,
254
- { cwd: worktreePath, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }
255
- );
256
- } finally {
257
- // 重置 index(不保留 staged 状态)
258
- gitQuiet(worktreePath, `reset HEAD -- ${addArgs}`);
259
- }
260
- }
261
-
262
- if (!patchContent.trim()) {
263
- // patch 为空(清单中部分文件可能没实际变更)
264
- result.ok = true;
265
- rmSync(tmpDir, { recursive: true, force: true });
266
- return result;
267
- }
268
-
269
- writeFileSync(patchPath, patchContent);
270
-
271
- // apply --check 预检
272
- try {
273
- git(projectRoot, `apply --check ${patchPath}`);
274
- } catch (e) {
275
- result.errors.push(`patch 预检失败: ${e.message}`);
276
- return result;
277
- }
278
-
279
- // apply --3way 正式应用
280
- try {
281
- git(projectRoot, `apply --3way ${patchPath}`);
282
- } catch (e) {
283
- result.errors.push(`patch apply 失败: ${e.message}`);
284
- return result;
285
- }
286
-
287
- result.ok = true;
288
-
289
- // --- 8. 成功后自动 cleanup(失败不影响整体结果) ---
290
- try {
291
- wm.cleanup(changeName);
292
- } catch (cleanupErr) {
293
- result.warnings = result.warnings || [];
294
- result.warnings.push(`cleanup 失败(不影响应用结果): ${cleanupErr.message}`);
295
- }
296
-
297
- } catch (e) {
298
- result.errors.push(`patch 生成/应用异常: ${e.message}`);
299
- return result;
300
- } finally {
301
- // 清理临时目录
302
- try { rmSync(tmpDir, { recursive: true, force: true }); } catch {}
303
- }
304
-
305
- return result;
306
- }
307
-
308
- /**
309
- * 风险审计:评估 worktree 变更是否可以安全自动 apply
310
- *
311
- * 检查项:
312
- * 1. patch --check 通过
313
- * 2. 所有变更在 allowed_paths 内
314
- * 3. 主工作区 baseline 未变化
315
- * 4. 没有删除/重命名关键文件
316
- * 5. 没有改高风险文件(lockfile/migration/配置/入口)除非任务显式允许
317
- * 6. diff 规模没有异常膨胀
318
- *
319
- * @param {string} changeName
320
- * @param {{ cwd?: string }} opts
321
- * @returns {{
322
- * decision: 'SAFE' | 'WARNING' | 'BLOCKED',
323
- * changedFiles: string[],
324
- * reasons: string[],
325
- * warnings: string[],
326
- * stats: { additions: number, deletions: number }
327
- * }}
328
- */
329
- export function assessApplyRisk(changeName, { cwd } = {}) {
330
- const projectRoot = cwd || process.cwd();
331
- const reasons = [];
332
- const warnings = [];
333
-
334
- // 先跑 --check-only 模式的 applyWorktree 获取变更文件列表
335
- const checkResult = applyWorktree(changeName, { cwd: projectRoot, checkOnly: true });
336
-
337
- if (checkResult.errors.length > 0) {
338
- return {
339
- decision: 'BLOCKED',
340
- changedFiles: checkResult.changedFiles,
341
- reasons: checkResult.errors,
342
- warnings: [],
343
- stats: { additions: 0, deletions: 0 }
344
- };
345
- }
346
-
347
- const changedFiles = checkResult.changedFiles;
348
-
349
- if (changedFiles.length === 0) {
350
- return {
351
- decision: 'SAFE',
352
- changedFiles: [],
353
- reasons: ['无变更需要应用'],
354
- warnings: [],
355
- stats: { additions: 0, deletions: 0 }
356
- };
357
- }
358
-
359
- // 解析 TaskCard allowed_paths
360
- const wm = new WorktreeManager({ cwd: projectRoot });
361
- const meta = wm.getMeta(changeName);
362
- const tasksDir = join(projectRoot, CHANGES_REL, changeName, 'tasks');
363
- const allowedPaths = new Set();
364
- if (existsSync(tasksDir)) {
365
- const { readdirSync, readFileSync } = require('fs');
366
- for (const tf of readdirSync(tasksDir).filter(f => /^task-\d+\.md$/.test(f))) {
367
- const content = readFileSync(join(tasksDir, tf), 'utf8');
368
- const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
369
- if (!fmMatch) continue;
370
- const fm = fmMatch[1];
371
- const inline = fm.match(/allowed_paths:\s*\[([^\]]*)\]/);
372
- if (inline) {
373
- inline[1].split(',').forEach(s => { const v = s.trim().replace(/['"]/g, ''); if (v) allowedPaths.add(v); });
374
- }
375
- const block = fm.match(/allowed_paths:\s*\n((?:\s+-\s+.+\n?)+)/);
376
- if (block) {
377
- block[1].match(/-\s+(.+)/g)?.forEach(s => { const v = s.replace(/^-\s+/, '').trim().replace(/['"]/g, ''); if (v) allowedPaths.add(v); });
378
- }
379
- }
380
- }
381
-
382
- // 检查 2: 变更在 allowed_paths 内(仅在 TaskCard 存在时)
383
- if (allowedPaths.size > 0) {
384
- const outsidePaths = changedFiles.filter(f => !
385
- [...allowedPaths].some(allowed => f === allowed || f.startsWith(allowed.replace(/\*$/, '')))
386
- );
387
- if (outsidePaths.length > 0) {
388
- reasons.push(`变更文件超出 allowed_paths:\n ${outsidePaths.join('\n ')}`);
389
- }
390
- }
391
-
392
- // 检查 4+5: 高风险文件模式
393
- const HIGH_RISK_PATTERNS = [
394
- /(^|\/)package-lock\.json$/,
395
- /(^|\/)pnpm-lock\.yaml$/,
396
- /(^|\/)yarn\.lock$/,
397
- /(^|\/)\.env($|\.)/,
398
- /(^|\/)docker-compose.*\.ya?ml$/,
399
- /(^|\/)Dockerfile$/,
400
- /migration[\w.-]*\.(sql|js|ts)$/i,
401
- /(^|\/).*entry.*\.(js|ts)$/i,
402
- /(^|\/)main\.(js|ts)$/i,
403
- /(^|\/)index\.(js|ts)$/i,
404
- /(^|\/)app\.(js|ts)$/i,
405
- ];
406
- const riskyFiles = changedFiles.filter(f => HIGH_RISK_PATTERNS.some(p => p.test(f)));
407
- if (riskyFiles.length > 0) {
408
- // 高风险文件只有在 allowedPaths 显式包含时才放行
409
- const trulyRisky = riskyFiles.filter(f => !
410
- [...allowedPaths].some(allowed => f === allowed)
411
- );
412
- if (trulyRisky.length > 0) {
413
- reasons.push(`高风险文件变更(未在 allowed_paths 中显式声明):\n ${trulyRisky.join('\n ')}`);
414
- } else {
415
- warnings.push(`高风险文件变更(已在 allowed_paths 中声明):${riskyFiles.join(', ')}`);
416
- }
417
- }
418
-
419
- // 检查 6: diff 规模异常(>2000 行变更视为异常)
420
- const wtPath = meta?.worktreePath;
421
- const diffBase = meta?.baselineCommit || meta?.baseHash;
422
- let additions = 0, deletions = 0;
423
- if (wtPath && diffBase) {
424
- try {
425
- const shortstat = gitQuiet(wtPath, `diff --shortstat ${diffBase}`);
426
- const insMatch = shortstat?.match(/(\d+) insertion/);
427
- const delMatch = shortstat?.match(/(\d+) deletion/);
428
- additions = insMatch ? parseInt(insMatch[1]) : 0;
429
- deletions = delMatch ? parseInt(delMatch[1]) : 0;
430
- if (additions + deletions > 2000) {
431
- reasons.push(`diff 规模异常(${additions} additions + ${deletions} deletions = ${additions + deletions} 行)`);
432
- }
433
- } catch {}
434
- }
435
-
436
- // 判定
437
- let decision;
438
- if (reasons.length > 0) {
439
- decision = 'BLOCKED';
440
- } else if (warnings.length > 0) {
441
- decision = 'WARNING';
442
- } else {
443
- decision = 'SAFE';
444
- }
445
-
446
- return { decision, changedFiles, reasons, warnings, stats: { additions, deletions } };
447
- }
448
-
449
- /**
450
- * 格式化 execute run summary(人类可读)
451
- *
452
- * 只展示 CLI 真实掌握的信息,不声称知道 per-task 状态。
453
- * @param {object} opts
454
- * @param {string} opts.changeName - 变更名
455
- * @param {number} opts.stepsCompleted - 已完成步骤数
456
- * @param {number} opts.stepsTotal - 总步骤数
457
- * @param {string} opts.agentSummary - Agent 最终输出摘要
458
- * @param {string} [opts.cwd] - 项目根目录(默认 process.cwd())
459
- * @returns {string} 格式化的 summary 文本
460
- */
461
- export function formatExecuteSummary({ changeName, stepsCompleted, stepsTotal, agentSummary, cwd }) {
462
- const wm = new WorktreeManager({ cwd });
463
- const meta = wm.getMeta(changeName);
464
- const lines = [];
465
-
466
- const SEPARATOR = '─'.repeat(32);
467
-
468
- // --- Header ---
469
- lines.push(`Execute Summary`);
470
- lines.push(SEPARATOR);
471
-
472
- // --- Status ---
473
- if (!meta) {
474
- // worktree 不存在(可能已 cleanup 或没有用过 worktree)
475
- lines.push(`Status: COMPLETED`);
476
- lines.push(`Steps: ${stepsCompleted} / ${stepsTotal}`);
477
- lines.push(`Apply: N/A`);
478
- } else {
479
- const hasBaseline = meta.baselineCommit != null;
480
- const wtExists = existsSync(meta.worktreePath);
481
-
482
- const applyStatus = wtExists ? 'pending' : 'applied';
483
- const baselineCount = meta.baselineFiles?.length || 0;
484
- const baselineStatus = hasBaseline
485
- ? `dirty (${baselineCount} baseline file${baselineCount === 1 ? '' : 's'} protected)`
486
- : 'clean';
487
-
488
- // Worktree 最终状态
489
- const mode = meta.mode || 'worktree';
490
- let worktreeStatus;
491
- if (mode === 'native-worktree') {
492
- worktreeStatus = 'kept (external worktree)';
493
- } else if (mode === 'in-place-fallback') {
494
- worktreeStatus = 'none (in-place)';
495
- } else if (!wtExists) {
496
- worktreeStatus = 'cleaned';
497
- } else {
498
- worktreeStatus = 'exists';
499
- }
500
-
501
- lines.push(`Status: COMPLETED`);
502
- lines.push(`Steps: ${stepsCompleted} / ${stepsTotal}`);
503
- lines.push(`Baseline: ${baselineStatus}`);
504
- lines.push(`Apply: ${applyStatus}`);
505
- lines.push(`Worktree: ${worktreeStatus}`);
506
- }
507
-
508
- // --- Changed files ---
509
- // 从主工作区 diff 获取(worktree 已 apply)或从 worktree diff 获取
510
- if (meta && existsSync(meta.worktreePath)) {
511
- // worktree 还在,用 baselineCommit 或 baseHash 做 diff
512
- try {
513
- const diffBase = meta.baselineCommit || meta.baseHash;
514
- const { execSync: es } = require('child_process');
515
- const filesRaw = es(`git -C ${meta.worktreePath} diff --name-only ${diffBase} 2>/dev/null`, { encoding: 'utf8' });
516
- const files = filesRaw ? filesRaw.trim().split('\n').filter(Boolean) : [];
517
- if (files.length > 0) {
518
- lines.push(``);
519
- const maxShow = 10;
520
- const showFiles = files.slice(0, maxShow);
521
- const remain = files.length - maxShow;
522
- lines.push(`Changed Files (${files.length})`);
523
- showFiles.forEach(f => lines.push(` ${f}`));
524
- if (remain > 0) {
525
- lines.push(` ... ${remain} more`);
526
- }
527
- }
528
- } catch {}
529
- }
530
-
531
- // --- Agent Summary ---
532
- if (agentSummary) {
533
- lines.push(``);
534
- lines.push(`Agent Summary`);
535
- // 缩进每行,截断过长内容
536
- const maxLen = 200;
537
- const summary = agentSummary.length > maxLen
538
- ? agentSummary.slice(0, maxLen) + '...'
539
- : agentSummary;
540
- summary.split('\n').forEach(l => lines.push(` ${l}`));
541
- }
542
-
543
- // --- Next ---
544
- lines.push(``);
545
- lines.push(`Next`);
546
- lines.push(` → sillyspec run verify`);
547
-
548
- return lines.join('\n');
549
- }