sillyspec 3.18.6 → 3.19.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sillyspec",
3
- "version": "3.18.6",
3
+ "version": "3.19.1",
4
4
  "description": "SillySpec CLI — 流程状态机,让 AI 严格按步骤来",
5
5
  "icon": "logo.jpg",
6
6
  "homepage": "https://sillyspec.ppdmq.top/",
package/src/run.js CHANGED
@@ -772,6 +772,23 @@ async function outputStep(stageName, stepIndex, steps, cwd, changeName, dbProjec
772
772
  }
773
773
  }
774
774
 
775
+ // Execute: 注入 currentExecuteRunId(从 runtime 标记文件读取)
776
+ if (stageName === 'execute' && promptText.includes('{EXECUTE_RUN_ID}')) {
777
+ const execSpecBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
778
+ const runIdFile = join(execSpecBase, '.runtime', 'current-execute-run-id')
779
+ let runId = ''
780
+ try {
781
+ if (existsSync(runIdFile)) {
782
+ runId = readFileSync(runIdFile, 'utf8').trim()
783
+ }
784
+ } catch {}
785
+ if (!runId) {
786
+ const { generateExecuteRunId, getLatestExecuteRunId } = await import('./task-review.js')
787
+ runId = getLatestExecuteRunId(join(execSpecBase, '.runtime')) || generateExecuteRunId()
788
+ }
789
+ promptText = promptText.replace(/\{EXECUTE_RUN_ID\}/g, runId)
790
+ }
791
+
775
792
  // 注入模块上下文(brainstorm/plan/execute 阶段,基于 Module Context Index)
776
793
  if (['brainstorm', 'plan', 'execute'].includes(stageName) && projectName) {
777
794
  const effectiveSpecBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
@@ -1485,6 +1502,18 @@ async function runStage(pm, progress, stageName, cwd, changeName, skipApproval =
1485
1502
  }
1486
1503
  }
1487
1504
 
1505
+ // ── execute 阶段启动时固定 executeRunId ──
1506
+ let currentExecuteRunId = null
1507
+ if (stageName === 'execute') {
1508
+ const { generateExecuteRunId, getLatestExecuteRunId } = await import('./task-review.js')
1509
+ const execSpecBase = platformOpts?.specRoot || join(cwd, '.sillyspec')
1510
+ const runtimeRoot = join(execSpecBase, '.runtime')
1511
+ currentExecuteRunId = getLatestExecuteRunId(runtimeRoot) || generateExecuteRunId()
1512
+ // 写入 runtime 标记文件,确保整个 execute 生命周期内 runId 不变
1513
+ mkdirSync(runtimeRoot, { recursive: true })
1514
+ writeFileSync(join(runtimeRoot, 'current-execute-run-id'), currentExecuteRunId + '\n')
1515
+ }
1516
+
1488
1517
  // 自动探测 currentChange
1489
1518
  if (autoDetectChange(progress, cwd)) {
1490
1519
  progress.lastActive = new Date().toLocaleString('zh-CN', { hour12: false })
@@ -2592,6 +2621,56 @@ async function completeStep(pm, progress, stageName, cwd, outputText, inputText
2592
2621
  }
2593
2622
  }
2594
2623
  }
2624
+
2625
+ // ── Execute Task Review Gate:所有 task 必须有 review.json 且 verdict 通过 ──
2626
+ if (stageName === 'execute') {
2627
+ try {
2628
+ const { validateTaskReviews, printReviewResult, writeVerifyRequiredEvidence, getLatestExecuteRunId, generateExecuteRunId } = await import('./task-review.js')
2629
+ const effectiveSpecBase = platformOpts?.specRoot || specBase
2630
+ const planFile = resolveChangeDir(cwd, progress, platformOpts?.specRoot)
2631
+ const planPath = planFile ? join(planFile, 'plan.md') : null
2632
+
2633
+ if (planPath && existsSync(planPath)) {
2634
+ const planContent = readFileSync(planPath, 'utf8')
2635
+ const runtimeRoot = join(effectiveSpecBase, '.runtime')
2636
+
2637
+ // 找到 execute run id:优先从 runtime 目录找最新,否则生成新的
2638
+ let executeRunId = getLatestExecuteRunId(runtimeRoot)
2639
+ if (!executeRunId) {
2640
+ executeRunId = generateExecuteRunId()
2641
+ }
2642
+
2643
+ const reviewResult = validateTaskReviews({ planContent, runtimeRoot, executeRunId })
2644
+ printReviewResult(reviewResult)
2645
+
2646
+ if (!reviewResult.ok) {
2647
+ // Task review 校验失败,阻断 execute 完成
2648
+ // 检查是否存在 checkbox 已勾但 review 不通过的情况
2649
+ const uncheckedTasks = reviewResult.errors.filter(e => e.includes('缺少 review.json'))
2650
+ if (uncheckedTasks.length > 0) {
2651
+ console.error('\n⚠️ 部分任务已在 plan.md 中勾选,但 review.json 不存在。')
2652
+ console.error(' 请取消勾选这些任务的 checkbox,或补充对应的 review.json。')
2653
+ }
2654
+ progress.lastActive = new Date().toLocaleString('zh-CN',{hour12:false})
2655
+ await pm._write(cwd, progress, changeName)
2656
+ triggerSync(cwd, changeName, platformOpts)
2657
+ return { stageCompleted: false, currentIdx, nextPendingIdx: currentIdx }
2658
+ }
2659
+
2660
+ // cannot_verify 的 requiredEvidence 写入 change 目录,供 verify 阶段消费
2661
+ if (reviewResult.requiredEvidence.length > 0) {
2662
+ const evidencePath = writeVerifyRequiredEvidence(join(effectiveSpecBase, 'changes', changeName), reviewResult.requiredEvidence)
2663
+ if (evidencePath) {
2664
+ console.log(`📄 verify-required-evidence.json 已写入: ${evidencePath}`)
2665
+ console.log(' verify 阶段必须满足这些证据要求。')
2666
+ }
2667
+ }
2668
+ }
2669
+ } catch (e) {
2670
+ console.warn(`⚠️ Task Review Gate 异常: ${e.message}`)
2671
+ // 不阻断,但记录异常
2672
+ }
2673
+ }
2595
2674
  } else if (actualCompleted < actualTotal) {
2596
2675
  // 实际步骤未全部完成,跳过 validator(状态可能不同步)
2597
2676
  console.log(`\n⚠️ 阶段校验跳过:${actualTotal} 步中仅 ${actualCompleted} 步标记为已完成,可能存在状态不同步。如确认阶段已完成,请运行 --status 确认。`)
@@ -531,10 +531,40 @@ ${taskList}
531
531
  - 最后一个 Wave 完成后做一次全量编译验证
532
532
  - 用户明确要求编译时
533
533
  4. 每个任务完成后:
534
- - 勾选 plan.md / tasks.md 中对应任务的 checkbox
534
+ - **先写 review.json 再勾选 checkbox**(见下方 Task Review Gate)
535
535
  - 记录改动文件和测试结果
536
536
  5. 遇到 BLOCKED → 记录原因,选择:重试/跳过/停止
537
537
 
538
+ ### Task Review Gate(必须执行,不可跳过)
539
+
540
+ 每个子代理完成后、勾选 checkbox **之前**,你必须创建 task review。
541
+
542
+ **操作步骤:**
543
+ 1. 读取当前 task 的 git diff(从 task 开始到完成的变更)
544
+ 2. 对照 plan.md 中该 task 的描述和 tasks/task-XX.md(如果存在)检查实现是否符合要求
545
+ 3. 写入 review.json 文件
546
+ 4. **只有 review.json 写入成功后,才允许勾选 plan.md 中的 checkbox**
547
+
548
+ **review.json 路径:**
549
+
550
+ task-XX 对应:.sillyspec/.runtime/execute-runs/{EXECUTE_RUN_ID}/tasks/task-XX/review.json
551
+
552
+ 本 execute run 的固定 ID 是:{EXECUTE_RUN_ID}
553
+ **所有 task 的 review.json 必须使用这个 ID,不要自行创建新目录。**
554
+
555
+ **review.json 必填字段:**
556
+
557
+ { "schemaVersion": 1, "task": "task-XX", "base": "<git-base-commit>", "head": "<git-head-commit>",
558
+ "changedFiles": ["src/foo.js"], "specVerdict": "pass|fail|cannot_verify",
559
+ "qualityVerdict": "pass|fail|cannot_verify", "reviewerNotes": "评审说明",
560
+ "requiredEvidence": [] }
561
+
562
+ **评审铁律:**
563
+ - 不信任 implementer 自报结果,对照 diff 和 task brief 验证
564
+ - 只看当前 task 的 diff,不做全仓库漫游审查
565
+ - \`cannot_verify\` 只在确实无法验证且有待补充证据时使用,且 requiredEvidence 必须非空
566
+ - \`sillyspec run execute --done\` 会校验所有 task 的 review.json,缺失或 fail 会阻断完成
567
+
538
568
  ### 完成后
539
569
  1. 为每个后端 router task,扫描变更文件提取 API 端点 artifact:
540
570
  - 在变更文件中搜索所有 router 注册路径(@router.get/post/put/delete)
@@ -543,7 +573,6 @@ ${taskList}
543
573
  2. 运行 sillyspec run execute --done --input "用户原始反馈" --output "Wave ${waveIndex} 结果摘要"`
544
574
  }
545
575
 
546
-
547
576
  /**
548
577
  * 动态构建 execute 步骤列表
549
578
  * @param {string|null} planFilePath - plan 文件路径,null 则用默认 3 Wave
@@ -62,6 +62,14 @@ export const definition = {
62
62
  5. 加载代码规范:\`cat .sillyspec/docs/<project>/scan/CONVENTIONS.md 2>/dev/null\`
63
63
  6. 标注每个文件的存在/不存在状态
64
64
 
65
+ ### Execute Evidence 传递检查
66
+ 7. 检查 verify-required-evidence.json 是否存在(由 execute 阶段 Task Review Gate 写入)
67
+ - 路径:变更目录下的 verify-required-evidence.json
68
+ - 如果存在 → 读取其中的 requiredEvidence 列表,逐条验证是否已满足
69
+ - 每条 evidence 必须在 verify-result.md 中给出明确结论(satisfied / missing / partial)
70
+ - 如果有任何 evidence 为 missing → verify 结论不能为 PASS
71
+ - 如果文件不存在 → 表示 execute 阶段无 cannot_verify 任务,正常继续
72
+
65
73
  ### 模块文档加载
66
74
  7. 读取 \`.sillyspec/docs/<project>/modules/_module-map.yaml\`(不存在则跳过以下步骤)
67
75
  8. 根据 design.md 的文件变更清单匹配 _module-map.yaml 中的模块
@@ -0,0 +1,346 @@
1
+ /**
2
+ * SillySpec Task Review Gate — execute 阶段任务级评审校验
3
+ *
4
+ * execute 阶段每个 task 完成后,controller 必须写入 review.json。
5
+ * execute --done 时 CLI 硬校验:缺失 review 或 verdict 不通过则阻断。
6
+ *
7
+ * 目录结构:
8
+ * .sillyspec/.runtime/execute-runs/<runId>/tasks/<taskId>/review.json
9
+ */
10
+
11
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync } from 'fs'
12
+ import { join, resolve } from 'path'
13
+
14
+ // ── review.json schema version ──
15
+ export const REVIEW_SCHEMA_VERSION = 1
16
+
17
+ // ── 合法 verdict 枚举 ──
18
+ export const VALID_VERDICTS = ['pass', 'fail', 'cannot_verify']
19
+
20
+ /**
21
+ * 解析 plan.md 中的 task 列表
22
+ * @param {string} planContent - plan.md 文件内容
23
+ * @returns {string[]} task id 列表,如 ['task-01', 'task-02']
24
+ */
25
+ export function parseTaskIdsFromPlan(planContent) {
26
+ if (!planContent) return []
27
+ const ids = new Set()
28
+ const re = /^\s*[-*]\s*\[[ x]\]\s*task-(\d+)/gim
29
+ for (const m of planContent.matchAll(re)) {
30
+ ids.add(`task-${m[1].padStart(2, '0')}`)
31
+ }
32
+ return [...ids].sort()
33
+ }
34
+
35
+ /**
36
+ * 校验单个 review.json 文件
37
+ * @param {object} review - 解析后的 JSON 对象
38
+ * @returns {{ ok: boolean, errors: string[] }}
39
+ */
40
+ export function validateReviewSchema(review) {
41
+ const errors = []
42
+ if (!review || typeof review !== 'object') {
43
+ errors.push('review.json 不是有效 JSON 对象')
44
+ return { ok: false, errors }
45
+ }
46
+
47
+ if (review.schemaVersion !== REVIEW_SCHEMA_VERSION) {
48
+ errors.push(`schemaVersion 应为 ${REVIEW_SCHEMA_VERSION},实际为 ${review.schemaVersion}`)
49
+ }
50
+
51
+ if (!review.task || typeof review.task !== 'string') {
52
+ errors.push('缺少 task 字段(应为 "task-XX" 格式)')
53
+ }
54
+
55
+ if (!VALID_VERDICTS.includes(review.specVerdict)) {
56
+ errors.push(`specVerdict 无效:${review.specVerdict}(应为 ${VALID_VERDICTS.join('/')})`)
57
+ }
58
+
59
+ if (!VALID_VERDICTS.includes(review.qualityVerdict)) {
60
+ errors.push(`qualityVerdict 无效:${review.qualityVerdict}(应为 ${VALID_VERDICTS.join('/')})`)
61
+ }
62
+
63
+ // cannot_verify 必须提供 requiredEvidence
64
+ if (review.specVerdict === 'cannot_verify' || review.qualityVerdict === 'cannot_verify') {
65
+ if (!Array.isArray(review.requiredEvidence) || review.requiredEvidence.length === 0) {
66
+ errors.push('cannot_verify 的 verdict 必须提供非空的 requiredEvidence 数组')
67
+ }
68
+ }
69
+
70
+ // base/head 非空检查
71
+ if (!review.base || typeof review.base !== 'string') {
72
+ errors.push('缺少 base 字段(git commit hash)')
73
+ }
74
+ if (!review.head || typeof review.head !== 'string') {
75
+ errors.push('缺少 head 字段(git commit hash)')
76
+ }
77
+
78
+ return { ok: errors.length === 0, errors }
79
+ }
80
+
81
+ /**
82
+ * 读取单个 task 的 review.json
83
+ * @param {string} reviewPath - review.json 文件路径
84
+ * @returns {{ ok: boolean, review: object|null, errors: string[] }}
85
+ */
86
+ export function readReview(reviewPath) {
87
+ if (!existsSync(reviewPath)) {
88
+ return { ok: false, review: null, errors: ['review.json 不存在'] }
89
+ }
90
+
91
+ let raw
92
+ try {
93
+ raw = readFileSync(reviewPath, 'utf8')
94
+ } catch (e) {
95
+ return { ok: false, review: null, parseError: true, errors: [`review.json 读取失败: ${e.message}`] }
96
+ }
97
+
98
+ let parsed
99
+ try {
100
+ parsed = JSON.parse(raw)
101
+ } catch (e) {
102
+ // 文件存在但 JSON 非法:review 设为 null 但标记 parseError=true
103
+ return { ok: false, review: null, parseError: true, errors: [`review.json 解析失败: ${e.message}`] }
104
+ }
105
+
106
+ const schemaResult = validateReviewSchema(parsed)
107
+ if (!schemaResult.ok) {
108
+ return { ok: false, review: parsed, schemaError: true, errors: schemaResult.errors }
109
+ }
110
+
111
+ return { ok: true, review: parsed, errors: [] }
112
+ }
113
+
114
+ /**
115
+ * execute --done 时的 task review 总校验
116
+ *
117
+ * 规则:
118
+ * - 每个 plan task 必须有 review.json
119
+ * - specVerdict 或 qualityVerdict 为 fail → 整体 fail
120
+ * - specVerdict 或 qualityVerdict 为 cannot_verify → warning(requiredEvidence 非空)
121
+ * - cannot_verify + requiredEvidence 为空 → fail(agent 逃避判断)
122
+ * - cannot_verify 的 requiredEvidence 汇总到 requiredEvidence 字段,供 verify 阶段消费
123
+ *
124
+ * @param {object} opts
125
+ * @param {string} opts.planContent - plan.md 内容
126
+ * @param {string} opts.runtimeRoot - .sillyspec/.runtime 的绝对路径
127
+ * @param {string} opts.executeRunId - execute run id(如 'exec-2026-06-23-131400')
128
+ * @param {boolean} [opts.allowCannotVerify=true] - 是否允许 cannot_verify(默认允许,给 warning)
129
+ * @returns {{ ok: boolean, errors: string[], warnings: string[], requiredEvidence: Array<{task: string, verdict: string, evidence: string[]}> }}
130
+ */
131
+ export function validateTaskReviews(opts) {
132
+ const { planContent, runtimeRoot, executeRunId, allowCannotVerify = true } = opts
133
+
134
+ const taskIds = parseTaskIdsFromPlan(planContent)
135
+
136
+ // 如果 plan 里没有 task,跳过校验(向后兼容)
137
+ if (taskIds.length === 0) {
138
+ return { ok: true, errors: [], warnings: [], requiredEvidence: [] }
139
+ }
140
+
141
+ const errors = []
142
+ const warnings = []
143
+ const requiredEvidence = []
144
+
145
+ for (const taskId of taskIds) {
146
+ const reviewDir = join(runtimeRoot, 'execute-runs', executeRunId, 'tasks', taskId)
147
+ const reviewPath = join(reviewDir, 'review.json')
148
+
149
+ const result = readReview(reviewPath)
150
+
151
+ if (!result.ok) {
152
+ if (result.parseError) {
153
+ // review.json 存在但 JSON 非法
154
+ errors.push(`${taskId}: review.json 解析失败 — ${result.errors.join('; ')}`)
155
+ } else if (result.schemaError) {
156
+ // review.json 存在且 JSON 合法,但 schema 校验失败
157
+ errors.push(`${taskId}: review.json 校验失败 — ${result.errors.join('; ')}`)
158
+ } else {
159
+ // review.json 不存在
160
+ errors.push(`${taskId}: 缺少 review.json — task 未经过评审`)
161
+ }
162
+ continue
163
+ }
164
+
165
+ const review = result.review
166
+
167
+ // 检查 review.task 是否与 plan 中的 taskId 一致
168
+ if (review.task && review.task !== taskId) {
169
+ errors.push(`${taskId}: review.json 中的 task 字段为 "${review.task}",与 plan 不一致(应为 "${taskId}")— agent 可能复制模板未修改`)
170
+ continue
171
+ }
172
+
173
+ // 检查 fail verdict
174
+ if (review.specVerdict === 'fail' || review.qualityVerdict === 'fail') {
175
+ errors.push(`${taskId}: review 未通过 — spec: ${review.specVerdict}, quality: ${review.qualityVerdict}`)
176
+ if (review.reviewerNotes) {
177
+ errors.push(`${taskId}: ${review.reviewerNotes}`)
178
+ }
179
+ continue
180
+ }
181
+
182
+ // 检查 cannot_verify
183
+ if (review.specVerdict === 'cannot_verify' || review.qualityVerdict === 'cannot_verify') {
184
+ if (!allowCannotVerify) {
185
+ errors.push(`${taskId}: cannot_verify 不被允许 — 必须提供评审结果`)
186
+ continue
187
+ }
188
+
189
+ if (review.requiredEvidence && review.requiredEvidence.length > 0) {
190
+ const verdicts = []
191
+ if (review.specVerdict === 'cannot_verify') verdicts.push('spec')
192
+ if (review.qualityVerdict === 'cannot_verify') verdicts.push('quality')
193
+ warnings.push(`${taskId}: ${verdicts.join('+')}=cannot_verify,requiredEvidence 必须在 verify 阶段满足`)
194
+ requiredEvidence.push({
195
+ task: taskId,
196
+ verdict: verdicts.join('+'),
197
+ evidence: review.requiredEvidence,
198
+ })
199
+ } else {
200
+ // cannot_verify + 空 requiredEvidence = agent 逃避判断
201
+ errors.push(`${taskId}: cannot_verify 但 requiredEvidence 为空 — 这是无效评审`)
202
+ }
203
+ }
204
+ }
205
+
206
+ // 额外检查:扫描 execute-runs/<runId>/tasks/ 下是否有 plan 里没有的 task review
207
+ // (agent 可能写错了 task id)
208
+ try {
209
+ const tasksDir = join(runtimeRoot, 'execute-runs', executeRunId, 'tasks')
210
+ if (existsSync(tasksDir)) {
211
+ const taskDirs = readdirSync(tasksDir, { withFileTypes: true })
212
+ .filter(e => e.isDirectory())
213
+ .map(e => e.name)
214
+ const taskIdSet = new Set(taskIds)
215
+ for (const dirName of taskDirs) {
216
+ if (!taskIdSet.has(dirName) && existsSync(join(tasksDir, dirName, 'review.json'))) {
217
+ warnings.push(`${dirName}: 存在 review.json 但不在 plan.md 的 task 列表中(可能是多余文件)`)
218
+ }
219
+ }
220
+ }
221
+ } catch (e) {
222
+ warnings.push(`task review extra-check 异常: ${e.message}`)
223
+ }
224
+
225
+ return {
226
+ ok: errors.length === 0,
227
+ errors,
228
+ warnings,
229
+ requiredEvidence,
230
+ }
231
+ }
232
+
233
+ /**
234
+ * 将 cannot_verify 的 requiredEvidence 写入 change 目录
235
+ * 供 verify 阶段消费
236
+ *
237
+ * @param {string} changeDir - 变更目录(.sillyspec/changes/<name>)
238
+ * @param {Array<{task: string, verdict: string, evidence: string[]}>} requiredEvidence
239
+ * @returns {string|null} 写入的文件路径,null 表示无需写入
240
+ */
241
+ export function writeVerifyRequiredEvidence(changeDir, requiredEvidence) {
242
+ if (!requiredEvidence || requiredEvidence.length === 0) return null
243
+
244
+ const filePath = join(changeDir, 'verify-required-evidence.json')
245
+ const data = {
246
+ generatedAt: new Date().toISOString(),
247
+ schemaVersion: 1,
248
+ items: requiredEvidence,
249
+ }
250
+
251
+ mkdirSync(changeDir, { recursive: true })
252
+ writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n')
253
+
254
+ return filePath
255
+ }
256
+
257
+ /**
258
+ * 生成 execute run id
259
+ * @returns {string} 如 'exec-2026-06-23-131400'
260
+ */
261
+ export function generateExecuteRunId() {
262
+ const now = new Date()
263
+ const pad = (n) => String(n).padStart(2, '0')
264
+ return `exec-${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`
265
+ }
266
+
267
+ /**
268
+ * 获取当前(或最新)execute run id
269
+ * 从 runtime 目录下查找 execute-runs/ 子目录
270
+ *
271
+ * @param {string} runtimeRoot - .sillyspec/.runtime 路径
272
+ * @returns {string|null} 最新 run id,null 表示无任何 run
273
+ */
274
+ /**
275
+ * 获取当前 execute run id
276
+ * 优先从 current-execute-run-id 标记文件读取(execute 阶段启动时写入),
277
+ * fallback 到 execute-runs/ 下最新的 exec- 前缀目录。
278
+ *
279
+ * @param {string} runtimeRoot - .sillyspec/.runtime 路径
280
+ * @returns {string|null} 当前 run id,null 表示无任何 run
281
+ */
282
+ export function getLatestExecuteRunId(runtimeRoot) {
283
+ // 优先读标记文件(execute 阶段启动时由 run.js 写入,生命周期内不变)
284
+ const markerPath = join(runtimeRoot, 'current-execute-run-id')
285
+ try {
286
+ if (existsSync(markerPath)) {
287
+ const content = readFileSync(markerPath, 'utf8').trim()
288
+ if (content) return content
289
+ }
290
+ } catch {}
291
+
292
+ // fallback:扫描 execute-runs/ 目录
293
+ const runsDir = join(runtimeRoot, 'execute-runs')
294
+ if (!existsSync(runsDir)) return null
295
+
296
+ try {
297
+ const entries = readdirSync(runsDir, { withFileTypes: true })
298
+ .filter(e => e.isDirectory() && e.name.startsWith('exec-'))
299
+ .map(e => e.name)
300
+ .sort()
301
+ .reverse()
302
+ return entries[0] || null
303
+ } catch {
304
+ return null
305
+ }
306
+ }
307
+
308
+ /**
309
+ * 确保 task review 目录存在
310
+ * @param {string} runtimeRoot
311
+ * @param {string} executeRunId
312
+ * @param {string} taskId
313
+ * @returns {string} task review 目录路径
314
+ */
315
+ export function ensureTaskReviewDir(runtimeRoot, executeRunId, taskId) {
316
+ const dir = join(runtimeRoot, 'execute-runs', executeRunId, 'tasks', taskId)
317
+ mkdirSync(dir, { recursive: true })
318
+ return dir
319
+ }
320
+
321
+ /**
322
+ * 打印校验结果
323
+ * @param {{ ok: boolean, errors: string[], warnings: string[], requiredEvidence: Array }} result
324
+ */
325
+ export function printReviewResult(result) {
326
+ if (result.ok && result.warnings.length === 0) {
327
+ console.log('\n✅ Task Review Gate — 所有任务评审通过')
328
+ return
329
+ }
330
+
331
+ if (result.errors.length > 0) {
332
+ console.error('\n🚫 Task Review Gate — FAILED')
333
+ for (const err of result.errors) {
334
+ console.error(` - ${err}`)
335
+ }
336
+ console.error('\n 提示:为缺失/失败的任务补充 review.json,然后重新 --done')
337
+ }
338
+
339
+ if (result.warnings.length > 0) {
340
+ console.warn('\n⚠️ Task Review Gate — WARNING')
341
+ for (const w of result.warnings) {
342
+ console.warn(` - ${w}`)
343
+ }
344
+ console.warn('\n cannot_verify 的 requiredEvidence 将在 verify 阶段校验')
345
+ }
346
+ }
package/src/worktree.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
  import { execSync } from 'child_process';
12
- import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, readdirSync } from 'fs';
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync } from 'fs';
13
13
  import { join, resolve, dirname } from 'path';
14
14
  import { createHash } from 'crypto';
15
15
 
@@ -120,7 +120,43 @@ export function isGitWorktreeSupported(cwd = process.cwd()) {
120
120
  export class WorktreeManager {
121
121
  constructor({ cwd, worktreeDir } = {}) {
122
122
  this.cwd = cwd || process.cwd();
123
- this.worktreeBase = worktreeDir || resolve(this.cwd, WORKTREES_REL);
123
+
124
+ // worktreeBase 必须固定到主仓库路径,不能跟着 cwd 变化。
125
+ // native-worktree 模式下 cwd 是 worktree 子目录,用 cwd 推导 worktreeBase
126
+ // 会导致 meta 写入 worktree 内部路径,worktree 内再次执行时找不到。
127
+ // 解决:用 git rev-parse --git-common-dir 反推主仓库路径。
128
+ if (worktreeDir) {
129
+ this.worktreeBase = worktreeDir;
130
+ } else {
131
+ this.worktreeBase = resolve(this._resolveMainRepoRoot(), WORKTREES_REL);
132
+ }
133
+ }
134
+
135
+ /**
136
+ * 解析当前 git 环境对应的主仓库根目录
137
+ * 在主仓库内执行:返回 cwd 自身
138
+ * 在 linked worktree 内执行:返回 git-common-dir 的父目录(即主仓库 .git 所在地)
139
+ * @private
140
+ */
141
+ _resolveMainRepoRoot() {
142
+ try {
143
+ // git-common-dir 在主仓库内 = <main>/.git
144
+ // 在 linked worktree 内 = <main>/.git(git 共享 .git 目录)
145
+ const commonDir = gitQuiet(this.cwd, 'rev-parse --git-common-dir');
146
+ if (!commonDir) return this.cwd;
147
+
148
+ // commonDir 应该是 <main-repo>/.git
149
+ // dirname(commonDir) = <main-repo>
150
+ if (existsSync(commonDir)) {
151
+ const st = statSync(commonDir);
152
+ if (st.isDirectory()) {
153
+ return dirname(commonDir);
154
+ }
155
+ }
156
+ } catch (e) {
157
+ // 静默 fallback:主仓库内执行或 git 异常
158
+ }
159
+ return this.cwd;
124
160
  }
125
161
 
126
162
  /**
@@ -167,11 +203,19 @@ export class WorktreeManager {
167
203
  if (isolation.inWorktree) {
168
204
  // 已在 linked worktree 中,复用当前目录作为 worktree 路径
169
205
  console.log(`ℹ️ 已在 linked worktree 中(git-dir: ${isolation.gitDir}),复用当前隔离环境。`);
170
- return this._createInPlaceMeta(name, {
206
+
207
+ // 幂等守卫:meta 已存在时不重新 overlay baseline
208
+ const existingMeta = this.getMeta(name)
209
+ if (existingMeta) {
210
+ return { branch: existingMeta.branch, worktreePath: existingMeta.worktreePath, baseHash: existingMeta.baseHash, mode: existingMeta.mode }
211
+ }
212
+
213
+ // meta 不存在但已在 worktree 内:可能是 meta 被损坏/误删。
214
+ // 绝对禁止 overlay baseline(source === target 会冲突),
215
+ // 只恢复 meta 引用,不触碰文件系统。
216
+ return this._recoverNativeWorktreeMeta(name, {
171
217
  worktreePath: this.cwd,
172
218
  branch: gitQuiet(this.cwd, 'symbolic-ref --short HEAD') || 'detached',
173
- mode: 'native-worktree',
174
- base,
175
219
  });
176
220
  }
177
221
 
@@ -304,12 +348,76 @@ export class WorktreeManager {
304
348
  return { branch, worktreePath, baseHash, mode: meta.mode };
305
349
  }
306
350
 
351
+ /**
352
+ * native-worktree 模式下恢复 meta 引用
353
+ * 当 meta.json 被损坏/误删时,只重建 meta 文件,不触碰文件系统(不 overlay)
354
+ * @private
355
+ */
356
+ _recoverNativeWorktreeMeta(name, { worktreePath, branch }) {
357
+ const baseHash = gitQuiet(worktreePath, 'rev-parse HEAD') || null
358
+ const meta = {
359
+ changeName: name,
360
+ branch: branch || BRANCH_PREFIX + name,
361
+ baseBranch: branch,
362
+ baseHash,
363
+ actualBaseHash: baseHash,
364
+ createdAt: new Date().toISOString(),
365
+ worktreePath,
366
+ mode: 'native-worktree',
367
+ baselineFiles: [],
368
+ baselineCommit: null,
369
+ baselineHash: null,
370
+ recoveredAt: new Date().toISOString(),
371
+ recoveryNote: 'meta was missing in native-worktree; recovered without baseline overlay',
372
+ }
373
+ if (!existsSync(this.worktreeBase)) mkdirSync(this.worktreeBase, { recursive: true })
374
+ const metaDir = join(this.worktreeBase, name)
375
+ if (!existsSync(metaDir)) mkdirSync(metaDir, { recursive: true })
376
+ writeFileSync(join(metaDir, META_FILE), JSON.stringify(meta, null, 2) + '\n')
377
+ console.log(`🔗 native-worktree meta 已恢复: ${metaDir}/meta.json`)
378
+ return { branch: meta.branch, worktreePath, baseHash, mode: meta.mode }
379
+ }
380
+
307
381
  /**
308
382
  * 创建 in-place 模式的 meta.json(降级路径)
309
383
  * 不创建 git worktree,直接在当前目录记录 baseline 并写入 meta
310
384
  * @private
311
385
  */
312
386
  _createInPlaceMeta(name, { worktreePath, branch, baseBranch, baseHash, mode } = {}) {
387
+ // 幂等守卫:meta 已存在时不重新创建(避免 overlay baseline 和已有改动冲突)
388
+ const existingMeta = this.getMeta(name)
389
+ if (existingMeta) {
390
+ return { branch: existingMeta.branch, worktreePath: existingMeta.worktreePath, baseHash: existingMeta.baseHash, mode: existingMeta.mode }
391
+ }
392
+
393
+ // 硬规则:禁止 self-overlay(source 和 target 相同时 overlay 必然冲突)
394
+ const resolvedSource = resolve(this.cwd)
395
+ const resolvedTarget = resolve(worktreePath)
396
+ if (resolvedSource === resolvedTarget) {
397
+ console.warn('⚠️ 跳过 baseline overlay:当前目录与目标目录相同(native-worktree 或 in-place 模式)')
398
+ // 写 meta 但不 overlay
399
+ baseBranch = baseBranch || gitQuiet(this.cwd, 'symbolic-ref --short HEAD') || gitQuiet(this.cwd, 'rev-parse HEAD')
400
+ baseHash = baseHash || git(this.cwd, 'rev-parse HEAD')
401
+ const meta = {
402
+ changeName: name,
403
+ branch: branch || BRANCH_PREFIX + name,
404
+ baseBranch,
405
+ baseHash,
406
+ actualBaseHash: gitQuiet(worktreePath, 'rev-parse HEAD') || baseHash,
407
+ createdAt: new Date().toISOString(),
408
+ worktreePath,
409
+ mode: mode || 'in-place-fallback',
410
+ baselineFiles: [],
411
+ baselineCommit: null,
412
+ baselineHash: null,
413
+ }
414
+ if (!existsSync(this.worktreeBase)) mkdirSync(this.worktreeBase, { recursive: true })
415
+ const metaDir = join(this.worktreeBase, name)
416
+ if (!existsSync(metaDir)) mkdirSync(metaDir, { recursive: true })
417
+ writeFileSync(join(metaDir, META_FILE), JSON.stringify(meta, null, 2) + '\n')
418
+ return { branch: meta.branch, worktreePath, baseHash, mode: meta.mode }
419
+ }
420
+
313
421
  // 解析 base
314
422
  if (!baseHash) {
315
423
  baseBranch = baseBranch || gitQuiet(this.cwd, 'symbolic-ref --short HEAD') || gitQuiet(this.cwd, 'rev-parse HEAD');
@@ -0,0 +1,188 @@
1
+ /**
2
+ * worktree native-worktree overlay regression tests
3
+ *
4
+ * 验证 Bug 1 + Bug 2 修复:
5
+ * 1. worktreeBase 固定到主仓库路径,不跟着 cwd 变化
6
+ * 2. 禁止 self-overlay(source === target 时)
7
+ * 3. native-worktree meta 缺失时 recover,不 overlay
8
+ * 4. meta 已存在时幂等返回,不重建
9
+ */
10
+
11
+ import fs from 'fs'
12
+ import path from 'path'
13
+ import os from 'os'
14
+ import { execSync } from 'child_process'
15
+
16
+ // ── Test 1: _resolveMainRepoRoot 在主仓库内返回 cwd ──
17
+
18
+ async function test1_mainRepoRoot() {
19
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-'))
20
+ execSync('git init', { cwd: d, stdio: 'pipe' })
21
+ execSync('git config user.email "test@test.com"', { cwd: d, stdio: 'pipe' })
22
+ execSync('git config user.name "test"', { cwd: d, stdio: 'pipe' })
23
+ execSync('git commit --allow-empty -m "init"', { cwd: d, stdio: 'pipe' })
24
+
25
+ // Add .gitignore to allow worktreeBase path
26
+ fs.mkdirSync(path.join(d, '.sillyspec'), { recursive: true })
27
+ fs.writeFileSync(path.join(d, '.gitignore'), '.sillyspec/\n')
28
+
29
+ const { WorktreeManager } = await import('../src/worktree.js')
30
+ const wm = new WorktreeManager({ cwd: d })
31
+ const root = wm._resolveMainRepoRoot()
32
+ console.assert(root === d, `Test 1 FAIL: expected ${d}, got ${root}`)
33
+ console.log('✅ Test 1: main repo root resolves to cwd')
34
+
35
+ fs.rmSync(d, { recursive: true })
36
+ }
37
+
38
+ // ── Test 2: native-worktree 检测 + 幂等守卫 ──
39
+
40
+ async function test2_nativeWorktreeIdempotent() {
41
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-'))
42
+ execSync('git init', { cwd: d, stdio: 'pipe' })
43
+ execSync('git config user.email "test@test.com"', { cwd: d, stdio: 'pipe' })
44
+ execSync('git config user.name "test"', { cwd: d, stdio: 'pipe' })
45
+ execSync('git commit --allow-empty -m "init"', { cwd: d, stdio: 'pipe' })
46
+
47
+ const wtDir = path.join(d, 'wt')
48
+ execSync(`git worktree add ${wtDir} -b test-branch`, { cwd: d, stdio: 'pipe' })
49
+
50
+ // wtDir is a linked worktree
51
+ const { WorktreeManager } = await import('../src/worktree.js')
52
+
53
+ // First: create meta from inside worktree (simulating native-worktree mode)
54
+ const wm1 = new WorktreeManager({ cwd: wtDir })
55
+ // This simulates what happens when Claude Code runs in the worktree
56
+ // and SillySpec calls create() — detectIsolation should return inWorktree=true
57
+ // and meta should be written to main repo's worktreeBase, not worktree's
58
+
59
+ // Verify worktreeBase points to main repo
60
+ const expectedBase = path.join(d, '.sillyspec', '.runtime', 'worktrees')
61
+ console.assert(wm1.worktreeBase === expectedBase, `Test 2 FAIL: worktreeBase=${wm1.worktreeBase}, expected=${expectedBase}`)
62
+ console.log('✅ Test 2: worktreeBase fixed to main repo path')
63
+
64
+ fs.rmSync(d, { recursive: true })
65
+ }
66
+
67
+ // ── Test 3: self-overlay 禁止 ──
68
+
69
+ async function test3_selfOverlayBlocked() {
70
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-'))
71
+ execSync('git init', { cwd: d, stdio: 'pipe' })
72
+ execSync('git config user.email "test@test.com"', { cwd: d, stdio: 'pipe' })
73
+ execSync('git config user.name "test"', { cwd: d, stdio: 'pipe' })
74
+ execSync('git commit --allow-empty -m "init"', { cwd: d, stdio: 'pipe' })
75
+ fs.mkdirSync(path.join(d, '.sillyspec'), { recursive: true })
76
+ fs.writeFileSync(path.join(d, '.gitignore'), '.sillyspec/\n')
77
+
78
+ const { WorktreeManager } = await import('../src/worktree.js')
79
+ const wm = new WorktreeManager({ cwd: d })
80
+
81
+ // Create with in-place-fallback mode (source === target)
82
+ const result = wm._createInPlaceMeta('test-change', {
83
+ worktreePath: d,
84
+ branch: 'test-branch',
85
+ mode: 'in-place-fallback',
86
+ })
87
+
88
+ console.assert(result.mode === 'in-place-fallback', `Test 3 FAIL: mode=${result.mode}`)
89
+ // 返回值不包含 baselineFiles(是简化的返回结构),验证 meta 文件本身
90
+ const meta3 = wm.getMeta('test-change')
91
+ console.assert(meta3 && meta3.baselineFiles.length === 0, `Test 3 FAIL: meta baselineFiles should be empty`)
92
+ console.log('✅ Test 3: self-overlay blocked, baselineFiles empty')
93
+
94
+ fs.rmSync(d, { recursive: true })
95
+ }
96
+
97
+ // ── Test 4: meta 幂等,不重复 overlay ──
98
+
99
+ async function test4_metaIdempotent() {
100
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-'))
101
+ execSync('git init', { cwd: d, stdio: 'pipe' })
102
+ execSync('git config user.email "test@test.com"', { cwd: d, stdio: 'pipe' })
103
+ execSync('git config user.name "test"', { cwd: d, stdio: 'pipe' })
104
+ execSync('git commit --allow-empty -m "init"', { cwd: d, stdio: 'pipe' })
105
+ fs.mkdirSync(path.join(d, '.sillyspec'), { recursive: true })
106
+ fs.writeFileSync(path.join(d, '.gitignore'), '.sillyspec/\n')
107
+
108
+ const { WorktreeManager } = await import('../src/worktree.js')
109
+ const wm = new WorktreeManager({ cwd: d })
110
+
111
+ // First create
112
+ const r1 = wm._createInPlaceMeta('test-change', {
113
+ worktreePath: d,
114
+ branch: 'test-branch',
115
+ mode: 'in-place-fallback',
116
+ })
117
+
118
+ // Second create (should return existing, not re-overlay)
119
+ const r2 = wm._createInPlaceMeta('test-change', {
120
+ worktreePath: d,
121
+ branch: 'test-branch',
122
+ mode: 'in-place-fallback',
123
+ })
124
+
125
+ console.assert(r1.baseHash === r2.baseHash, `Test 4 FAIL: hashes differ`)
126
+ console.log('✅ Test 4: _createInPlaceMeta idempotent')
127
+
128
+ fs.rmSync(d, { recursive: true })
129
+ }
130
+
131
+ // ── Test 5: native-worktree meta 恢复 ──
132
+
133
+ async function test5_nativeRecovery() {
134
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-'))
135
+ execSync('git init', { cwd: d, stdio: 'pipe' })
136
+ execSync('git config user.email "test@test.com"', { cwd: d, stdio: 'pipe' })
137
+ execSync('git config user.name "test"', { cwd: d, stdio: 'pipe' })
138
+ execSync('git commit --allow-empty -m "init"', { cwd: d, stdio: 'pipe' })
139
+
140
+ const wtDir = path.join(d, 'wt')
141
+ execSync(`git worktree add ${wtDir} -b test-branch`, { cwd: d, stdio: 'pipe' })
142
+
143
+ const { WorktreeManager } = await import('../src/worktree.js')
144
+ const wm = new WorktreeManager({ cwd: wtDir })
145
+
146
+ // Simulate meta missing in native-worktree (should recover, not overlay)
147
+ const result = wm._recoverNativeWorktreeMeta('test-change', {
148
+ worktreePath: wtDir,
149
+ branch: 'test-branch',
150
+ })
151
+
152
+ console.assert(result.mode === 'native-worktree', `Test 5 FAIL: mode=${result.mode}`)
153
+ // 返回值不包含 baselineFiles,验证 meta 文件本身
154
+ const meta5 = wm.getMeta('test-change')
155
+ console.assert(meta5 && meta5.baselineFiles.length === 0, `Test 5 FAIL: meta baselineFiles should be empty`)
156
+
157
+ // Verify meta is readable now
158
+ const meta = wm.getMeta('test-change')
159
+ console.assert(meta !== null, `Test 5 FAIL: meta should exist after recovery`)
160
+ console.assert(meta.mode === 'native-worktree', `Test 5 FAIL: meta.mode=${meta.mode}`)
161
+ console.log('✅ Test 5: native-worktree meta recovery without overlay')
162
+
163
+ fs.rmSync(d, { recursive: true })
164
+ }
165
+
166
+ // ── Run all ──
167
+
168
+ const tests = [
169
+ ['main repo root', test1_mainRepoRoot],
170
+ ['native worktree worktreeBase', test2_nativeWorktreeIdempotent],
171
+ ['self-overlay blocked', test3_selfOverlayBlocked],
172
+ ['meta idempotent', test4_metaIdempotent],
173
+ ['native recovery', test5_nativeRecovery],
174
+ ]
175
+
176
+ let passed = 0, failed = 0
177
+ for (const [name, fn] of tests) {
178
+ try {
179
+ await fn()
180
+ passed++
181
+ } catch (e) {
182
+ console.log(`❌ ${name}: ${e.message}`)
183
+ failed++
184
+ }
185
+ }
186
+
187
+ console.log(`\n${passed}/${tests.length} passed`)
188
+ if (failed) process.exit(1)