sillyspec 3.27.5 → 3.27.6

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 (194) hide show
  1. package/.worktrees/8d2d0392/.claude/skills/sillyspec-archive/SKILL.md +87 -0
  2. package/.worktrees/8d2d0392/.claude/skills/sillyspec-auto/SKILL.md +93 -0
  3. package/.worktrees/8d2d0392/.claude/skills/sillyspec-brainstorm/SKILL.md +114 -0
  4. package/.worktrees/8d2d0392/.claude/skills/sillyspec-commit/SKILL.md +67 -0
  5. package/.worktrees/8d2d0392/.claude/skills/sillyspec-continue/SKILL.md +47 -0
  6. package/.worktrees/8d2d0392/.claude/skills/sillyspec-doctor/SKILL.md +76 -0
  7. package/.worktrees/8d2d0392/.claude/skills/sillyspec-execute/SKILL.md +214 -0
  8. package/.worktrees/8d2d0392/.claude/skills/sillyspec-explore/SKILL.md +102 -0
  9. package/.worktrees/8d2d0392/.claude/skills/sillyspec-export/SKILL.md +57 -0
  10. package/.worktrees/8d2d0392/.claude/skills/sillyspec-init/SKILL.md +177 -0
  11. package/.worktrees/8d2d0392/.claude/skills/sillyspec-knowledge/SKILL.md +270 -0
  12. package/.worktrees/8d2d0392/.claude/skills/sillyspec-plan/SKILL.md +156 -0
  13. package/.worktrees/8d2d0392/.claude/skills/sillyspec-propose/SKILL.md +87 -0
  14. package/.worktrees/8d2d0392/.claude/skills/sillyspec-quick/SKILL.md +116 -0
  15. package/.worktrees/8d2d0392/.claude/skills/sillyspec-resume/SKILL.md +70 -0
  16. package/.worktrees/8d2d0392/.claude/skills/sillyspec-scan/SKILL.md +79 -0
  17. package/.worktrees/8d2d0392/.claude/skills/sillyspec-state/SKILL.md +64 -0
  18. package/.worktrees/8d2d0392/.claude/skills/sillyspec-status/SKILL.md +54 -0
  19. package/.worktrees/8d2d0392/.claude/skills/sillyspec-verify/SKILL.md +87 -0
  20. package/.worktrees/8d2d0392/.claude/skills/sillyspec-workspace/SKILL.md +175 -0
  21. package/.worktrees/8d2d0392/.claude/skills/verify-per-user/SKILL.md +6 -0
  22. package/.worktrees/8d2d0392/.gitattributes +2 -0
  23. package/.worktrees/8d2d0392/.husky/pre-push +20 -0
  24. package/.worktrees/8d2d0392/README.md +203 -0
  25. package/.worktrees/8d2d0392/SKILL.md +91 -0
  26. package/.worktrees/8d2d0392/architecture-analysis.md +448 -0
  27. package/.worktrees/8d2d0392/bin/sillyspec.js +2 -0
  28. package/.worktrees/8d2d0392/eval/README.md +86 -0
  29. package/.worktrees/8d2d0392/eval/eval.config.json +28 -0
  30. package/.worktrees/8d2d0392/eval/lib/adapters/cli.mjs +63 -0
  31. package/.worktrees/8d2d0392/eval/lib/adapters/dryrun.mjs +27 -0
  32. package/.worktrees/8d2d0392/eval/lib/config.mjs +82 -0
  33. package/.worktrees/8d2d0392/eval/lib/db.mjs +76 -0
  34. package/.worktrees/8d2d0392/eval/lib/report.mjs +120 -0
  35. package/.worktrees/8d2d0392/eval/lib/runner.mjs +157 -0
  36. package/.worktrees/8d2d0392/eval/lib/tasks.mjs +73 -0
  37. package/.worktrees/8d2d0392/eval/lib/util.mjs +107 -0
  38. package/.worktrees/8d2d0392/eval/lib/workdir.mjs +30 -0
  39. package/.worktrees/8d2d0392/eval/run.mjs +83 -0
  40. package/.worktrees/8d2d0392/eval/tasks/001-slugify/files/package.json +6 -0
  41. package/.worktrees/8d2d0392/eval/tasks/001-slugify/solution/src/slugify.mjs +26 -0
  42. package/.worktrees/8d2d0392/eval/tasks/001-slugify/task.json +6 -0
  43. package/.worktrees/8d2d0392/eval/tasks/001-slugify/verify.mjs +28 -0
  44. package/.worktrees/8d2d0392/eval/tasks/002-each-day/files/package.json +6 -0
  45. package/.worktrees/8d2d0392/eval/tasks/002-each-day/files/src/dates.mjs +4 -0
  46. package/.worktrees/8d2d0392/eval/tasks/002-each-day/solution/src/dates.mjs +30 -0
  47. package/.worktrees/8d2d0392/eval/tasks/002-each-day/task.json +6 -0
  48. package/.worktrees/8d2d0392/eval/tasks/002-each-day/verify.mjs +31 -0
  49. package/.worktrees/8d2d0392/eval/tasks/003-word-report/files/data/notes.txt +5 -0
  50. package/.worktrees/8d2d0392/eval/tasks/003-word-report/files/package.json +6 -0
  51. package/.worktrees/8d2d0392/eval/tasks/003-word-report/solution/bin/report.mjs +36 -0
  52. package/.worktrees/8d2d0392/eval/tasks/003-word-report/task.json +6 -0
  53. package/.worktrees/8d2d0392/eval/tasks/003-word-report/verify.mjs +38 -0
  54. package/.worktrees/8d2d0392/logo.jpg +0 -0
  55. package/.worktrees/8d2d0392/package-lock.json +977 -0
  56. package/.worktrees/8d2d0392/package.json +41 -0
  57. package/.worktrees/8d2d0392/packages/dashboard/dist/assets/index-Bq_Z2hne.js +7446 -0
  58. package/.worktrees/8d2d0392/packages/dashboard/dist/assets/index-O2W5RV4z.css +1 -0
  59. package/.worktrees/8d2d0392/packages/dashboard/dist/favicon.jpg +0 -0
  60. package/.worktrees/8d2d0392/packages/dashboard/dist/index.html +16 -0
  61. package/.worktrees/8d2d0392/packages/dashboard/dist/logo.jpg +0 -0
  62. package/.worktrees/8d2d0392/packages/dashboard/dist/prototype-dashboard.html +836 -0
  63. package/.worktrees/8d2d0392/packages/dashboard/dist/prototype-overview.html +256 -0
  64. package/.worktrees/8d2d0392/packages/dashboard/package.json +25 -0
  65. package/.worktrees/8d2d0392/packages/dashboard/server/executor.js +95 -0
  66. package/.worktrees/8d2d0392/packages/dashboard/server/index.js +679 -0
  67. package/.worktrees/8d2d0392/packages/dashboard/server/parser.js +526 -0
  68. package/.worktrees/8d2d0392/packages/dashboard/server/watcher.js +357 -0
  69. package/.worktrees/8d2d0392/src/agent-session-log.js +803 -0
  70. package/.worktrees/8d2d0392/src/change-list.js +290 -0
  71. package/.worktrees/8d2d0392/src/change-risk-profile.js +339 -0
  72. package/.worktrees/8d2d0392/src/check-primitives.js +65 -0
  73. package/.worktrees/8d2d0392/src/classify-change.js +109 -0
  74. package/.worktrees/8d2d0392/src/commit-suggest.js +202 -0
  75. package/.worktrees/8d2d0392/src/config-cat.js +88 -0
  76. package/.worktrees/8d2d0392/src/config-schema.js +328 -0
  77. package/.worktrees/8d2d0392/src/constants.js +97 -0
  78. package/.worktrees/8d2d0392/src/contract-matrix.js +533 -0
  79. package/.worktrees/8d2d0392/src/datetime.js +20 -0
  80. package/.worktrees/8d2d0392/src/db-engine.js +55 -0
  81. package/.worktrees/8d2d0392/src/db.js +381 -0
  82. package/.worktrees/8d2d0392/src/decision-distill.js +517 -0
  83. package/.worktrees/8d2d0392/src/dispatch/backends/local-agent.js +155 -0
  84. package/.worktrees/8d2d0392/src/dispatch/backends/sillyhub-mcp.js +245 -0
  85. package/.worktrees/8d2d0392/src/dispatch/probe.js +246 -0
  86. package/.worktrees/8d2d0392/src/dispatch/strategy.js +121 -0
  87. package/.worktrees/8d2d0392/src/docs-check.js +825 -0
  88. package/.worktrees/8d2d0392/src/docs-debt.js +393 -0
  89. package/.worktrees/8d2d0392/src/docs-gate.js +107 -0
  90. package/.worktrees/8d2d0392/src/doctor-diagnostics.js +1099 -0
  91. package/.worktrees/8d2d0392/src/endpoint-extractor.js +409 -0
  92. package/.worktrees/8d2d0392/src/foreign-declared.js +78 -0
  93. package/.worktrees/8d2d0392/src/fs-atomic.js +73 -0
  94. package/.worktrees/8d2d0392/src/git-helper.js +150 -0
  95. package/.worktrees/8d2d0392/src/hooks/claude-pre-tool-use.cjs +130 -0
  96. package/.worktrees/8d2d0392/src/hooks/worktree-guard.js +892 -0
  97. package/.worktrees/8d2d0392/src/index.js +2854 -0
  98. package/.worktrees/8d2d0392/src/init.js +626 -0
  99. package/.worktrees/8d2d0392/src/knowledge-match.js +231 -0
  100. package/.worktrees/8d2d0392/src/local-detect.js +128 -0
  101. package/.worktrees/8d2d0392/src/local-register.js +104 -0
  102. package/.worktrees/8d2d0392/src/machine-interface.js +543 -0
  103. package/.worktrees/8d2d0392/src/migrate.js +127 -0
  104. package/.worktrees/8d2d0392/src/module-impact.js +166 -0
  105. package/.worktrees/8d2d0392/src/module-resolve.js +222 -0
  106. package/.worktrees/8d2d0392/src/modules.js +580 -0
  107. package/.worktrees/8d2d0392/src/plan-adopt-waves.js +126 -0
  108. package/.worktrees/8d2d0392/src/progress/change-registry.js +336 -0
  109. package/.worktrees/8d2d0392/src/progress/consistency-doctor.js +355 -0
  110. package/.worktrees/8d2d0392/src/progress/shared.js +36 -0
  111. package/.worktrees/8d2d0392/src/progress/stage-machine.js +594 -0
  112. package/.worktrees/8d2d0392/src/progress/step-store.js +265 -0
  113. package/.worktrees/8d2d0392/src/progress.js +1304 -0
  114. package/.worktrees/8d2d0392/src/quick-recommend.js +115 -0
  115. package/.worktrees/8d2d0392/src/quicklog.js +883 -0
  116. package/.worktrees/8d2d0392/src/review-tier.js +77 -0
  117. package/.worktrees/8d2d0392/src/run/command.js +1641 -0
  118. package/.worktrees/8d2d0392/src/run/complete-handlers.js +1552 -0
  119. package/.worktrees/8d2d0392/src/run/complete.js +1259 -0
  120. package/.worktrees/8d2d0392/src/run/concurrent-detect.js +156 -0
  121. package/.worktrees/8d2d0392/src/run/gates.js +1094 -0
  122. package/.worktrees/8d2d0392/src/run/multi-repo-context.js +208 -0
  123. package/.worktrees/8d2d0392/src/run/next.js +128 -0
  124. package/.worktrees/8d2d0392/src/run/prompt.js +843 -0
  125. package/.worktrees/8d2d0392/src/run/quick-audit.js +186 -0
  126. package/.worktrees/8d2d0392/src/run/scan-profile.js +269 -0
  127. package/.worktrees/8d2d0392/src/run/shared.js +1562 -0
  128. package/.worktrees/8d2d0392/src/run/stage.js +587 -0
  129. package/.worktrees/8d2d0392/src/run.js +23 -0
  130. package/.worktrees/8d2d0392/src/scan-diff.js +388 -0
  131. package/.worktrees/8d2d0392/src/scan-postcheck.js +524 -0
  132. package/.worktrees/8d2d0392/src/scan-staleness.js +95 -0
  133. package/.worktrees/8d2d0392/src/setup.js +414 -0
  134. package/.worktrees/8d2d0392/src/sillyhub-mcp/client.js +597 -0
  135. package/.worktrees/8d2d0392/src/sillyhub-mcp/config.js +62 -0
  136. package/.worktrees/8d2d0392/src/spec-dir-typo.js +50 -0
  137. package/.worktrees/8d2d0392/src/spec-sync.js +358 -0
  138. package/.worktrees/8d2d0392/src/stage-contract-engine.js +171 -0
  139. package/.worktrees/8d2d0392/src/stage-contract-spec.js +551 -0
  140. package/.worktrees/8d2d0392/src/stage-contract.js +948 -0
  141. package/.worktrees/8d2d0392/src/stage-review.js +597 -0
  142. package/.worktrees/8d2d0392/src/stages/archive.js +199 -0
  143. package/.worktrees/8d2d0392/src/stages/brainstorm-auto.js +285 -0
  144. package/.worktrees/8d2d0392/src/stages/brainstorm.js +624 -0
  145. package/.worktrees/8d2d0392/src/stages/cmd-existence.js +145 -0
  146. package/.worktrees/8d2d0392/src/stages/doctor.js +540 -0
  147. package/.worktrees/8d2d0392/src/stages/execute.js +1277 -0
  148. package/.worktrees/8d2d0392/src/stages/explore.js +43 -0
  149. package/.worktrees/8d2d0392/src/stages/index.js +29 -0
  150. package/.worktrees/8d2d0392/src/stages/knowledge.js +514 -0
  151. package/.worktrees/8d2d0392/src/stages/plan-postcheck.js +1398 -0
  152. package/.worktrees/8d2d0392/src/stages/plan.js +651 -0
  153. package/.worktrees/8d2d0392/src/stages/quick.js +167 -0
  154. package/.worktrees/8d2d0392/src/stages/scan.js +608 -0
  155. package/.worktrees/8d2d0392/src/stages/status.js +64 -0
  156. package/.worktrees/8d2d0392/src/stages/verify.js +246 -0
  157. package/.worktrees/8d2d0392/src/sync.js +1470 -0
  158. package/.worktrees/8d2d0392/src/task-review.js +1498 -0
  159. package/.worktrees/8d2d0392/src/taskcard-placeholders.js +21 -0
  160. package/.worktrees/8d2d0392/src/taskcard.js +217 -0
  161. package/.worktrees/8d2d0392/src/verify-postcheck.js +1718 -0
  162. package/.worktrees/8d2d0392/src/verify-probes.js +327 -0
  163. package/.worktrees/8d2d0392/src/version.js +19 -0
  164. package/.worktrees/8d2d0392/src/workflow.js +600 -0
  165. package/.worktrees/8d2d0392/src/workspace.js +125 -0
  166. package/.worktrees/8d2d0392/src/worktree-apply.js +1611 -0
  167. package/.worktrees/8d2d0392/src/worktree-deps.js +576 -0
  168. package/.worktrees/8d2d0392/src/worktree.js +1838 -0
  169. package/.worktrees/8d2d0392/templates/claude-instruction.md +23 -0
  170. package/.worktrees/8d2d0392/templates/prompts/taskcard-rules.md +29 -0
  171. package/.worktrees/8d2d0392/templates/prompts/testcase-design.md +12 -0
  172. package/.worktrees/8d2d0392/templates/prompts/verify-probes.md +32 -0
  173. package/.worktrees/8d2d0392/templates/workflows/archive-impact.yaml +79 -0
  174. package/.worktrees/8d2d0392/templates/workflows/scan-docs.yaml +132 -0
  175. package/architecture-analysis.md +448 -0
  176. package/package.json +1 -1
  177. package/src/contract-matrix.js +1 -1
  178. package/src/endpoint-extractor.js +41 -52
  179. package/src/foreign-declared.js +78 -1
  180. package/src/index.js +9 -7
  181. package/src/run/command.js +2 -1
  182. package/src/run/gates.js +17 -0
  183. package/src/run/stage.js +8 -5
  184. package/src/stage-contract-spec.js +1 -1
  185. package/src/stages/brainstorm-auto.js +43 -1
  186. package/src/stages/brainstorm.js +2 -0
  187. package/src/stages/plan.js +8 -4
  188. package/src/stages/verify.js +1 -1
  189. package/src/taskcard.js +33 -0
  190. package/src/verify-probes.js +27 -6
  191. package/src/worktree-apply.js +451 -286
  192. package/src/worktree-deps.js +93 -1
  193. package/src/worktree.js +84 -19
  194. package/templates/prompts/taskcard-rules.md +1 -1
@@ -19,7 +19,7 @@ import { WorktreeManager } from './worktree.js';
19
19
  import { parseFileChangeList, parseFileChangeListDetailed, pathMatches } from './change-list.js';
20
20
  import { parseAllowedPaths, parseRepo } from './stages/plan-postcheck.js';
21
21
  import { git, gitQuiet } from './git-helper.js';
22
- import { resolveLatestExecuteRunId, readReview } from './task-review.js';
22
+ import { resolveLatestExecuteRunId, resolveLatestExecuteRunIdWithTasks, readReview, normalizeRepoKey } from './task-review.js';
23
23
 
24
24
  const CHANGES_REL = '.sillyspec/changes';
25
25
 
@@ -229,6 +229,46 @@ export function resolveApplyAllowSet(projectRoot, changeName) {
229
229
  return repoMap;
230
230
  }
231
231
 
232
+ /**
233
+ * 收集最新 execute run 各 task review.json 的 changedFiles 声明 → Map<repoKey, string[]>。
234
+ *
235
+ * 坑 apply-undeclared-deviation-block(2026-08-24 用户反馈四期③):执行期有据越界文件
236
+ * (facade 转发/名单测试)不在 design §6 也不在 allowed_paths,Gate1 拦 apply 只能回改
237
+ * design.md。review.json changedFiles 是 reviewer 对实际改动的声明(Task Review Gate 的
238
+ * verifyReviewGitEvidence 已交叉校验其与真实 git diff 相交),作为第三源并入 allow set——
239
+ * 放行仅限「已声明且过证据校验」的文件,完全越界仍拦。口径与 complete-handlers 的
240
+ * collectExecuteChangedFiles 一致:change 戳归属 run、.sillyspec//meta.json 过滤、
241
+ * review.repo 切片(跨仓声明不进 main 集)。读不到 run/review → 空 Map(fail-closed 回退旧行为)。
242
+ *
243
+ * @param {string} projectRoot - 主仓库根
244
+ * @param {string} changeName - 变更名
245
+ * @returns {Map<string, string[]>}
246
+ */
247
+ export function collectReviewDeclaredFiles(projectRoot, changeName) {
248
+ const byRepo = new Map();
249
+ try {
250
+ const runtimeRoot = join(projectRoot, '.sillyspec', '.runtime');
251
+ const runId = resolveLatestExecuteRunIdWithTasks({ runtimeRoot, changeName });
252
+ if (!runId) return byRepo;
253
+ const runTasksDir = join(runtimeRoot, 'execute-runs', runId, 'tasks');
254
+ if (!existsSync(runTasksDir)) return byRepo;
255
+ for (const taskId of readdirSync(runTasksDir)) {
256
+ const r = readReview(join(runTasksDir, taskId, 'review.json'));
257
+ if (!r.ok || !r.review || !Array.isArray(r.review.changedFiles)) continue;
258
+ const repoKey = normalizeRepoKey(r.review.repo);
259
+ const list = byRepo.get(repoKey) || [];
260
+ for (const f of r.review.changedFiles) {
261
+ // 交付物过滤(与 collectExecuteChangedFiles 同口径):.sillyspec/ 运行时产物/meta.json 不进 allow
262
+ if (typeof f !== 'string' || f.trim() === '') continue;
263
+ if (f.startsWith('.sillyspec/') || f === 'meta.json') continue;
264
+ list.push(f);
265
+ }
266
+ byRepo.set(repoKey, list);
267
+ }
268
+ } catch { /* 读不到 run/review → 空 Map(fail-closed 回退旧行为) */ }
269
+ return byRepo;
270
+ }
271
+
232
272
  /**
233
273
  * 跨仓 task apply = no-op 校验(task-05 / D-009 / design §6 A3 G1)。
234
274
  *
@@ -384,7 +424,7 @@ export async function withMainRepoLock(projectRoot, changeName, purpose, fn, opt
384
424
  }
385
425
  }
386
426
 
387
- export function applyWorktree(changeName, { cwd, checkOnly = false, merge = false, base = 'merge-base', ctx = null, skipOverlap = false } = {}) {
427
+ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = false, base = 'merge-base', ctx = null, skipOverlap = false, stashDirty = false } = {}) {
388
428
  const projectRoot = cwd || process.cwd();
389
429
  const wm = new WorktreeManager({ cwd: projectRoot });
390
430
  const meta = wm.getMeta(changeName);
@@ -502,6 +542,29 @@ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = fals
502
542
  // (主仓 worktree diff 只含主仓文件,跨仓文件在跨仓仓不进主仓 worktree diff)。跨仓 allowed_paths
503
543
  // 仅作 Map 切片返回供上游用,主流程不消费(跨仓 apply=no-op,D-009)。
504
544
  const allowMap = resolveApplyAllowSet(projectRoot, changeName);
545
+ // --- 3b. review.json 声明偏差文件并入(坑 apply-undeclared-deviation-block)---
546
+ // 第三源:reviewer 声明的 changedFiles(已过 Task Review Gate git 证据交叉校验)——执行期
547
+ // 有据越界(facade 转发/名单测试)不再逼回改 design.md。各 repo 切片各自并入;仅靠 review
548
+ // 放行的文件记审计 warning(result.reviewAdmittedFiles),完全越界文件仍拦(Gate1 在扩展后判)。
549
+ const reviewDeclaredByRepo = collectReviewDeclaredFiles(projectRoot, changeName);
550
+ const reviewAdmittedFiles = [];
551
+ for (const [repoKey, files] of reviewDeclaredByRepo) {
552
+ const repoSet = allowMap.get(repoKey);
553
+ if (!repoSet) continue; // 该 repo 无 design/任务卡清单(无清单=不校验),无需扩展
554
+ const existing = [...repoSet];
555
+ for (const f of files) {
556
+ if (!existing.some(ap => pathMatches(f, ap))) {
557
+ repoSet.add(f);
558
+ if (repoKey === 'main') reviewAdmittedFiles.push(f);
559
+ }
560
+ }
561
+ }
562
+ if (reviewAdmittedFiles.length > 0) {
563
+ result.reviewAdmittedFiles = reviewAdmittedFiles;
564
+ result.warnings = (result.warnings || []).concat([
565
+ `${reviewAdmittedFiles.length} 个变更文件不在 design.md/任务卡清单,但已被 task review.json changedFiles 声明(review 声明放行,已过 Task Review Gate git 证据校验;审计留痕):${reviewAdmittedFiles.join(', ')}`
566
+ ]);
567
+ }
505
568
  const allowSet = allowMap.get('main') || new Set();
506
569
  const hasAllowList = allowSet.size > 0;
507
570
 
@@ -541,7 +604,7 @@ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = fals
541
604
  if (violations.length > 0) {
542
605
  result.extraFiles.push(...violations);
543
606
  result.errors.push(
544
- `文件清单校验失败:以下变更文件不在 design.md 清单中:\n ${violations.join('\n ')}`
607
+ `文件清单校验失败:以下变更文件不在 design.md 清单、也不在 task review.json changedFiles 声明中:\n ${violations.join('\n ')}\n(若属执行期合理偏差:在 task review.json 的 changedFiles 声明,或在 design.md §6 清单补行)`
545
608
  );
546
609
  // checkOnly(assess)模式不短路:继续跑 Gate3,收集所有道供一次报全(坑 worktree-execute-apply-friction 坑4)。
547
610
  // 真实 apply(checkOnly=false)仍短路,保安全。
@@ -549,83 +612,178 @@ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = fals
549
612
  }
550
613
  }
551
614
 
552
- // --- 4.6 显式 --merge:用户显式选择 git merge 兜底(主干已提交推进重叠时的三方合并) ---
553
- // 触发点从「4.5 baseline 漂移自动降级」改为「用户显式 --merge flag」(D-001 保留,触发方式变化)。
554
- // 用 --merge 时跳过未提交 dirty 拦截——merge 同样要求工作区相对干净,此处仅提示风险,真正失败由 applyByMerge 报告。
555
- // keepConflicts:true——显式 --merge 冲突时保留现场供手工解决(不再直接 abort 丢上下文)。
556
- if (merge && !checkOnly) {
557
- return applyByMerge(result, changeName, projectRoot, wm, { keepConflicts: true });
615
+ // --- 4.4 --stash-dirty:主仓在途改动自动 stash(坑 apply-main-dirty-no-first-class, ---
616
+ // 2026-08-24 用户反馈四期①:主仓并行在途改动下默认 / --skip-overlap(全重叠「无可应用子集」)/
617
+ // --merge(git 拒在脏树启动合并)三路死锁,手工 stash→3way→pop 流程未内置。flag 显式 opt-in
618
+ // (自动触碰用户未提交工作区必须可审计):stash SHA 显著打印;恢复用 apply --index 保暂存区
619
+ // 状态(普通 pop 会把 staged 降级为 unstaged);恢复失败保留条目绝不自动 drop(SHA 兜底)。
620
+ // checkOnly(assess)只读,绝不 stash。放在 Gate1 之后:清单违规先拦,不动用户树。
621
+ let stashInfo = null;
622
+ if (stashDirty && !checkOnly) {
623
+ try {
624
+ const dirtyProbe = computeRescueDirtyFiles(projectRoot);
625
+ if (dirtyProbe.length > 0) {
626
+ const marker = `sillyspec apply ${changeName} --stash-dirty ${new Date().toISOString()}`;
627
+ const before = (gitQuiet(projectRoot, ['stash', 'list']) || '').split('\n').filter(Boolean).length;
628
+ // pathspec 限定 stash 范围与探针/4.5 同口径(排除 .sillyspec/ 运行时与他者 spec 产物、
629
+ // .claude/docs/CLAUDE.md)——裸 push -u 会把排除项的未跟踪文件一并卷走,恢复时与
630
+ // apply 期间重建的 spec 文件 already exists 互踩(实证 dbg)。
631
+ git(projectRoot, ['stash', 'push', '--include-untracked', '-m', marker,
632
+ '--', '.', ':(exclude).sillyspec/', ':(exclude).claude/', ':(exclude)docs/', ':(exclude)CLAUDE.md'], { timeout: 60000 });
633
+ const headEntry = ((gitQuiet(projectRoot, ['stash', 'list']) || '').split('\n')[0] || '');
634
+ const after = (gitQuiet(projectRoot, ['stash', 'list']) || '').split('\n').filter(Boolean).length;
635
+ const sha = gitQuiet(projectRoot, ['rev-parse', '--verify', 'stash@{0}']);
636
+ if (after !== before + 1 || !sha || !headEntry.includes(marker.split(' ').slice(0, 4).join(' '))) {
637
+ // 栈顶非本次条目(并行外部操作插队)——不盲动栈,fail-closed
638
+ throw new Error(`stash push 后栈顶校验失败(before=${before} after=${after} head=${headEntry.slice(0, 60)})`);
639
+ }
640
+ stashInfo = { sha: sha.trim(), marker };
641
+ console.log(`📦 主仓在途改动已 stash(--stash-dirty,${dirtyProbe.length} 个文件):stash@{0} = ${stashInfo.sha}`);
642
+ console.log(` apply 结束后自动恢复(git stash apply --index,保留暂存区状态);若恢复冲突,stash 条目保留不丢弃,用上述 SHA 兜底`);
643
+ }
644
+ } catch (e) {
645
+ result.errors.push(`--stash-dirty:主仓 stash 失败(apply 未开始,主仓未改动): ${e.message}——若栈中已有新条目请 git stash list 核对后再处置,勿盲 pop`);
646
+ return result;
647
+ }
558
648
  }
559
649
 
560
- // --- 4.5 校验:主工作区「未提交」脏文件是否与本次变更重叠(overlap-only 拦截)---
561
- // 分工:4.5(排除规则下 dirty∩changedFiles)+ 5a(更宽口径的同一交集)挡「未提交」dirty 重叠;
562
- // 5b 管「已提交」HEAD 分叉(已放宽)。
563
- // 2026-08-20 放宽(原全量拦截 → 只拦重叠):原「排除规则下任何未提交文件即整体拒绝」会把与本次
564
- // 变更无关的脏文件也硬挡,用户被迫走 rescue cp 手动路径。重叠(dirtyFiles ∩ changedFiles,
565
- // changedFiles 已含删除文件与 worktree 新增同名文件)才是 git apply 无法安全应用的实际危险区。
566
- // 残余风险与兜底(Windows/autocrlf):实测 autocrlf on 时 git apply --3way 对 dirty 工作区可报
567
- // `does not match index`(哪怕脏文件与 patch 不重叠;autocrlf off 时能干净应用,非 git 本质限制)。
568
- // 交集空前提下该失败是安全的:step7 catch → rollbackApply 只 checkout/删除 patch 涉及文件
569
- // (这些文件 apply 前无未提交修改,还原 = apply 前状态),无关脏文件不在 patch/rollback 范围
570
- // 不受影响 → fail-safe,报错后 stash 重试即可。放行时 warning 提示此路径。
571
- // 排除非交付物的元数据/文档 churn(execute 自身改的 + 多操作者常改的 agent 指引/文档),
572
- // 否则别人改 CLAUDE.md/docs/.claude → 判定 dirty → apply 误阻断(多操作者仓库高频踩坑)。
573
- // 注意:排除规则必须和 computeBaselineHash (worktree.js) 一致(虽已不比对 hash,仍用同一口径判当前 dirty)。
574
- if (meta.baselineHash) {
575
- // pathspec:`--` 结束选项,`.` 包含全部,后续 :(exclude) 排除非交付物元数据/文档 churn
576
- // (与 computeBaselineHash 同口径)。数组形式逐元素传递,:(exclude) magic 字面直传不经 shell。
577
- const exclude = ['--', '.', ':(exclude).sillyspec/', ':(exclude).claude/', ':(exclude)docs/', ':(exclude)CLAUDE.md'];
578
- const staged = gitQuiet(projectRoot, ['diff', '--cached', ...exclude]) || '';
579
- const unstaged = gitQuiet(projectRoot, ['diff', ...exclude]) || '';
580
- const untracked = gitQuiet(projectRoot, ['ls-files', '--others', '--exclude-standard', ...exclude]) || '';
581
- // 意图(与 computeBaselineHash 注释一致):只看「未提交 dirty」——git apply --3way 对 dirty 工作区不稳。
582
- // 不比对 hash 是否等于 execute 启动时 baselineHash:主仓 dirty→clean(execute 期间 commit 无关文件)后
583
- // hash 必变,若仍比对会永久死锁(须手改 meta.baselineHash)。改判「排除规则下当前是否有未提交 dirty」。
584
- const hasUncommittedDirty = staged !== '' || unstaged !== '' || untracked !== '';
585
- if (hasUncommittedDirty) {
586
- const dirtyFiles = [...new Set(
587
- ((gitQuiet(projectRoot, ['diff', '--name-only', 'HEAD']) || '').split('\n').filter(Boolean))
588
- .concat((gitQuiet(projectRoot, ['ls-files', '--others', '--exclude-standard']) || '').split('\n').filter(Boolean))
589
- )].filter(f => !f.startsWith('.sillyspec/') && f !== 'meta.json');
590
- const overlapDirty = dirtyFiles.filter(f => changedFiles.includes(f));
591
- if (overlapDirty.length > 0) {
592
- // --skip-overlap(坑 apply-overlap-all-or-nothing,2026-08-23 实证:多 agent 并发仓主仓
593
- // 常态有在途变更,overlap 整批拦截使 apply 基本不可用,rescue 手动 cp 又留混合状态):
594
- // 显式 opt-in 剔除重叠文件、应用干净子集。重叠文件留在 worktree——step8 非 force
595
- // cleanup 被 hasUnappliedChanges 护栏拦住(主仓工作区逐字节降噪层只剔除已应用文件),
596
- // 待主仓干净后重新 apply(此时只剩剩余文件)或人工裁决。
650
+ try {
651
+ // --- 4.6 显式 --merge:用户显式选择 git merge 兜底(主干已提交推进重叠时的三方合并) ---
652
+ // 触发点从「4.5 baseline 漂移自动降级」改为「用户显式 --merge flag」(D-001 保留,触发方式变化)。
653
+ // 用 --merge 时跳过未提交 dirty 拦截——merge 同样要求工作区相对干净,此处仅提示风险,真正失败由 applyByMerge 报告。
654
+ // keepConflicts:true——显式 --merge 冲突时保留现场供手工解决(不再直接 abort 丢上下文)。
655
+ if (merge && !checkOnly) {
656
+ return applyByMerge(result, changeName, projectRoot, wm, { keepConflicts: true });
657
+ }
658
+
659
+ // --- 4.5 校验:主工作区「未提交」脏文件是否与本次变更重叠(overlap-only 拦截)---
660
+ // 分工:4.5(排除规则下 dirty∩changedFiles)+ 5a(更宽口径的同一交集)挡「未提交」dirty 重叠;
661
+ // 5b 管「已提交」HEAD 分叉(已放宽)。
662
+ // 2026-08-20 放宽(原全量拦截 → 只拦重叠):原「排除规则下任何未提交文件即整体拒绝」会把与本次
663
+ // 变更无关的脏文件也硬挡,用户被迫走 rescue cp 手动路径。重叠(dirtyFiles ∩ changedFiles,
664
+ // changedFiles 已含删除文件与 worktree 新增同名文件)才是 git apply 无法安全应用的实际危险区。
665
+ // 残余风险与兜底(Windows/autocrlf):实测 autocrlf on 时 git apply --3way 对 dirty 工作区可报
666
+ // `does not match index`(哪怕脏文件与 patch 不重叠;autocrlf off 时能干净应用,非 git 本质限制)。
667
+ // 交集空前提下该失败是安全的:step7 catch → rollbackApply 只 checkout/删除 patch 涉及文件
668
+ // (这些文件 apply 前无未提交修改,还原 = apply 前状态),无关脏文件不在 patch/rollback 范围
669
+ // 不受影响 → fail-safe,报错后 stash 重试即可。放行时 warning 提示此路径。
670
+ // 排除非交付物的元数据/文档 churn(execute 自身改的 + 多操作者常改的 agent 指引/文档),
671
+ // 否则别人改 CLAUDE.md/docs/.claude → 判定 dirty → apply 误阻断(多操作者仓库高频踩坑)。
672
+ // 注意:排除规则必须和 computeBaselineHash (worktree.js) 一致(虽已不比对 hash,仍用同一口径判当前 dirty)。
673
+ if (meta.baselineHash) {
674
+ // pathspec:`--` 结束选项,`.` 包含全部,后续 :(exclude) 排除非交付物元数据/文档 churn
675
+ // (与 computeBaselineHash 同口径)。数组形式逐元素传递,:(exclude) magic 字面直传不经 shell。
676
+ const exclude = ['--', '.', ':(exclude).sillyspec/', ':(exclude).claude/', ':(exclude)docs/', ':(exclude)CLAUDE.md'];
677
+ const staged = gitQuiet(projectRoot, ['diff', '--cached', ...exclude]) || '';
678
+ const unstaged = gitQuiet(projectRoot, ['diff', ...exclude]) || '';
679
+ const untracked = gitQuiet(projectRoot, ['ls-files', '--others', '--exclude-standard', ...exclude]) || '';
680
+ // 意图(与 computeBaselineHash 注释一致):只看「未提交 dirty」——git apply --3way 对 dirty 工作区不稳。
681
+ // 不比对 hash 是否等于 execute 启动时 baselineHash:主仓 dirty→clean(execute 期间 commit 无关文件)后
682
+ // hash 必变,若仍比对会永久死锁(须手改 meta.baselineHash)。改判「排除规则下当前是否有未提交 dirty」。
683
+ const hasUncommittedDirty = staged !== '' || unstaged !== '' || untracked !== '';
684
+ if (hasUncommittedDirty) {
685
+ const dirtyFiles = [...new Set(
686
+ ((gitQuiet(projectRoot, ['diff', '--name-only', 'HEAD']) || '').split('\n').filter(Boolean))
687
+ .concat((gitQuiet(projectRoot, ['ls-files', '--others', '--exclude-standard']) || '').split('\n').filter(Boolean))
688
+ )].filter(f => !f.startsWith('.sillyspec/') && f !== 'meta.json');
689
+ const overlapDirty = dirtyFiles.filter(f => changedFiles.includes(f));
690
+ if (overlapDirty.length > 0) {
691
+ // --skip-overlap(坑 apply-overlap-all-or-nothing,2026-08-23 实证:多 agent 并发仓主仓
692
+ // 常态有在途变更,overlap 整批拦截使 apply 基本不可用,rescue 手动 cp 又留混合状态):
693
+ // 显式 opt-in 剔除重叠文件、应用干净子集。重叠文件留在 worktree——step8 非 force
694
+ // cleanup 被 hasUnappliedChanges 护栏拦住(主仓工作区逐字节降噪层只剔除已应用文件),
695
+ // 待主仓干净后重新 apply(此时只剩剩余文件)或人工裁决。
696
+ if (skipOverlap && !checkOnly) {
697
+ const skipSet = new Set(overlapDirty);
698
+ result.skippedOverlapFiles = overlapDirty.slice();
699
+ changedFiles = changedFiles.filter(f => !skipSet.has(f));
700
+ result.changedFiles = changedFiles;
701
+ result.deletedFiles = deletedFiles.filter(f => !skipSet.has(f));
702
+ result.hashMismatchFiles = (result.hashMismatchFiles || []).filter(f => !skipSet.has(f));
703
+ if (changedFiles.length === 0) {
704
+ result.errors.push(
705
+ `--skip-overlap:本次 ${overlapDirty.length} 个变更文件全部与主仓未提交改动重叠,无可应用子集:\n ${overlapDirty.join('\n ')}\n` +
706
+ `请先提交/stash 主仓改动后重试(不带 --skip-overlap),或 sillyspec worktree apply ${changeName} --stash-dirty(工具内置 stash→apply→恢复,保暂存区状态,SHA 兜底可审计)。`
707
+ );
708
+ return result;
709
+ }
710
+ result.warnings = (result.warnings || []).concat([
711
+ `--skip-overlap:跳过 ${overlapDirty.length} 个与主仓未提交改动重叠的文件(留在 worktree,未应用):${overlapDirty.join(', ')}——待主仓提交/stash 后重新 apply 只应用剩余文件,或确认放弃后 cleanup --force`
712
+ ]);
713
+ } else {
714
+ // 重叠拦截:只有与本次变更同文件的未提交改动才无法安全 apply(列重叠文件,非全部脏文件)
715
+ const rescueDirty = computeRescueDirtyFiles(projectRoot);
716
+ result.rescueCommands = generateRescueCommands({
717
+ changedFiles,
718
+ dirtyFiles: rescueDirty,
719
+ hashMismatchFiles: result.hashMismatchFiles,
720
+ deletedFiles: result.deletedFiles,
721
+ worktreePath,
722
+ projectRoot,
723
+ });
724
+ result.errors.push(
725
+ `主工作区以下未提交文件与本次 apply 的变更重叠,git apply 无法安全应用:\n ${overlapDirty.join('\n ')}\n` +
726
+ `请先提交或暂存这些改动,再重新 apply:\n git add -A && git commit -m "..." 或 git stash\n` +
727
+ `或 sillyspec worktree apply ${changeName} --stash-dirty(工具内置 stash→apply→恢复,保暂存区状态,SHA 兜底可审计)\n` +
728
+ `或应用非重叠部分(重叠文件留在 worktree,主仓干净后重新 apply 只补剩余):\n sillyspec worktree apply ${changeName} --skip-overlap\n` +
729
+ (result.rescueCommands.commands.length > 0 || result.rescueCommands.warnings.length > 0
730
+ ? `或手动 rescue(旁路 git apply,逐文件 cp 安全子集;cp 后需手动 sillyspec worktree cleanup ${changeName}):\n` +
731
+ result.rescueCommands.commands.map(c => ` ${c}`).join('\n') +
732
+ (result.rescueCommands.warnings.length > 0 ? '\n' + result.rescueCommands.warnings.map(w => ` ${w}`).join('\n') : '') +
733
+ `\n (共 ${result.rescueCommands.cpFileCount} 个可安全 cp,${result.rescueCommands.excludedCount} 个被排除)\n`
734
+ : '')
735
+ );
736
+ if (!checkOnly) return result; // checkOnly 收集不短路(一次报全);真实 apply 短路
737
+ }
738
+ } else {
739
+ // 无关脏文件放行(只校验重叠文件):--3way 若因 autocrlf 报 does not match index 会被
740
+ // step7 catch 回滚(交集空前提下无损,见上注释),stash 后重试即可——不再硬挡 rescue 手动路径
741
+ result.warnings = (result.warnings || []).concat([
742
+ `主工作区有 ${dirtyFiles.length} 个与本次 apply 无关的未提交文件,已放行(只校验重叠文件):` +
743
+ `${dirtyFiles.slice(0, 5).join(', ')}${dirtyFiles.length > 5 ? ' 等' : ''}` +
744
+ `——若 apply --3way 因 CRLF/autocrlf 报 does not match index,可 git stash 后重试`
745
+ ]);
746
+ }
747
+ }
748
+ }
749
+
750
+ // --- 5. 校验:主工作区文件 base hash 一致 ---
751
+ // 5a. 检查主工作区是否有未 commit 的脏文件(会影响 apply)
752
+ const mainDirtyRaw = gitQuiet(projectRoot, ['diff', '--name-only', 'HEAD']);
753
+ const mainDirtyFiles = mainDirtyRaw ? mainDirtyRaw.split('\n').filter(Boolean) : [];
754
+ if (mainDirtyFiles.length > 0) {
755
+ // 如果脏文件和本次 apply 的文件有交集 → 报错
756
+ const conflictDirty = mainDirtyFiles.filter(f => changedFiles.includes(f));
757
+ if (conflictDirty.length > 0) {
758
+ // --skip-overlap 同款剔除(4.5 过滤后此处残余多为 staged 口径差集,防御性同处理)
597
759
  if (skipOverlap && !checkOnly) {
598
- const skipSet = new Set(overlapDirty);
599
- result.skippedOverlapFiles = overlapDirty.slice();
600
- changedFiles = changedFiles.filter(f => !skipSet.has(f));
760
+ const skipSet5a = new Set(conflictDirty);
761
+ for (const f of conflictDirty) {
762
+ if (!result.skippedOverlapFiles.includes(f)) result.skippedOverlapFiles.push(f);
763
+ }
764
+ changedFiles = changedFiles.filter(f => !skipSet5a.has(f));
601
765
  result.changedFiles = changedFiles;
602
- result.deletedFiles = deletedFiles.filter(f => !skipSet.has(f));
603
- result.hashMismatchFiles = (result.hashMismatchFiles || []).filter(f => !skipSet.has(f));
766
+ result.deletedFiles = deletedFiles.filter(f => !skipSet5a.has(f));
767
+ result.hashMismatchFiles = (result.hashMismatchFiles || []).filter(f => !skipSet5a.has(f));
604
768
  if (changedFiles.length === 0) {
605
769
  result.errors.push(
606
- `--skip-overlap:本次 ${overlapDirty.length} 个变更文件全部与主仓未提交改动重叠,无可应用子集:\n ${overlapDirty.join('\n ')}\n` +
607
- `请先提交/stash 主仓改动后重试(不带 --skip-overlap)。`
770
+ `--skip-overlap:变更文件全部与主仓未提交改动重叠,无可应用子集:\n ${conflictDirty.join('\n ')}\n` +
771
+ `请先提交/stash 主仓改动后重试,或 sillyspec worktree apply ${changeName} --stash-dirty(工具内置 stash→apply→恢复,保暂存区状态,SHA 兜底可审计)。`
608
772
  );
609
773
  return result;
610
774
  }
611
775
  result.warnings = (result.warnings || []).concat([
612
- `--skip-overlap:跳过 ${overlapDirty.length} 个与主仓未提交改动重叠的文件(留在 worktree,未应用):${overlapDirty.join(', ')}——待主仓提交/stash 后重新 apply 只应用剩余文件,或确认放弃后 cleanup --force`
776
+ `--skip-overlap(5a 口径):再剔除 ${conflictDirty.length} 个重叠文件:${conflictDirty.join(', ')}`
613
777
  ]);
614
778
  } else {
615
- // 重叠拦截:只有与本次变更同文件的未提交改动才无法安全 apply(列重叠文件,非全部脏文件)
616
- const rescueDirty = computeRescueDirtyFiles(projectRoot);
779
+ const rescueDirty5a = computeRescueDirtyFiles(projectRoot);
617
780
  result.rescueCommands = generateRescueCommands({
618
- changedFiles,
619
- dirtyFiles: rescueDirty,
620
- hashMismatchFiles: result.hashMismatchFiles,
621
- deletedFiles: result.deletedFiles,
622
- worktreePath,
623
- projectRoot,
781
+ changedFiles, dirtyFiles: rescueDirty5a, hashMismatchFiles: result.hashMismatchFiles,
782
+ deletedFiles: result.deletedFiles, worktreePath, projectRoot,
624
783
  });
625
784
  result.errors.push(
626
- `主工作区以下未提交文件与本次 apply 的变更重叠,git apply 无法安全应用:\n ${overlapDirty.join('\n ')}\n` +
627
- `请先提交或暂存这些改动,再重新 apply:\n git add -A && git commit -m "..." 或 git stash\n` +
628
- `或应用非重叠部分(重叠文件留在 worktree,主仓干净后重新 apply 只补剩余):\n sillyspec worktree apply ${changeName} --skip-overlap\n` +
785
+ `主工作区有以下未 commit 的变更,会影响 apply:\n ${conflictDirty.join('\n ')}\n请先 commit 或 stash 这些变更。` +
786
+ `或应用非重叠部分:sillyspec worktree apply ${changeName} --skip-overlap` +
629
787
  (result.rescueCommands.commands.length > 0 || result.rescueCommands.warnings.length > 0
630
788
  ? `或手动 rescue(旁路 git apply,逐文件 cp 安全子集;cp 后需手动 sillyspec worktree cleanup ${changeName}):\n` +
631
789
  result.rescueCommands.commands.map(c => ` ${c}`).join('\n') +
@@ -635,260 +793,259 @@ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = fals
635
793
  );
636
794
  if (!checkOnly) return result; // checkOnly 收集不短路(一次报全);真实 apply 短路
637
795
  }
638
- } else {
639
- // 无关脏文件放行(只校验重叠文件):--3way 若因 autocrlf 报 does not match index 会被
640
- // step7 catch 回滚(交集空前提下无损,见上注释),stash 后重试即可——不再硬挡 rescue 手动路径
641
- result.warnings = (result.warnings || []).concat([
642
- `主工作区有 ${dirtyFiles.length} 个与本次 apply 无关的未提交文件,已放行(只校验重叠文件):` +
643
- `${dirtyFiles.slice(0, 5).join(', ')}${dirtyFiles.length > 5 ? ' 等' : ''}` +
644
- `——若 apply --3way 因 CRLF/autocrlf 报 does not match index,可 git stash 后重试`
645
- ]);
646
- }
647
- }
648
- }
649
-
650
- // --- 5. 校验:主工作区文件 base hash 一致 ---
651
- // 5a. 检查主工作区是否有未 commit 的脏文件(会影响 apply)
652
- const mainDirtyRaw = gitQuiet(projectRoot, ['diff', '--name-only', 'HEAD']);
653
- const mainDirtyFiles = mainDirtyRaw ? mainDirtyRaw.split('\n').filter(Boolean) : [];
654
- if (mainDirtyFiles.length > 0) {
655
- // 如果脏文件和本次 apply 的文件有交集 → 报错
656
- const conflictDirty = mainDirtyFiles.filter(f => changedFiles.includes(f));
657
- if (conflictDirty.length > 0) {
658
- // --skip-overlap 同款剔除(4.5 过滤后此处残余多为 staged 口径差集,防御性同处理)
659
- if (skipOverlap && !checkOnly) {
660
- const skipSet5a = new Set(conflictDirty);
661
- for (const f of conflictDirty) {
662
- if (!result.skippedOverlapFiles.includes(f)) result.skippedOverlapFiles.push(f);
663
- }
664
- changedFiles = changedFiles.filter(f => !skipSet5a.has(f));
665
- result.changedFiles = changedFiles;
666
- result.deletedFiles = deletedFiles.filter(f => !skipSet5a.has(f));
667
- result.hashMismatchFiles = (result.hashMismatchFiles || []).filter(f => !skipSet5a.has(f));
668
- if (changedFiles.length === 0) {
669
- result.errors.push(
670
- `--skip-overlap:变更文件全部与主仓未提交改动重叠,无可应用子集:\n ${conflictDirty.join('\n ')}\n` +
671
- `请先提交/stash 主仓改动后重试。`
672
- );
673
- return result;
674
- }
675
- result.warnings = (result.warnings || []).concat([
676
- `--skip-overlap(5a 口径):再剔除 ${conflictDirty.length} 个重叠文件:${conflictDirty.join(', ')}`
677
- ]);
678
- } else {
679
- const rescueDirty5a = computeRescueDirtyFiles(projectRoot);
680
- result.rescueCommands = generateRescueCommands({
681
- changedFiles, dirtyFiles: rescueDirty5a, hashMismatchFiles: result.hashMismatchFiles,
682
- deletedFiles: result.deletedFiles, worktreePath, projectRoot,
683
- });
684
- result.errors.push(
685
- `主工作区有以下未 commit 的变更,会影响 apply:\n ${conflictDirty.join('\n ')}\n请先 commit 或 stash 这些变更。` +
686
- `或应用非重叠部分:sillyspec worktree apply ${changeName} --skip-overlap` +
687
- (result.rescueCommands.commands.length > 0 || result.rescueCommands.warnings.length > 0
688
- ? `或手动 rescue(旁路 git apply,逐文件 cp 安全子集;cp 后需手动 sillyspec worktree cleanup ${changeName}):\n` +
689
- result.rescueCommands.commands.map(c => ` ${c}`).join('\n') +
690
- (result.rescueCommands.warnings.length > 0 ? '\n' + result.rescueCommands.warnings.map(w => ` ${w}`).join('\n') : '') +
691
- `\n (共 ${result.rescueCommands.cpFileCount} 个可安全 cp,${result.rescueCommands.excludedCount} 个被排除)\n`
692
- : '')
693
- );
694
- if (!checkOnly) return result; // checkOnly 收集不短路(一次报全);真实 apply 短路
695
796
  }
696
797
  }
697
- }
698
-
699
- // 5b hashMismatch 计算已前移到 step3.5(Grill P0),见上
700
798
 
701
- // --- 6. checkOnly 模式:到此返回 ---
702
- if (checkOnly) {
703
- result.ok = true;
704
- return result;
705
- }
799
+ // 5b hashMismatch 计算已前移到 step3.5(Grill P0),见上
706
800
 
707
- // --- 7. 生成 patch 并 apply ---
708
- // 确定要包含在 patch 中的文件:有清单用「实际变更 ∩ 清单(pathMatches 容差)」,无清单用全部变更。
709
- // 口径与 classifyAllowListViolations 一致(坑 apply-glob-manifest-passes-check-but-not-patch)。
710
- const patchFiles = resolvePatchFiles(changedFiles, allowSet, hasAllowList);
801
+ // --- 6. checkOnly 模式:到此返回 ---
802
+ if (checkOnly) {
803
+ result.ok = true;
804
+ return result;
805
+ }
711
806
 
712
- // 创建临时文件
713
- const tmpDir = mkdtempSync(join(tmpdir(), 'sillyspec-patch-'));
714
- const patchPath = join(tmpDir, 'apply.patch');
715
- result.patchPath = patchPath;
807
+ // --- 7. 生成 patch 并 apply ---
808
+ // 确定要包含在 patch 中的文件:有清单用「实际变更 ∩ 清单(pathMatches 容差)」,无清单用全部变更。
809
+ // 口径与 classifyAllowListViolations 一致(坑 apply-glob-manifest-passes-check-but-not-patch)。
810
+ const patchFiles = resolvePatchFiles(changedFiles, allowSet, hasAllowList);
716
811
 
717
- try {
718
- // patch 以 Buffer 聚合:git diff --binary 对二进制/非 UTF-8 文件输出任意字节序列,
719
- // 按 utf8 string 拼接会破坏 NUL 字节成 U+FFFD → corrupt patch(git-helper.js git() 注释
720
- // 同款坑;worktree.js 的 diff 采集已是 encoding:'buffer' 正确写法)。
721
- const patchParts = [];
722
-
723
- // 分 tracked 变更和 untracked 新文件生成 patch
724
- // 批量化:一次 ls-tree(deliverableBase tree 中存在的文件)+ 一次 ls-files(index 中存在的文件)
725
- // 建集合,替代 per-file cat-file -e / ls-files --error-unmatch(原至多 2N spawn → 固定 2)。
726
- // 语义等价:cat-file -e deliverableBase:f 成功 ⟺ f 在 ls-tree deliverableBase 输出(getBlobHashMap key);
727
- // ls-files --error-unmatch f 成功 ⟺ f 在 ls-files -- 输出。
728
- // tracked 判定用 deliverableBase(集合判定侧)
729
- const inTree = getBlobHashMap(worktreePath, deliverableBase, patchFiles);
730
- const inIndexList = patchFiles.length > 0
731
- ? (gitQuiet(worktreePath, ['ls-files', '--', ...patchFiles]) || '').split('\n').filter(Boolean)
732
- : [];
733
- const inIndex = new Set(inIndexList);
734
- const trackedFiles = patchFiles.filter(f => inTree.has(f) || inIndex.has(f));
735
- const trackedSet = new Set(trackedFiles);
736
- const untrackedPatchFiles = patchFiles.filter(f => !trackedSet.has(f));
737
-
738
- // tracked 文件:git diff patchBase(patch 生成锚点,默认 merge-base)
739
- // 数组形式,文件名逐个展开为独立 argv,不经 shell;
740
- // encoding:'buffer' 保留二进制补丁原样,timeout 放大到 60s 防大 diff 超时——原裸 execSync 无 timeout
741
- if (trackedFiles.length > 0) {
742
- patchParts.push(git(
743
- worktreePath,
744
- ['diff', '--binary', patchBase, '--', ...trackedFiles],
745
- { encoding: 'buffer', timeout: 60000 }
746
- ));
747
- }
812
+ // 创建临时文件
813
+ const tmpDir = mkdtempSync(join(tmpdir(), 'sillyspec-patch-'));
814
+ const patchPath = join(tmpDir, 'apply.patch');
815
+ result.patchPath = patchPath;
748
816
 
749
- // untracked 新文件:git add 到 index,git diff --cached,然后 reset(均数组形式,文件名逐个展开)
750
- if (untrackedPatchFiles.length > 0) {
751
- git(worktreePath, ['add', '--', ...untrackedPatchFiles]);
752
- try {
753
- // encoding:'buffer' 保留二进制补丁原样,timeout 放大到 60s 防大 diff 超时
817
+ try {
818
+ // patch 以 Buffer 聚合:git diff --binary 对二进制/非 UTF-8 文件输出任意字节序列,
819
+ // 按 utf8 string 拼接会破坏 NUL 字节成 U+FFFD → corrupt patch(git-helper.js git() 注释
820
+ // 同款坑;worktree.js 的 diff 采集已是 encoding:'buffer' 正确写法)。
821
+ const patchParts = [];
822
+
823
+ // 分 tracked 变更和 untracked 新文件生成 patch
824
+ // 批量化:一次 ls-tree(deliverableBase tree 中存在的文件)+ 一次 ls-files(index 中存在的文件)
825
+ // 建集合,替代 per-file cat-file -e / ls-files --error-unmatch(原至多 2N spawn → 固定 2)。
826
+ // 语义等价:cat-file -e deliverableBase:f 成功 ⟺ f 在 ls-tree deliverableBase 输出(getBlobHashMap key);
827
+ // ls-files --error-unmatch f 成功 ⟺ f 在 ls-files -- 输出。
828
+ // tracked 判定用 deliverableBase(集合判定侧)
829
+ const inTree = getBlobHashMap(worktreePath, deliverableBase, patchFiles);
830
+ const inIndexList = patchFiles.length > 0
831
+ ? (gitQuiet(worktreePath, ['ls-files', '--', ...patchFiles]) || '').split('\n').filter(Boolean)
832
+ : [];
833
+ const inIndex = new Set(inIndexList);
834
+ const trackedFiles = patchFiles.filter(f => inTree.has(f) || inIndex.has(f));
835
+ const trackedSet = new Set(trackedFiles);
836
+ const untrackedPatchFiles = patchFiles.filter(f => !trackedSet.has(f));
837
+
838
+ // tracked 文件:git diff patchBase(patch 生成锚点,默认 merge-base)
839
+ // 数组形式,文件名逐个展开为独立 argv,不经 shell;
840
+ // encoding:'buffer' 保留二进制补丁原样,timeout 放大到 60s 防大 diff 超时——原裸 execSync 无 timeout
841
+ if (trackedFiles.length > 0) {
754
842
  patchParts.push(git(
755
843
  worktreePath,
756
- ['diff', '--binary', '--cached', '--', ...untrackedPatchFiles],
844
+ ['diff', '--binary', patchBase, '--', ...trackedFiles],
757
845
  { encoding: 'buffer', timeout: 60000 }
758
846
  ));
759
- } finally {
760
- // 重置 index(不保留 staged 状态)
761
- gitQuiet(worktreePath, ['reset', 'HEAD', '--', ...untrackedPatchFiles]);
762
847
  }
763
- }
764
848
 
765
- const patchContent = Buffer.concat(patchParts);
766
- if (patchContent.length === 0) {
767
- // patch 为空(清单中部分文件可能没实际变更)
768
- result.ok = true;
769
- rmSync(tmpDir, { recursive: true, force: true });
770
- return result;
771
- }
849
+ // untracked 新文件:git add 到 index,git diff --cached,然后 reset(均数组形式,文件名逐个展开)
850
+ if (untrackedPatchFiles.length > 0) {
851
+ git(worktreePath, ['add', '--', ...untrackedPatchFiles]);
852
+ try {
853
+ // encoding:'buffer' 保留二进制补丁原样,timeout 放大到 60s 防大 diff 超时
854
+ patchParts.push(git(
855
+ worktreePath,
856
+ ['diff', '--binary', '--cached', '--', ...untrackedPatchFiles],
857
+ { encoding: 'buffer', timeout: 60000 }
858
+ ));
859
+ } finally {
860
+ // 重置 index(不保留 staged 状态)
861
+ gitQuiet(worktreePath, ['reset', 'HEAD', '--', ...untrackedPatchFiles]);
862
+ }
863
+ }
772
864
 
773
- writeFileSync(patchPath, patchContent);
865
+ const patchContent = Buffer.concat(patchParts);
866
+ if (patchContent.length === 0) {
867
+ // patch 为空(清单中部分文件可能没实际变更)
868
+ result.ok = true;
869
+ rmSync(tmpDir, { recursive: true, force: true });
870
+ return result;
871
+ }
774
872
 
775
- // apply --check 预检失败不再拦截(--check 只测 clean apply,--3way 能处理 clean apply 失败的
776
- // 三路合并场景——主干已提交推进时 --check 恒失败但 --3way 可合)。故跳过 --check,直接试 --3way。
873
+ writeFileSync(patchPath, patchContent);
777
874
 
778
- // 回滚准备:记录 patch 涉及的 tracked 文件(--3way 冲突后需恢复 HEAD 版,不留半成品冲突标记)。
779
- // tracked 文件冲突 → git checkout -- <f> 还原;untracked 新建文件(--3way 不会对其冲突)不在回滚范围,
780
- // 但若 --3way 部分成功后冲突,已创建的新文件需删,故记录 untracked 集合。
781
- const trackedPatchFiles = patchFiles.filter(f => {
782
- // 该文件在主仓库 HEAD 存在 → 是 tracked(--3way 冲突时留标记需 checkout 还原)
783
- return gitQuiet(projectRoot, ['cat-file', '-e', `HEAD:${f}`]) === null ? false : true;
784
- });
785
- const newPatchFiles = patchFiles.filter(f => !trackedPatchFiles.includes(f));
875
+ // apply --check 预检失败不再拦截(--check 只测 clean apply,--3way 能处理 clean apply 失败的
876
+ // 三路合并场景——主干已提交推进时 --check 恒失败但 --3way 可合)。故跳过 --check,直接试 --3way。
786
877
 
787
- // apply --3way 正式应用(主干已提交推进时自动三路合并)
788
- try {
789
- git(projectRoot, ['apply', '--3way', patchPath], { timeout: 30000 });
790
- } catch (e) {
791
- // --3way 冲突(exit 1,工作区已留冲突标记):回滚到 apply 前干净状态,不留半成品
792
- // FR-06:解析 git 原始 stderr 提取冲突文件列表(不静默吞掉)
793
- const rawStderr = e.message || '';
794
- const rollback = rollbackApply(projectRoot, trackedPatchFiles, newPatchFiles, rawStderr);
795
- // autocrlf 副作用单独点名:主仓无关未提交 dirty + CRLF 转换可触发 does not match index
796
- // (非文件内容冲突,交集空时 step4.5 已放行到这里)——回滚无损,stash 后重试即可
797
- if (/does not match index/i.test(rawStderr)) {
878
+ // 回滚准备:记录 patch 涉及的 tracked 文件(--3way 冲突后需恢复 HEAD 版,不留半成品冲突标记)。
879
+ // tracked 文件冲突 → git checkout -- <f> 还原;untracked 新建文件(--3way 不会对其冲突)不在回滚范围,
880
+ // 但若 --3way 部分成功后冲突,已创建的新文件需删,故记录 untracked 集合。
881
+ const trackedPatchFiles = patchFiles.filter(f => {
882
+ // 该文件在主仓库 HEAD 存在 → 是 tracked(--3way 冲突时留标记需 checkout 还原)
883
+ return gitQuiet(projectRoot, ['cat-file', '-e', `HEAD:${f}`]) === null ? false : true;
884
+ });
885
+ const newPatchFiles = patchFiles.filter(f => !trackedPatchFiles.includes(f));
886
+
887
+ // apply --3way 正式应用(主干已提交推进时自动三路合并)
888
+ try {
889
+ git(projectRoot, ['apply', '--3way', patchPath], { timeout: 30000 });
890
+ } catch (e) {
891
+ // --3way 冲突(exit 1,工作区已留冲突标记):回滚到 apply 前干净状态,不留半成品
892
+ // FR-06:解析 git 原始 stderr 提取冲突文件列表(不静默吞掉)
893
+ const rawStderr = e.message || '';
894
+ const rollback = rollbackApply(projectRoot, trackedPatchFiles, newPatchFiles, rawStderr);
895
+ // autocrlf 副作用单独点名:主仓无关未提交 dirty + CRLF 转换可触发 does not match index
896
+ // (非文件内容冲突,交集空时 step4.5 已放行到这里)——回滚无损,stash 后重试即可
897
+ if (/does not match index/i.test(rawStderr)) {
898
+ result.errors.push(
899
+ `apply --3way 失败(does not match index):多为主仓未提交文件 + Windows autocrlf 的 CRLF 副作用触发,非文件内容冲突。\n` +
900
+ `已回滚工作区到 apply 前状态(无损,无关未提交文件未受影响)。\n` +
901
+ `处理:git stash 后重试 sillyspec worktree apply ${changeName}(手工 stash 记下 git stash list 的 SHA——pop 失败时兜底),或 --merge 兜底,或 --stash-dirty 由工具自动 stash→apply→恢复。`
902
+ );
903
+ if (rollback.error) result.warnings = (result.warnings || []).concat([`回滚警告: ${rollback.error}`]);
904
+ return result;
905
+ }
798
906
  result.errors.push(
799
- `apply --3way 失败(does not match index):多为主仓未提交文件 + Windows autocrlf 的 CRLF 副作用触发,非文件内容冲突。\n` +
800
- `已回滚工作区到 apply 前状态(无损,无关未提交文件未受影响)。\n` +
801
- `处理:git stash 后重试 sillyspec worktree apply ${changeName},或 --merge 兜底。`
907
+ `apply --3way 冲突:以下文件与主干「已提交」推进重叠,无法自动合并:\n` +
908
+ ` ${rollback.conflicts.length > 0 ? rollback.conflicts.join('\n ') : '(未能获取冲突文件列表)'}\n` +
909
+ `已回滚工作区到 apply 前状态(无半成品冲突标记)。\n` +
910
+ `可选:用 --merge 自动三方合并兜底(git merge sillyspec/${changeName},会引入合并提交):\n` +
911
+ ` sillyspec worktree apply ${changeName} --merge\n` +
912
+ `或手动解决后重试。`
802
913
  );
803
914
  if (rollback.error) result.warnings = (result.warnings || []).concat([`回滚警告: ${rollback.error}`]);
804
915
  return result;
805
916
  }
806
- result.errors.push(
807
- `apply --3way 冲突:以下文件与主干「已提交」推进重叠,无法自动合并:\n` +
808
- ` ${rollback.conflicts.length > 0 ? rollback.conflicts.join('\n ') : '(未能获取冲突文件列表)'}\n` +
809
- `已回滚工作区到 apply 前状态(无半成品冲突标记)。\n` +
810
- `可选:用 --merge 自动三方合并兜底(git merge sillyspec/${changeName},会引入合并提交):\n` +
811
- ` sillyspec worktree apply ${changeName} --merge\n` +
812
- `或手动解决后重试。`
813
- );
814
- if (rollback.error) result.warnings = (result.warnings || []).concat([`回滚警告: ${rollback.error}`]);
815
- return result;
816
- }
817
917
 
818
- result.ok = true;
918
+ result.ok = true;
819
919
 
820
- // --- 7.5 提交复用 pathspec(坑 apply-commit-pathspec-sweep,2026-08-21 实证)---
821
- // apply 后主仓常混有无关未提交文件(他者会话/并行 quick),agent 习惯 `git add <目录>/`
822
- // 会把无关文件扫进暂存需手工剔除。落盘本变更精确 pathspec 供提交直接复用:
823
- // 文件 + result 字段(CLI 输出可照抄 git add -- … / 长清单用 --pathspec-from-file)。
824
- try {
825
- const commitFiles = [...new Set(patchFiles)].sort().filter(Boolean);
826
- result.commitPathspec = commitFiles;
827
- const runtimeRoot = join(projectRoot, '.sillyspec', '.runtime');
828
- mkdirSync(runtimeRoot, { recursive: true });
829
- const pathspecFile = join(runtimeRoot, `apply-pathspec-${changeName}.txt`);
830
- writeFileSync(pathspecFile, commitFiles.join('\n') + '\n');
831
- result.pathspecFile = pathspecFile;
832
- } catch { /* pathspec 落盘失败不影响 apply 结果 */ }
833
-
834
- // --- 8. 成功后自动 cleanup(失败不影响整体结果) ---
835
- // --skip-overlap 时先查 hasUnappliedChanges:跳过文件未落主仓 → 保留 worktree(不触发
836
- // cleanup 的拦截横幅吓人,主动判断 + 温和提示);全部已落地(无跳过残留)才照常清理。
837
- // cleanup 返回值必须消费(坑 ghost-dir-junction-pierce,2026-08-23 实证:apply 后 partial
838
- // 残留被静默丢弃,用户以为已干净、人工 rm -rf 时穿透 junction 删主仓 node_modules)。
839
- const consumeCleanup = (cr) => {
840
- if (cr && (cr.result === 'partial' || (Array.isArray(cr.residual) && cr.residual.length > 0))) {
841
- result.warnings.push(
842
- `⚠️ worktree 部分清理残留(${cr.result}):${(cr.residual || []).join('; ') || 'worktree 目录'}` +
843
- `——Windows 勿直接 rm -rf(会穿透 node_modules junction 删主仓依赖):先 cmd /c rmdir "<worktree>\\node_modules" 解链再删目录,或跑 sillyspec worktree doctor --fix`
844
- )
845
- }
846
- return cr
847
- }
848
- try {
849
- if (skipOverlap) {
850
- const unapplied = wm.hasUnappliedChanges(changeName);
851
- if (unapplied.hasChanges) {
852
- const pend = unapplied.changedFiles || [];
920
+ // --- 7.5 提交复用 pathspec(坑 apply-commit-pathspec-sweep,2026-08-21 实证)---
921
+ // apply 后主仓常混有无关未提交文件(他者会话/并行 quick),agent 习惯 `git add <目录>/`
922
+ // 会把无关文件扫进暂存需手工剔除。落盘本变更精确 pathspec 供提交直接复用:
923
+ // 文件 + result 字段(CLI 输出可照抄 git add -- … / 长清单用 --pathspec-from-file)。
924
+ try {
925
+ const commitFiles = [...new Set(patchFiles)].sort().filter(Boolean);
926
+ result.commitPathspec = commitFiles;
927
+ const runtimeRoot = join(projectRoot, '.sillyspec', '.runtime');
928
+ mkdirSync(runtimeRoot, { recursive: true });
929
+ const pathspecFile = join(runtimeRoot, `apply-pathspec-${changeName}.txt`);
930
+ writeFileSync(pathspecFile, commitFiles.join('\n') + '\n');
931
+ result.pathspecFile = pathspecFile;
932
+ } catch { /* pathspec 落盘失败不影响 apply 结果 */ }
933
+
934
+ // --- 8. 成功后自动 cleanup(失败不影响整体结果) ---
935
+ // --skip-overlap 时先查 hasUnappliedChanges:跳过文件未落主仓 → 保留 worktree(不触发
936
+ // cleanup 的拦截横幅吓人,主动判断 + 温和提示);全部已落地(无跳过残留)才照常清理。
937
+ // cleanup 返回值必须消费(坑 ghost-dir-junction-pierce,2026-08-23 实证:apply 后 partial
938
+ // 残留被静默丢弃,用户以为已干净、人工 rm -rf 时穿透 junction 删主仓 node_modules)。
939
+ const consumeCleanup = (cr) => {
940
+ if (cr && (cr.result === 'partial' || (Array.isArray(cr.residual) && cr.residual.length > 0))) {
853
941
  result.warnings.push(
854
- `worktree 已保留(--skip-overlap 有未应用文件):${pend.length} 个文件仍在 worktree` +
855
- `(${pend.slice(0, 5).join(', ')}${pend.length > 5 ? ' 等' : ''})——主仓提交/stash 后重新 sillyspec worktree apply ${changeName} 只应用剩余文件,或确认放弃后 sillyspec worktree cleanup ${changeName} --force`
856
- );
942
+ `⚠️ worktree 部分清理残留(${cr.result}):${(cr.residual || []).join('; ') || 'worktree 目录'}` +
943
+ `——Windows 勿直接 rm -rf(会穿透 node_modules junction 删主仓依赖):先 cmd /c rmdir "<worktree>\\node_modules" 解链再删目录,或跑 sillyspec worktree doctor --fix`
944
+ )
945
+ }
946
+ return cr
947
+ }
948
+ try {
949
+ if (skipOverlap) {
950
+ const unapplied = wm.hasUnappliedChanges(changeName);
951
+ if (unapplied.hasChanges) {
952
+ const pend = unapplied.changedFiles || [];
953
+ result.warnings.push(
954
+ `worktree 已保留(--skip-overlap 有未应用文件):${pend.length} 个文件仍在 worktree` +
955
+ `(${pend.slice(0, 5).join(', ')}${pend.length > 5 ? ' 等' : ''})——主仓提交/stash 后重新 sillyspec worktree apply ${changeName} 只应用剩余文件,或确认放弃后 sillyspec worktree cleanup ${changeName} --force`
956
+ );
957
+ } else {
958
+ consumeCleanup(wm.cleanup(changeName, { force: true }));
959
+ }
857
960
  } else {
858
961
  consumeCleanup(wm.cleanup(changeName, { force: true }));
859
962
  }
860
- } else {
861
- consumeCleanup(wm.cleanup(changeName, { force: true }));
963
+ } catch (cleanupErr) {
964
+ result.warnings = result.warnings || [];
965
+ result.warnings.push(`cleanup 失败(不影响应用结果;Windows 手动清理先解 junction 再删,勿 rm -rf): ${cleanupErr.message}`);
862
966
  }
863
- } catch (cleanupErr) {
864
- result.warnings = result.warnings || [];
865
- result.warnings.push(`cleanup 失败(不影响应用结果;Windows 手动清理先解 junction 再删,勿 rm -rf): ${cleanupErr.message}`);
866
- }
867
967
 
868
- } catch (e) {
869
- // ENOBUFS 自动降级(坑 apply-spawnsync-enobufs,2026-08-22 实证:大 diff 的 binary patch
870
- // 超 maxBuffer 抛 ENOBUFS,此前只能 agent 手动 git merge 绕行)——git apply 路径走不通时
871
- // 自动落 applyByMerge(既有 --merge 兜底,语义同为三方合并)
872
- if (/ENOBUFS/i.test(String(e.message || e.code || ''))) {
873
- result.warnings = (result.warnings || []).concat(
874
- [`patch 生成超出进程缓冲区(ENOBUFS,超大 diff)——自动降级 git merge 路径应用`]
875
- );
876
- try {
877
- // keepConflicts:false——自动降级路径无人善后冲突状态,维持 abort 回滚干净态
878
- return applyByMerge(result, changeName, projectRoot, wm, { keepConflicts: false });
879
- } catch (mergeErr) {
880
- result.errors.push(`ENOBUFS 降级 merge 也失败: ${mergeErr.message}`);
881
- return result;
968
+ } catch (e) {
969
+ // ENOBUFS 自动降级(坑 apply-spawnsync-enobufs,2026-08-22 实证:大 diff 的 binary patch
970
+ // 超 maxBuffer 抛 ENOBUFS,此前只能 agent 手动 git merge 绕行)——git apply 路径走不通时
971
+ // 自动落 applyByMerge(既有 --merge 兜底,语义同为三方合并)
972
+ if (/ENOBUFS/i.test(String(e.message || e.code || ''))) {
973
+ result.warnings = (result.warnings || []).concat(
974
+ [`patch 生成超出进程缓冲区(ENOBUFS,超大 diff)——自动降级 git merge 路径应用`]
975
+ );
976
+ try {
977
+ // keepConflicts:false——自动降级路径无人善后冲突状态,维持 abort 回滚干净态
978
+ return applyByMerge(result, changeName, projectRoot, wm, { keepConflicts: false });
979
+ } catch (mergeErr) {
980
+ result.errors.push(`ENOBUFS 降级 merge 也失败: ${mergeErr.message}`);
981
+ return result;
982
+ }
882
983
  }
984
+ result.errors.push(`patch 生成/应用异常: ${e.message}`);
985
+ return result;
986
+ } finally {
987
+ // 清理临时目录
988
+ try { rmSync(tmpDir, { recursive: true, force: true }); } catch {}
883
989
  }
884
- result.errors.push(`patch 生成/应用异常: ${e.message}`);
990
+
885
991
  return result;
886
992
  } finally {
887
- // 清理临时目录
888
- try { rmSync(tmpDir, { recursive: true, force: true }); } catch {}
993
+ // stash 恢复(含 --merge 早退 / 各拦截 return / 异常路径——finally 全覆盖,绝不遗漏)
994
+ if (stashInfo) restoreMainStash(projectRoot, stashInfo);
889
995
  }
996
+ }
890
997
 
891
- return result;
998
+ /**
999
+ * --stash-dirty 的收尾恢复(applyWorktree finally 调用)。
1000
+ *
1001
+ * 语义(坑 apply-main-dirty-no-first-class / stash-pop-silent-noop,2026-08-24 用户反馈四期①②):
1002
+ * - 恢复用 `git stash apply --index`(保暂存区状态——普通 pop 会把 staged 降级为 unstaged);
1003
+ * - apply 成功后才 drop 本次条目,drop 后核验栈顶已非本 SHA(用户实证 stash pop 有静默不落地
1004
+ * 形态,退出码不可尽信);
1005
+ * - apply --index 冲突/异常 → stash 条目保留(git apply 失败不 drop),大字打印 SHA 兜底,
1006
+ * 绝不自动丢弃、绝不盲 pop 栈顶(并行外部操作可能插队,先按 SHA 校验栈顶归属)。
1007
+ * @param {string} projectRoot
1008
+ * @param {{ sha: string, marker: string }} stashInfo
1009
+ */
1010
+ function restoreMainStash(projectRoot, { sha, marker }) {
1011
+ // 栈顶归属校验按 SHA(git stash list 行不含 SHA,须 rev-parse 对比)——防并行外部操作插队后误恢复他者条目
1012
+ const headSha = (gitQuiet(projectRoot, ['rev-parse', '--verify', 'stash@{0}']) || '').trim();
1013
+ if (headSha !== sha) {
1014
+ console.error(`⚠️ stash 恢复跳过:栈顶 stash@{0} 已非本次条目(本次 ${sha},栈顶 ${headSha || '空'})——可能被并行操作消费/弹出。若本次条目仍在栈中:git stash list 找 ${sha.slice(0, 8)} 后 git stash apply --index <该ref>`);
1015
+ return;
1016
+ }
1017
+ // 两级恢复:① apply --index(保暂存区状态)——但 apply 本身会把变更留在工作区未提交,stash 树是
1018
+ // 全量快照,--index 的合并对「stash 树内但未被 stash 改动的脏文件」(正是刚 apply 落地的文件)
1019
+ // 会报 local changes would be overwritten;② 退普通 apply(内容保真恢复,staged 扁平化为
1020
+ // unstaged——诚实降级并提示重 add)。两级都失败 → 保留条目 + SHA 兜底,绝不自动丢弃。
1021
+ let restored = null // 'index' | 'plain'
1022
+ try {
1023
+ git(projectRoot, ['stash', 'apply', '--index', 'stash@{0}'], { timeout: 60000 });
1024
+ restored = 'index';
1025
+ } catch (eIndex) {
1026
+ try {
1027
+ git(projectRoot, ['stash', 'apply', 'stash@{0}'], { timeout: 60000 });
1028
+ restored = 'plain';
1029
+ console.warn(`⚠️ 暂存区状态未能完整还原(apply --index 与本次 apply 落地的未提交变更互斥),已退普通恢复——内容保真,staged 文件被扁平化为 unstaged,如需请重新 git add。原因:${String(eIndex.message || eIndex).split('\n').slice(-2)[0] || eIndex}`);
1030
+ } catch (e) {
1031
+ console.error(`⚠️ stash 恢复失败(apply 冲突或异常)——stash 条目已保留(未丢弃),SHA 兜底:${sha}`);
1032
+ console.error(` 处理:git stash list 定位条目(marker 含 "${String(marker || '').slice(0, 50)}");解决工作区冲突后 git stash apply stash@{N} 重试或人工合并;确认无需后再 git stash drop。未跟踪文件若报 already exists,比对内容后手动处理。`);
1033
+ console.error(` git 输出: ${String(e.message || e).split('\n').slice(0, 3).join('\n ')}`);
1034
+ return;
1035
+ }
1036
+ }
1037
+ try {
1038
+ git(projectRoot, ['stash', 'drop', 'stash@{0}'], { timeout: 60000 });
1039
+ // 防静默不落地(用户实证②):drop 后栈顶不得仍是本 SHA
1040
+ const headAfter = gitQuiet(projectRoot, ['rev-parse', '--verify', 'stash@{0}']);
1041
+ if (headAfter && headAfter.trim() === sha) {
1042
+ console.error(`⚠️ stash drop 未生效(栈顶仍为 ${sha})——改动应已恢复,确认 git status 后手动 git stash drop stash@{0}`);
1043
+ } else {
1044
+ console.log(`✅ 主仓在途改动已恢复(${restored === 'index' ? 'apply --index 保留暂存区状态' : '普通恢复,内容保真'})并清理 stash 条目:${sha}`);
1045
+ }
1046
+ } catch (e) {
1047
+ console.error(`⚠️ stash drop 失败(改动应已恢复)——手动 git stash drop stash@{0}(${sha}):${e.message}`);
1048
+ }
892
1049
  }
893
1050
 
894
1051
  /**
@@ -1145,7 +1302,7 @@ export function applyByMerge(result, changeName, projectRoot, wm, opts = {}) {
1145
1302
  result.errors.push(
1146
1303
  `git merge ${branch} 未执行成功——主仓有会被合并覆盖的未提交改动,git 拒绝启动合并(无冲突现场)。\n` +
1147
1304
  `git 输出: ${String(e.message || '').split('\n').slice(0, 3).join(' | ').slice(0, 300)}\n` +
1148
- `请先 commit/stash 主仓改动后重试,或用 --skip-overlap 应用非重叠子集。`
1305
+ `请先 commit/stash 主仓改动后重试,或用 --skip-overlap 应用非重叠子集,或 sillyspec worktree apply ${changeName} --stash-dirty(自动 stash→apply→恢复,保暂存区状态,SHA 兜底)。`
1149
1306
  );
1150
1307
  return result;
1151
1308
  }
@@ -1266,20 +1423,28 @@ export function assessApplyRisk(changeName, { cwd } = {}) {
1266
1423
  const incidentalSet = new Set(
1267
1424
  parseFileChangeListDetailed(designPath).filter(e => e.incidental).map(e => e.path)
1268
1425
  );
1426
+ // review.json 声明偏差文件(坑 apply-undeclared-deviation-block):与顺带修复同等待遇——
1427
+ // reviewer 声明(已过 git 证据校验)的执行期偏差豁免 allowed_paths 严格校验,降 warning 注明来源。
1428
+ const reviewDeclaredSet = new Set(collectReviewDeclaredFiles(projectRoot, changeName).get('main') || []);
1269
1429
 
1270
- // 检查 2: 变更在 allowed_paths 内(仅在 TaskCard 存在时);顺带修复文件豁免。
1430
+ // 检查 2: 变更在 allowed_paths 内(仅在 TaskCard 存在时);顺带修复/review 声明文件豁免。
1271
1431
  // 匹配换 pathMatches(与 Gate1/plan-postcheck 同语义容差),消除原字面前缀弱匹配漂移。
1272
1432
  if (allowedPaths.size > 0) {
1273
1433
  const isIncidental = f => [...incidentalSet].some(ap => pathMatches(f, ap));
1434
+ const isReviewDeclared = f => [...reviewDeclaredSet].some(ap => pathMatches(f, ap));
1274
1435
  const outsideAll = changedFiles.filter(f => ![...allowedPaths].some(allowed => pathMatches(f, allowed)));
1275
- const outsidePaths = outsideAll.filter(f => !isIncidental(f));
1436
+ const outsidePaths = outsideAll.filter(f => !isIncidental(f) && !isReviewDeclared(f));
1276
1437
  const exempted = outsideAll.filter(f => isIncidental(f));
1438
+ const reviewExempted = outsideAll.filter(f => !isIncidental(f) && isReviewDeclared(f));
1277
1439
  if (outsidePaths.length > 0) {
1278
1440
  reasons.push(`变更文件超出 allowed_paths:\n ${outsidePaths.join('\n ')}`);
1279
1441
  }
1280
1442
  if (exempted.length > 0) {
1281
1443
  warnings.push(`顺带修复文件(已豁免 allowed_paths,来源 design §6 标记):${exempted.join(', ')}`);
1282
1444
  }
1445
+ if (reviewExempted.length > 0) {
1446
+ warnings.push(`review 声明偏差文件(已豁免 allowed_paths,来源 task review.json changedFiles,过 git 证据校验):${reviewExempted.join(', ')}`);
1447
+ }
1283
1448
  }
1284
1449
 
1285
1450
  // 检查 4+5: 高风险文件模式