sillyspec 3.27.2 → 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 (398) hide show
  1. package/.claude/skills/sillyspec-execute/SKILL.md +8 -0
  2. package/.claude/skills/sillyspec-quick/SKILL.md +2 -1
  3. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-archive/SKILL.md +87 -0
  4. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-auto/SKILL.md +93 -0
  5. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-brainstorm/SKILL.md +114 -0
  6. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-commit/SKILL.md +67 -0
  7. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-continue/SKILL.md +47 -0
  8. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-doctor/SKILL.md +76 -0
  9. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-execute/SKILL.md +214 -0
  10. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-explore/SKILL.md +102 -0
  11. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-export/SKILL.md +57 -0
  12. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-init/SKILL.md +177 -0
  13. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-knowledge/SKILL.md +270 -0
  14. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-plan/SKILL.md +156 -0
  15. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-quick/SKILL.md +116 -0
  16. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-resume/SKILL.md +70 -0
  17. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-scan/SKILL.md +79 -0
  18. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-state/SKILL.md +64 -0
  19. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-status/SKILL.md +54 -0
  20. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-verify/SKILL.md +87 -0
  21. package/.claude/worktrees/sillyspec-data-model-research/.claude/skills/sillyspec-workspace/SKILL.md +175 -0
  22. package/.claude/worktrees/sillyspec-data-model-research/.gitattributes +2 -0
  23. package/.claude/worktrees/sillyspec-data-model-research/.husky/pre-push +20 -0
  24. package/.claude/worktrees/sillyspec-data-model-research/README.md +203 -0
  25. package/.claude/worktrees/sillyspec-data-model-research/SKILL.md +91 -0
  26. package/.claude/worktrees/sillyspec-data-model-research/bin/sillyspec.js +2 -0
  27. package/.claude/worktrees/sillyspec-data-model-research/logo.jpg +0 -0
  28. package/.claude/worktrees/sillyspec-data-model-research/package-lock.json +977 -0
  29. package/.claude/worktrees/sillyspec-data-model-research/package.json +39 -0
  30. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/dist/assets/index-Bq_Z2hne.js +7446 -0
  31. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/dist/assets/index-O2W5RV4z.css +1 -0
  32. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/dist/favicon.jpg +0 -0
  33. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/dist/index.html +16 -0
  34. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/dist/logo.jpg +0 -0
  35. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/dist/prototype-dashboard.html +836 -0
  36. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/dist/prototype-overview.html +256 -0
  37. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/package.json +25 -0
  38. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/server/executor.js +95 -0
  39. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/server/index.js +679 -0
  40. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/server/parser.js +526 -0
  41. package/.claude/worktrees/sillyspec-data-model-research/packages/dashboard/server/watcher.js +357 -0
  42. package/.claude/worktrees/sillyspec-data-model-research/src/agent-session-log.js +803 -0
  43. package/.claude/worktrees/sillyspec-data-model-research/src/change-list.js +290 -0
  44. package/.claude/worktrees/sillyspec-data-model-research/src/change-risk-profile.js +270 -0
  45. package/.claude/worktrees/sillyspec-data-model-research/src/check-primitives.js +65 -0
  46. package/.claude/worktrees/sillyspec-data-model-research/src/classify-change.js +109 -0
  47. package/.claude/worktrees/sillyspec-data-model-research/src/commit-suggest.js +202 -0
  48. package/.claude/worktrees/sillyspec-data-model-research/src/config-cat.js +88 -0
  49. package/.claude/worktrees/sillyspec-data-model-research/src/config-schema.js +328 -0
  50. package/.claude/worktrees/sillyspec-data-model-research/src/constants.js +97 -0
  51. package/.claude/worktrees/sillyspec-data-model-research/src/contract-matrix.js +480 -0
  52. package/.claude/worktrees/sillyspec-data-model-research/src/datetime.js +20 -0
  53. package/.claude/worktrees/sillyspec-data-model-research/src/db-engine.js +55 -0
  54. package/.claude/worktrees/sillyspec-data-model-research/src/db.js +381 -0
  55. package/.claude/worktrees/sillyspec-data-model-research/src/decision-distill.js +517 -0
  56. package/.claude/worktrees/sillyspec-data-model-research/src/dispatch/backends/local-agent.js +155 -0
  57. package/.claude/worktrees/sillyspec-data-model-research/src/dispatch/backends/sillyhub-mcp.js +245 -0
  58. package/.claude/worktrees/sillyspec-data-model-research/src/dispatch/probe.js +246 -0
  59. package/.claude/worktrees/sillyspec-data-model-research/src/dispatch/strategy.js +121 -0
  60. package/.claude/worktrees/sillyspec-data-model-research/src/docs-check.js +825 -0
  61. package/.claude/worktrees/sillyspec-data-model-research/src/docs-debt.js +393 -0
  62. package/.claude/worktrees/sillyspec-data-model-research/src/docs-gate.js +107 -0
  63. package/.claude/worktrees/sillyspec-data-model-research/src/doctor-diagnostics.js +1099 -0
  64. package/.claude/worktrees/sillyspec-data-model-research/src/endpoint-extractor.js +420 -0
  65. package/.claude/worktrees/sillyspec-data-model-research/src/foreign-declared.js +78 -0
  66. package/.claude/worktrees/sillyspec-data-model-research/src/fs-atomic.js +73 -0
  67. package/.claude/worktrees/sillyspec-data-model-research/src/git-helper.js +150 -0
  68. package/.claude/worktrees/sillyspec-data-model-research/src/hooks/claude-pre-tool-use.cjs +130 -0
  69. package/.claude/worktrees/sillyspec-data-model-research/src/hooks/worktree-guard.js +892 -0
  70. package/.claude/worktrees/sillyspec-data-model-research/src/index.js +2798 -0
  71. package/.claude/worktrees/sillyspec-data-model-research/src/init.js +626 -0
  72. package/.claude/worktrees/sillyspec-data-model-research/src/knowledge-match.js +231 -0
  73. package/.claude/worktrees/sillyspec-data-model-research/src/local-detect.js +128 -0
  74. package/.claude/worktrees/sillyspec-data-model-research/src/local-register.js +104 -0
  75. package/.claude/worktrees/sillyspec-data-model-research/src/machine-interface.js +543 -0
  76. package/.claude/worktrees/sillyspec-data-model-research/src/migrate.js +127 -0
  77. package/.claude/worktrees/sillyspec-data-model-research/src/module-impact.js +166 -0
  78. package/.claude/worktrees/sillyspec-data-model-research/src/module-resolve.js +222 -0
  79. package/.claude/worktrees/sillyspec-data-model-research/src/modules.js +580 -0
  80. package/.claude/worktrees/sillyspec-data-model-research/src/progress/change-registry.js +336 -0
  81. package/.claude/worktrees/sillyspec-data-model-research/src/progress/consistency-doctor.js +355 -0
  82. package/.claude/worktrees/sillyspec-data-model-research/src/progress/shared.js +36 -0
  83. package/.claude/worktrees/sillyspec-data-model-research/src/progress/stage-machine.js +594 -0
  84. package/.claude/worktrees/sillyspec-data-model-research/src/progress/step-store.js +265 -0
  85. package/.claude/worktrees/sillyspec-data-model-research/src/progress.js +1304 -0
  86. package/.claude/worktrees/sillyspec-data-model-research/src/quick-recommend.js +115 -0
  87. package/.claude/worktrees/sillyspec-data-model-research/src/quicklog.js +852 -0
  88. package/.claude/worktrees/sillyspec-data-model-research/src/review-tier.js +77 -0
  89. package/.claude/worktrees/sillyspec-data-model-research/src/run/command.js +1595 -0
  90. package/.claude/worktrees/sillyspec-data-model-research/src/run/complete-handlers.js +1552 -0
  91. package/.claude/worktrees/sillyspec-data-model-research/src/run/complete.js +1259 -0
  92. package/.claude/worktrees/sillyspec-data-model-research/src/run/concurrent-detect.js +156 -0
  93. package/.claude/worktrees/sillyspec-data-model-research/src/run/gates.js +1084 -0
  94. package/.claude/worktrees/sillyspec-data-model-research/src/run/multi-repo-context.js +208 -0
  95. package/.claude/worktrees/sillyspec-data-model-research/src/run/next.js +128 -0
  96. package/.claude/worktrees/sillyspec-data-model-research/src/run/prompt.js +843 -0
  97. package/.claude/worktrees/sillyspec-data-model-research/src/run/quick-audit.js +186 -0
  98. package/.claude/worktrees/sillyspec-data-model-research/src/run/scan-profile.js +269 -0
  99. package/.claude/worktrees/sillyspec-data-model-research/src/run/shared.js +1562 -0
  100. package/.claude/worktrees/sillyspec-data-model-research/src/run/stage.js +584 -0
  101. package/.claude/worktrees/sillyspec-data-model-research/src/run.js +23 -0
  102. package/.claude/worktrees/sillyspec-data-model-research/src/scan-diff.js +388 -0
  103. package/.claude/worktrees/sillyspec-data-model-research/src/scan-postcheck.js +512 -0
  104. package/.claude/worktrees/sillyspec-data-model-research/src/scan-staleness.js +95 -0
  105. package/.claude/worktrees/sillyspec-data-model-research/src/setup.js +414 -0
  106. package/.claude/worktrees/sillyspec-data-model-research/src/sillyhub-mcp/client.js +597 -0
  107. package/.claude/worktrees/sillyspec-data-model-research/src/sillyhub-mcp/config.js +62 -0
  108. package/.claude/worktrees/sillyspec-data-model-research/src/spec-dir-typo.js +50 -0
  109. package/.claude/worktrees/sillyspec-data-model-research/src/spec-sync.js +358 -0
  110. package/.claude/worktrees/sillyspec-data-model-research/src/stage-contract-engine.js +171 -0
  111. package/.claude/worktrees/sillyspec-data-model-research/src/stage-contract-spec.js +550 -0
  112. package/.claude/worktrees/sillyspec-data-model-research/src/stage-contract.js +889 -0
  113. package/.claude/worktrees/sillyspec-data-model-research/src/stage-review.js +597 -0
  114. package/.claude/worktrees/sillyspec-data-model-research/src/stages/archive.js +199 -0
  115. package/.claude/worktrees/sillyspec-data-model-research/src/stages/brainstorm-auto.js +236 -0
  116. package/.claude/worktrees/sillyspec-data-model-research/src/stages/brainstorm.js +617 -0
  117. package/.claude/worktrees/sillyspec-data-model-research/src/stages/cmd-existence.js +145 -0
  118. package/.claude/worktrees/sillyspec-data-model-research/src/stages/doctor.js +540 -0
  119. package/.claude/worktrees/sillyspec-data-model-research/src/stages/execute.js +1275 -0
  120. package/.claude/worktrees/sillyspec-data-model-research/src/stages/explore.js +43 -0
  121. package/.claude/worktrees/sillyspec-data-model-research/src/stages/index.js +29 -0
  122. package/.claude/worktrees/sillyspec-data-model-research/src/stages/knowledge.js +514 -0
  123. package/.claude/worktrees/sillyspec-data-model-research/src/stages/plan-postcheck.js +1344 -0
  124. package/.claude/worktrees/sillyspec-data-model-research/src/stages/plan.js +650 -0
  125. package/.claude/worktrees/sillyspec-data-model-research/src/stages/quick.js +167 -0
  126. package/.claude/worktrees/sillyspec-data-model-research/src/stages/scan.js +608 -0
  127. package/.claude/worktrees/sillyspec-data-model-research/src/stages/status.js +64 -0
  128. package/.claude/worktrees/sillyspec-data-model-research/src/stages/verify.js +246 -0
  129. package/.claude/worktrees/sillyspec-data-model-research/src/sync.js +1470 -0
  130. package/.claude/worktrees/sillyspec-data-model-research/src/task-review.js +1498 -0
  131. package/.claude/worktrees/sillyspec-data-model-research/src/taskcard.js +210 -0
  132. package/.claude/worktrees/sillyspec-data-model-research/src/verify-postcheck.js +1718 -0
  133. package/.claude/worktrees/sillyspec-data-model-research/src/verify-probes.js +277 -0
  134. package/.claude/worktrees/sillyspec-data-model-research/src/version.js +19 -0
  135. package/.claude/worktrees/sillyspec-data-model-research/src/workflow.js +600 -0
  136. package/.claude/worktrees/sillyspec-data-model-research/src/workspace.js +125 -0
  137. package/.claude/worktrees/sillyspec-data-model-research/src/worktree-apply.js +1446 -0
  138. package/.claude/worktrees/sillyspec-data-model-research/src/worktree-deps.js +576 -0
  139. package/.claude/worktrees/sillyspec-data-model-research/src/worktree.js +1715 -0
  140. package/.claude/worktrees/sillyspec-data-model-research/templates/claude-instruction.md +23 -0
  141. package/.claude/worktrees/sillyspec-data-model-research/templates/prompts/taskcard-rules.md +28 -0
  142. package/.claude/worktrees/sillyspec-data-model-research/templates/prompts/testcase-design.md +12 -0
  143. package/.claude/worktrees/sillyspec-data-model-research/templates/prompts/verify-probes.md +32 -0
  144. package/.claude/worktrees/sillyspec-data-model-research/templates/workflows/archive-impact.yaml +79 -0
  145. package/.claude/worktrees/sillyspec-data-model-research/templates/workflows/scan-docs.yaml +132 -0
  146. package/.worktrees/8d2d0392/.claude/skills/sillyspec-archive/SKILL.md +87 -0
  147. package/.worktrees/8d2d0392/.claude/skills/sillyspec-auto/SKILL.md +93 -0
  148. package/.worktrees/8d2d0392/.claude/skills/sillyspec-brainstorm/SKILL.md +114 -0
  149. package/.worktrees/8d2d0392/.claude/skills/sillyspec-commit/SKILL.md +67 -0
  150. package/.worktrees/8d2d0392/.claude/skills/sillyspec-continue/SKILL.md +47 -0
  151. package/.worktrees/8d2d0392/.claude/skills/sillyspec-doctor/SKILL.md +76 -0
  152. package/.worktrees/8d2d0392/.claude/skills/sillyspec-execute/SKILL.md +214 -0
  153. package/.worktrees/8d2d0392/.claude/skills/sillyspec-explore/SKILL.md +102 -0
  154. package/.worktrees/8d2d0392/.claude/skills/sillyspec-export/SKILL.md +57 -0
  155. package/.worktrees/8d2d0392/.claude/skills/sillyspec-init/SKILL.md +177 -0
  156. package/.worktrees/8d2d0392/.claude/skills/sillyspec-knowledge/SKILL.md +270 -0
  157. package/.worktrees/8d2d0392/.claude/skills/sillyspec-plan/SKILL.md +156 -0
  158. package/.worktrees/8d2d0392/.claude/skills/sillyspec-propose/SKILL.md +87 -0
  159. package/.worktrees/8d2d0392/.claude/skills/sillyspec-quick/SKILL.md +116 -0
  160. package/.worktrees/8d2d0392/.claude/skills/sillyspec-resume/SKILL.md +70 -0
  161. package/.worktrees/8d2d0392/.claude/skills/sillyspec-scan/SKILL.md +79 -0
  162. package/.worktrees/8d2d0392/.claude/skills/sillyspec-state/SKILL.md +64 -0
  163. package/.worktrees/8d2d0392/.claude/skills/sillyspec-status/SKILL.md +54 -0
  164. package/.worktrees/8d2d0392/.claude/skills/sillyspec-verify/SKILL.md +87 -0
  165. package/.worktrees/8d2d0392/.claude/skills/sillyspec-workspace/SKILL.md +175 -0
  166. package/.worktrees/8d2d0392/.claude/skills/verify-per-user/SKILL.md +6 -0
  167. package/.worktrees/8d2d0392/.gitattributes +2 -0
  168. package/.worktrees/8d2d0392/.husky/pre-push +20 -0
  169. package/.worktrees/8d2d0392/README.md +203 -0
  170. package/.worktrees/8d2d0392/SKILL.md +91 -0
  171. package/.worktrees/8d2d0392/architecture-analysis.md +448 -0
  172. package/.worktrees/8d2d0392/bin/sillyspec.js +2 -0
  173. package/.worktrees/8d2d0392/eval/README.md +86 -0
  174. package/.worktrees/8d2d0392/eval/eval.config.json +28 -0
  175. package/.worktrees/8d2d0392/eval/lib/adapters/cli.mjs +63 -0
  176. package/.worktrees/8d2d0392/eval/lib/adapters/dryrun.mjs +27 -0
  177. package/.worktrees/8d2d0392/eval/lib/config.mjs +82 -0
  178. package/.worktrees/8d2d0392/eval/lib/db.mjs +76 -0
  179. package/.worktrees/8d2d0392/eval/lib/report.mjs +120 -0
  180. package/.worktrees/8d2d0392/eval/lib/runner.mjs +157 -0
  181. package/.worktrees/8d2d0392/eval/lib/tasks.mjs +73 -0
  182. package/.worktrees/8d2d0392/eval/lib/util.mjs +107 -0
  183. package/.worktrees/8d2d0392/eval/lib/workdir.mjs +30 -0
  184. package/.worktrees/8d2d0392/eval/run.mjs +83 -0
  185. package/.worktrees/8d2d0392/eval/tasks/001-slugify/files/package.json +6 -0
  186. package/.worktrees/8d2d0392/eval/tasks/001-slugify/solution/src/slugify.mjs +26 -0
  187. package/.worktrees/8d2d0392/eval/tasks/001-slugify/task.json +6 -0
  188. package/.worktrees/8d2d0392/eval/tasks/001-slugify/verify.mjs +28 -0
  189. package/.worktrees/8d2d0392/eval/tasks/002-each-day/files/package.json +6 -0
  190. package/.worktrees/8d2d0392/eval/tasks/002-each-day/files/src/dates.mjs +4 -0
  191. package/.worktrees/8d2d0392/eval/tasks/002-each-day/solution/src/dates.mjs +30 -0
  192. package/.worktrees/8d2d0392/eval/tasks/002-each-day/task.json +6 -0
  193. package/.worktrees/8d2d0392/eval/tasks/002-each-day/verify.mjs +31 -0
  194. package/.worktrees/8d2d0392/eval/tasks/003-word-report/files/data/notes.txt +5 -0
  195. package/.worktrees/8d2d0392/eval/tasks/003-word-report/files/package.json +6 -0
  196. package/.worktrees/8d2d0392/eval/tasks/003-word-report/solution/bin/report.mjs +36 -0
  197. package/.worktrees/8d2d0392/eval/tasks/003-word-report/task.json +6 -0
  198. package/.worktrees/8d2d0392/eval/tasks/003-word-report/verify.mjs +38 -0
  199. package/.worktrees/8d2d0392/logo.jpg +0 -0
  200. package/.worktrees/8d2d0392/package-lock.json +977 -0
  201. package/.worktrees/8d2d0392/package.json +41 -0
  202. package/.worktrees/8d2d0392/packages/dashboard/dist/assets/index-Bq_Z2hne.js +7446 -0
  203. package/.worktrees/8d2d0392/packages/dashboard/dist/assets/index-O2W5RV4z.css +1 -0
  204. package/.worktrees/8d2d0392/packages/dashboard/dist/favicon.jpg +0 -0
  205. package/.worktrees/8d2d0392/packages/dashboard/dist/index.html +16 -0
  206. package/.worktrees/8d2d0392/packages/dashboard/dist/logo.jpg +0 -0
  207. package/.worktrees/8d2d0392/packages/dashboard/dist/prototype-dashboard.html +836 -0
  208. package/.worktrees/8d2d0392/packages/dashboard/dist/prototype-overview.html +256 -0
  209. package/.worktrees/8d2d0392/packages/dashboard/package.json +25 -0
  210. package/.worktrees/8d2d0392/packages/dashboard/server/executor.js +95 -0
  211. package/.worktrees/8d2d0392/packages/dashboard/server/index.js +679 -0
  212. package/.worktrees/8d2d0392/packages/dashboard/server/parser.js +526 -0
  213. package/.worktrees/8d2d0392/packages/dashboard/server/watcher.js +357 -0
  214. package/.worktrees/8d2d0392/src/agent-session-log.js +803 -0
  215. package/.worktrees/8d2d0392/src/change-list.js +290 -0
  216. package/.worktrees/8d2d0392/src/change-risk-profile.js +339 -0
  217. package/.worktrees/8d2d0392/src/check-primitives.js +65 -0
  218. package/.worktrees/8d2d0392/src/classify-change.js +109 -0
  219. package/.worktrees/8d2d0392/src/commit-suggest.js +202 -0
  220. package/.worktrees/8d2d0392/src/config-cat.js +88 -0
  221. package/.worktrees/8d2d0392/src/config-schema.js +328 -0
  222. package/.worktrees/8d2d0392/src/constants.js +97 -0
  223. package/.worktrees/8d2d0392/src/contract-matrix.js +533 -0
  224. package/.worktrees/8d2d0392/src/datetime.js +20 -0
  225. package/.worktrees/8d2d0392/src/db-engine.js +55 -0
  226. package/.worktrees/8d2d0392/src/db.js +381 -0
  227. package/.worktrees/8d2d0392/src/decision-distill.js +517 -0
  228. package/.worktrees/8d2d0392/src/dispatch/backends/local-agent.js +155 -0
  229. package/.worktrees/8d2d0392/src/dispatch/backends/sillyhub-mcp.js +245 -0
  230. package/.worktrees/8d2d0392/src/dispatch/probe.js +246 -0
  231. package/.worktrees/8d2d0392/src/dispatch/strategy.js +121 -0
  232. package/.worktrees/8d2d0392/src/docs-check.js +825 -0
  233. package/.worktrees/8d2d0392/src/docs-debt.js +393 -0
  234. package/.worktrees/8d2d0392/src/docs-gate.js +107 -0
  235. package/.worktrees/8d2d0392/src/doctor-diagnostics.js +1099 -0
  236. package/.worktrees/8d2d0392/src/endpoint-extractor.js +409 -0
  237. package/.worktrees/8d2d0392/src/foreign-declared.js +78 -0
  238. package/.worktrees/8d2d0392/src/fs-atomic.js +73 -0
  239. package/.worktrees/8d2d0392/src/git-helper.js +150 -0
  240. package/.worktrees/8d2d0392/src/hooks/claude-pre-tool-use.cjs +130 -0
  241. package/.worktrees/8d2d0392/src/hooks/worktree-guard.js +892 -0
  242. package/.worktrees/8d2d0392/src/index.js +2854 -0
  243. package/.worktrees/8d2d0392/src/init.js +626 -0
  244. package/.worktrees/8d2d0392/src/knowledge-match.js +231 -0
  245. package/.worktrees/8d2d0392/src/local-detect.js +128 -0
  246. package/.worktrees/8d2d0392/src/local-register.js +104 -0
  247. package/.worktrees/8d2d0392/src/machine-interface.js +543 -0
  248. package/.worktrees/8d2d0392/src/migrate.js +127 -0
  249. package/.worktrees/8d2d0392/src/module-impact.js +166 -0
  250. package/.worktrees/8d2d0392/src/module-resolve.js +222 -0
  251. package/.worktrees/8d2d0392/src/modules.js +580 -0
  252. package/.worktrees/8d2d0392/src/plan-adopt-waves.js +126 -0
  253. package/.worktrees/8d2d0392/src/progress/change-registry.js +336 -0
  254. package/.worktrees/8d2d0392/src/progress/consistency-doctor.js +355 -0
  255. package/.worktrees/8d2d0392/src/progress/shared.js +36 -0
  256. package/.worktrees/8d2d0392/src/progress/stage-machine.js +594 -0
  257. package/.worktrees/8d2d0392/src/progress/step-store.js +265 -0
  258. package/.worktrees/8d2d0392/src/progress.js +1304 -0
  259. package/.worktrees/8d2d0392/src/quick-recommend.js +115 -0
  260. package/.worktrees/8d2d0392/src/quicklog.js +883 -0
  261. package/.worktrees/8d2d0392/src/review-tier.js +77 -0
  262. package/.worktrees/8d2d0392/src/run/command.js +1641 -0
  263. package/.worktrees/8d2d0392/src/run/complete-handlers.js +1552 -0
  264. package/.worktrees/8d2d0392/src/run/complete.js +1259 -0
  265. package/.worktrees/8d2d0392/src/run/concurrent-detect.js +156 -0
  266. package/.worktrees/8d2d0392/src/run/gates.js +1094 -0
  267. package/.worktrees/8d2d0392/src/run/multi-repo-context.js +208 -0
  268. package/.worktrees/8d2d0392/src/run/next.js +128 -0
  269. package/.worktrees/8d2d0392/src/run/prompt.js +843 -0
  270. package/.worktrees/8d2d0392/src/run/quick-audit.js +186 -0
  271. package/.worktrees/8d2d0392/src/run/scan-profile.js +269 -0
  272. package/.worktrees/8d2d0392/src/run/shared.js +1562 -0
  273. package/.worktrees/8d2d0392/src/run/stage.js +587 -0
  274. package/.worktrees/8d2d0392/src/run.js +23 -0
  275. package/.worktrees/8d2d0392/src/scan-diff.js +388 -0
  276. package/.worktrees/8d2d0392/src/scan-postcheck.js +524 -0
  277. package/.worktrees/8d2d0392/src/scan-staleness.js +95 -0
  278. package/.worktrees/8d2d0392/src/setup.js +414 -0
  279. package/.worktrees/8d2d0392/src/sillyhub-mcp/client.js +597 -0
  280. package/.worktrees/8d2d0392/src/sillyhub-mcp/config.js +62 -0
  281. package/.worktrees/8d2d0392/src/spec-dir-typo.js +50 -0
  282. package/.worktrees/8d2d0392/src/spec-sync.js +358 -0
  283. package/.worktrees/8d2d0392/src/stage-contract-engine.js +171 -0
  284. package/.worktrees/8d2d0392/src/stage-contract-spec.js +551 -0
  285. package/.worktrees/8d2d0392/src/stage-contract.js +948 -0
  286. package/.worktrees/8d2d0392/src/stage-review.js +597 -0
  287. package/.worktrees/8d2d0392/src/stages/archive.js +199 -0
  288. package/.worktrees/8d2d0392/src/stages/brainstorm-auto.js +285 -0
  289. package/.worktrees/8d2d0392/src/stages/brainstorm.js +624 -0
  290. package/.worktrees/8d2d0392/src/stages/cmd-existence.js +145 -0
  291. package/.worktrees/8d2d0392/src/stages/doctor.js +540 -0
  292. package/.worktrees/8d2d0392/src/stages/execute.js +1277 -0
  293. package/.worktrees/8d2d0392/src/stages/explore.js +43 -0
  294. package/.worktrees/8d2d0392/src/stages/index.js +29 -0
  295. package/.worktrees/8d2d0392/src/stages/knowledge.js +514 -0
  296. package/.worktrees/8d2d0392/src/stages/plan-postcheck.js +1398 -0
  297. package/.worktrees/8d2d0392/src/stages/plan.js +651 -0
  298. package/.worktrees/8d2d0392/src/stages/quick.js +167 -0
  299. package/.worktrees/8d2d0392/src/stages/scan.js +608 -0
  300. package/.worktrees/8d2d0392/src/stages/status.js +64 -0
  301. package/.worktrees/8d2d0392/src/stages/verify.js +246 -0
  302. package/.worktrees/8d2d0392/src/sync.js +1470 -0
  303. package/.worktrees/8d2d0392/src/task-review.js +1498 -0
  304. package/.worktrees/8d2d0392/src/taskcard-placeholders.js +21 -0
  305. package/.worktrees/8d2d0392/src/taskcard.js +217 -0
  306. package/.worktrees/8d2d0392/src/verify-postcheck.js +1718 -0
  307. package/.worktrees/8d2d0392/src/verify-probes.js +327 -0
  308. package/.worktrees/8d2d0392/src/version.js +19 -0
  309. package/.worktrees/8d2d0392/src/workflow.js +600 -0
  310. package/.worktrees/8d2d0392/src/workspace.js +125 -0
  311. package/.worktrees/8d2d0392/src/worktree-apply.js +1611 -0
  312. package/.worktrees/8d2d0392/src/worktree-deps.js +576 -0
  313. package/.worktrees/8d2d0392/src/worktree.js +1838 -0
  314. package/.worktrees/8d2d0392/templates/claude-instruction.md +23 -0
  315. package/.worktrees/8d2d0392/templates/prompts/taskcard-rules.md +29 -0
  316. package/.worktrees/8d2d0392/templates/prompts/testcase-design.md +12 -0
  317. package/.worktrees/8d2d0392/templates/prompts/verify-probes.md +32 -0
  318. package/.worktrees/8d2d0392/templates/workflows/archive-impact.yaml +79 -0
  319. package/.worktrees/8d2d0392/templates/workflows/scan-docs.yaml +132 -0
  320. package/architecture-analysis.md +448 -0
  321. package/eval/README.md +86 -0
  322. package/eval/eval.config.json +28 -0
  323. package/eval/lib/adapters/cli.mjs +63 -0
  324. package/eval/lib/adapters/dryrun.mjs +27 -0
  325. package/eval/lib/config.mjs +82 -0
  326. package/eval/lib/db.mjs +76 -0
  327. package/eval/lib/report.mjs +120 -0
  328. package/eval/lib/runner.mjs +157 -0
  329. package/eval/lib/tasks.mjs +73 -0
  330. package/eval/lib/util.mjs +107 -0
  331. package/eval/lib/workdir.mjs +30 -0
  332. package/eval/run.mjs +83 -0
  333. package/eval/tasks/001-slugify/files/package.json +6 -0
  334. package/eval/tasks/001-slugify/solution/src/slugify.mjs +26 -0
  335. package/eval/tasks/001-slugify/task.json +6 -0
  336. package/eval/tasks/001-slugify/verify.mjs +28 -0
  337. package/eval/tasks/002-each-day/files/package.json +6 -0
  338. package/eval/tasks/002-each-day/files/src/dates.mjs +4 -0
  339. package/eval/tasks/002-each-day/solution/src/dates.mjs +30 -0
  340. package/eval/tasks/002-each-day/task.json +6 -0
  341. package/eval/tasks/002-each-day/verify.mjs +31 -0
  342. package/eval/tasks/003-word-report/files/data/notes.txt +5 -0
  343. package/eval/tasks/003-word-report/files/package.json +6 -0
  344. package/eval/tasks/003-word-report/solution/bin/report.mjs +36 -0
  345. package/eval/tasks/003-word-report/task.json +6 -0
  346. package/eval/tasks/003-word-report/verify.mjs +38 -0
  347. package/package.json +4 -2
  348. package/src/agent-session-log.js +45 -5
  349. package/src/change-risk-profile.js +83 -14
  350. package/src/config-schema.js +18 -3
  351. package/src/contract-matrix.js +90 -29
  352. package/src/datetime.js +20 -0
  353. package/src/decision-distill.js +517 -0
  354. package/src/dispatch/backends/local-agent.js +4 -4
  355. package/src/docs-check.js +227 -0
  356. package/src/docs-debt.js +187 -24
  357. package/src/doctor-diagnostics.js +102 -2
  358. package/src/endpoint-extractor.js +41 -52
  359. package/src/foreign-declared.js +155 -0
  360. package/src/index.js +95 -13
  361. package/src/init.js +9 -7
  362. package/src/knowledge-match.js +107 -6
  363. package/src/local-register.js +7 -1
  364. package/src/module-resolve.js +12 -1
  365. package/src/modules.js +2 -1
  366. package/src/plan-adopt-waves.js +126 -0
  367. package/src/quicklog.js +50 -4
  368. package/src/run/command.js +124 -44
  369. package/src/run/complete-handlers.js +48 -19
  370. package/src/run/complete.js +5 -2
  371. package/src/run/gates.js +104 -22
  372. package/src/run/prompt.js +84 -42
  373. package/src/run/quick-audit.js +11 -0
  374. package/src/run/shared.js +152 -10
  375. package/src/run/stage.js +8 -5
  376. package/src/run.js +2 -2
  377. package/src/scan-postcheck.js +30 -17
  378. package/src/stage-contract-spec.js +3 -2
  379. package/src/stage-contract.js +68 -4
  380. package/src/stages/archive.js +53 -12
  381. package/src/stages/brainstorm-auto.js +50 -1
  382. package/src/stages/brainstorm.js +13 -0
  383. package/src/stages/doctor.js +157 -1
  384. package/src/stages/execute.js +32 -6
  385. package/src/stages/plan-postcheck.js +76 -17
  386. package/src/stages/plan.js +9 -4
  387. package/src/stages/quick.js +6 -1
  388. package/src/stages/verify.js +32 -15
  389. package/src/sync.js +41 -3
  390. package/src/task-review.js +2 -2
  391. package/src/taskcard-placeholders.js +21 -0
  392. package/src/taskcard.js +43 -1
  393. package/src/verify-postcheck.js +315 -13
  394. package/src/verify-probes.js +73 -10
  395. package/src/worktree-apply.js +569 -227
  396. package/src/worktree-deps.js +150 -1
  397. package/src/worktree.js +285 -77
  398. package/templates/prompts/taskcard-rules.md +2 -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
  *
@@ -329,7 +369,62 @@ function validateCrossRepoNoOp(ctx, projectRoot, changeName) {
329
369
  * crossRepoValidated?: Array<{ repo: string, head: string }>
330
370
  * }}
331
371
  */
332
- export function applyWorktree(changeName, { cwd, checkOnly = false, merge = false, base = 'merge-base', ctx = null } = {}) {
372
+ /**
373
+ * 主仓级互斥锁(坑 main-apply-no-mutex → 泛化 main-repo-no-mutex,2026-08-23 二批实证:
374
+ * 除 apply 外,cleanup(worktree 注册表/分支删除)、archive 收尾(目录 rename + 共享 index
375
+ * 的 git add + marker 删除)同样直接改主仓共享状态且零互斥——两会话并发操作互踩。泛化为
376
+ * withMainRepoLock:同一把主仓锁保护所有「写主仓的破坏性短操作」(apply / cleanup / archive
377
+ * 收尾);verify 的长时间测试执行**不**上锁(读树为主,靠对账归属过滤与归因提示治误伤)。
378
+ *
379
+ * 锁粒度 = 主仓级(竞争资源是 main 工作区/.git 状态,非 change):O_EXCL 文件锁复用
380
+ * quicklog 的 withFileLock(stale 偷锁 + rename 防 TOCTOU),锁内容写
381
+ * {pid, changeName, purpose, startedAt} 供超时报错展示持有者。staleMs 10min(大 diff/deps
382
+ * 可慢);抢锁等待 60s 仍失败 → fail-closed 报错退出:写主仓操作并发互踩不可自动恢复,
383
+ * 宁可明确失败让人重试,不硬闯。只读路径(--check-only/status)不加锁。
384
+ */
385
+ export async function withMainRepoLock(projectRoot, changeName, purpose, fn, opts = {}) {
386
+ const { withFileLock } = await import('./quicklog.js');
387
+ const lockPath = join(projectRoot, '.sillyspec', '.runtime', 'main-repo.lock');
388
+ const holder = JSON.stringify({ pid: process.pid, changeName, purpose: purpose || 'unknown', startedAt: new Date().toISOString() });
389
+ const { staleMs = 10 * 60 * 1000, retryMs = 200 } = opts;
390
+ // 等待时长可被 env 覆盖(测试与紧急调参用;opts.timeoutMs 显式传入仍最高优先)
391
+ const envTimeout = parseInt(process.env.SILLYSPEC_MAIN_REPO_LOCK_TIMEOUT_MS || '', 10);
392
+ const defaultTimeout = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : 60 * 1000;
393
+ const { timeoutMs = defaultTimeout } = opts;
394
+ // 进程退出兜底清锁:临界区内 process.exit(如 archiveChangeDirectory 的 guard exit(1))不会走
395
+ // withFileLock 的 finally——不挂此钩子锁会残留挡他者直到 staleMs(10min)被偷。正常路径
396
+ // finally 先释放并注销钩子,钩子只在进程真正退出时执行,无双删竞态。
397
+ const onExit = () => { try { unlinkSync(lockPath) } catch {} };
398
+ process.on('exit', onExit);
399
+ try {
400
+ return await withFileLock(lockPath, fn, {
401
+ content: holder,
402
+ staleMs,
403
+ timeoutMs,
404
+ retryMs,
405
+ });
406
+ } catch (e) {
407
+ if (/文件锁超时/.test(String(e.message))) {
408
+ let holderInfo = '';
409
+ try {
410
+ const raw = readFileSync(lockPath, 'utf8');
411
+ try {
412
+ const h = JSON.parse(raw);
413
+ holderInfo = `(持有者: pid=${h.pid}, change=${h.changeName}, 操作=${h.purpose}, 始于 ${h.startedAt})`;
414
+ } catch { holderInfo = `(持有者标识: ${raw.slice(0, 120)})`; }
415
+ } catch { /* 锁文件已被释放(竞态窗口)→ 无持有者信息 */ }
416
+ throw new Error(
417
+ `主仓互斥锁被占用${holderInfo}:另一会话正在对主仓执行写操作(apply/cleanup/归档会写主仓工作区与 git 状态,并发互踩会互相清文件)。` +
418
+ `等它完成后重试即可;若确认持有进程已崩溃退出,删除锁文件后重试:${lockPath}`
419
+ );
420
+ }
421
+ throw e;
422
+ } finally {
423
+ process.removeListener('exit', onExit);
424
+ }
425
+ }
426
+
427
+ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = false, base = 'merge-base', ctx = null, skipOverlap = false, stashDirty = false } = {}) {
333
428
  const projectRoot = cwd || process.cwd();
334
429
  const wm = new WorktreeManager({ cwd: projectRoot });
335
430
  const meta = wm.getMeta(changeName);
@@ -344,6 +439,7 @@ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = fals
344
439
  errors: [],
345
440
  merged: false,
346
441
  crossRepoValidated: [],
442
+ skippedOverlapFiles: [],
347
443
  };
348
444
 
349
445
  // --- 0. 跨仓 task no-op 校验(task-05 / D-009) ---
@@ -446,6 +542,29 @@ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = fals
446
542
  // (主仓 worktree diff 只含主仓文件,跨仓文件在跨仓仓不进主仓 worktree diff)。跨仓 allowed_paths
447
543
  // 仅作 Map 切片返回供上游用,主流程不消费(跨仓 apply=no-op,D-009)。
448
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
+ }
449
568
  const allowSet = allowMap.get('main') || new Set();
450
569
  const hasAllowList = allowSet.size > 0;
451
570
 
@@ -464,6 +583,20 @@ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = fals
464
583
  if (wtBlob === mainBlob) continue;
465
584
  result.hashMismatchFiles.push(f);
466
585
  }
586
+ // 派生产物基线漂移 advisory(坑 derived-artifact-stale-baseline,2026-08-23 实证:多 agent
587
+ // 并发仓中 worktree 旧基线生成的 api-types 被 apply 落地,把并行变更已合入主仓的新枚举刷掉,
588
+ // 一次 build 红)。hashMismatchFiles 此前只在 rescue 分类 / merge 冲突时冒头——语义级覆盖
589
+ // (旧内容文本可合 → --3way 静默成功)零提示。纯 warning 不阻断(生成器类变更的产物是合法
590
+ // 交付,是否重跑生成命令由 agent 判断)。
591
+ {
592
+ const derivedRisk = result.hashMismatchFiles.filter(f => changedFiles.includes(f));
593
+ if (derivedRisk.length > 0) {
594
+ result.warnings = (result.warnings || []).concat([
595
+ `${derivedRisk.length} 个变更文件在 worktree 基线后主仓已有新提交(并行变更可能已合入):${derivedRisk.slice(0, 5).join(', ')}${derivedRisk.length > 5 ? ' 等' : ''}` +
596
+ `——若其中含生成产物(api-types/generated 等),本次 apply 可能以旧基线内容覆盖已合入的新内容;apply 后在新基线重跑生成命令(如 gen:types)再验证`
597
+ ]);
598
+ }
599
+ }
467
600
 
468
601
  // --- 4. 校验:变更文件 ⊆ 清单(无清单则跳过)---
469
602
  if (hasAllowList) {
@@ -471,7 +604,7 @@ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = fals
471
604
  if (violations.length > 0) {
472
605
  result.extraFiles.push(...violations);
473
606
  result.errors.push(
474
- `文件清单校验失败:以下变更文件不在 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 清单补行)`
475
608
  );
476
609
  // checkOnly(assess)模式不短路:继续跑 Gate3,收集所有道供一次报全(坑 worktree-execute-apply-friction 坑4)。
477
610
  // 真实 apply(checkOnly=false)仍短路,保安全。
@@ -479,58 +612,178 @@ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = fals
479
612
  }
480
613
  }
481
614
 
482
- // --- 4.6 显式 --merge:用户显式选择 git merge 兜底(主干已提交推进重叠时的三方合并) ---
483
- // 触发点从「4.5 baseline 漂移自动降级」改为「用户显式 --merge flag」(D-001 保留,触发方式变化)。
484
- // 用 --merge 时跳过未提交 dirty 拦截——merge 同样要求工作区相对干净,此处仅提示风险,真正失败由 applyByMerge 报告。
485
- if (merge && !checkOnly) {
486
- return applyByMerge(result, changeName, projectRoot, wm);
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
+ }
487
648
  }
488
649
 
489
- // --- 4.5 校验:主工作区「未提交」脏文件是否与本次变更重叠(overlap-only 拦截)---
490
- // 分工:4.5(排除规则下 dirty∩changedFiles)+ 5a(更宽口径的同一交集)挡「未提交」dirty 重叠;
491
- // 5b 管「已提交」HEAD 分叉(已放宽)。
492
- // 2026-08-20 放宽(原全量拦截 → 只拦重叠):原「排除规则下任何未提交文件即整体拒绝」会把与本次
493
- // 变更无关的脏文件也硬挡,用户被迫走 rescue cp 手动路径。重叠(dirtyFiles ∩ changedFiles,
494
- // changedFiles 已含删除文件与 worktree 新增同名文件)才是 git apply 无法安全应用的实际危险区。
495
- // 残余风险与兜底(Windows/autocrlf):实测 autocrlf on 时 git apply --3way 对 dirty 工作区可报
496
- // `does not match index`(哪怕脏文件与 patch 不重叠;autocrlf off 时能干净应用,非 git 本质限制)。
497
- // 交集空前提下该失败是安全的:step7 catch → rollbackApply 只 checkout/删除 patch 涉及文件
498
- // (这些文件 apply 前无未提交修改,还原 = apply 前状态),无关脏文件不在 patch/rollback 范围
499
- // 不受影响 → fail-safe,报错后 stash 重试即可。放行时 warning 提示此路径。
500
- // 排除非交付物的元数据/文档 churn(execute 自身改的 + 多操作者常改的 agent 指引/文档),
501
- // 否则别人改 CLAUDE.md/docs/.claude → 判定 dirty → apply 误阻断(多操作者仓库高频踩坑)。
502
- // 注意:排除规则必须和 computeBaselineHash (worktree.js) 一致(虽已不比对 hash,仍用同一口径判当前 dirty)。
503
- if (meta.baselineHash) {
504
- // pathspec:`--` 结束选项,`.` 包含全部,后续 :(exclude) 排除非交付物元数据/文档 churn
505
- // (与 computeBaselineHash 同口径)。数组形式逐元素传递,:(exclude) magic 字面直传不经 shell。
506
- const exclude = ['--', '.', ':(exclude).sillyspec/', ':(exclude).claude/', ':(exclude)docs/', ':(exclude)CLAUDE.md'];
507
- const staged = gitQuiet(projectRoot, ['diff', '--cached', ...exclude]) || '';
508
- const unstaged = gitQuiet(projectRoot, ['diff', ...exclude]) || '';
509
- const untracked = gitQuiet(projectRoot, ['ls-files', '--others', '--exclude-standard', ...exclude]) || '';
510
- // 意图(与 computeBaselineHash 注释一致):只看「未提交 dirty」——git apply --3way 对 dirty 工作区不稳。
511
- // 不比对 hash 是否等于 execute 启动时 baselineHash:主仓 dirty→clean(execute 期间 commit 无关文件)后
512
- // hash 必变,若仍比对会永久死锁(须手改 meta.baselineHash)。改判「排除规则下当前是否有未提交 dirty」。
513
- const hasUncommittedDirty = staged !== '' || unstaged !== '' || untracked !== '';
514
- if (hasUncommittedDirty) {
515
- const dirtyFiles = [...new Set(
516
- ((gitQuiet(projectRoot, ['diff', '--name-only', 'HEAD']) || '').split('\n').filter(Boolean))
517
- .concat((gitQuiet(projectRoot, ['ls-files', '--others', '--exclude-standard']) || '').split('\n').filter(Boolean))
518
- )].filter(f => !f.startsWith('.sillyspec/') && f !== 'meta.json');
519
- const overlapDirty = dirtyFiles.filter(f => changedFiles.includes(f));
520
- if (overlapDirty.length > 0) {
521
- // 重叠拦截:只有与本次变更同文件的未提交改动才无法安全 apply(列重叠文件,非全部脏文件)
522
- const rescueDirty = computeRescueDirtyFiles(projectRoot);
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 口径差集,防御性同处理)
759
+ if (skipOverlap && !checkOnly) {
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));
765
+ result.changedFiles = changedFiles;
766
+ result.deletedFiles = deletedFiles.filter(f => !skipSet5a.has(f));
767
+ result.hashMismatchFiles = (result.hashMismatchFiles || []).filter(f => !skipSet5a.has(f));
768
+ if (changedFiles.length === 0) {
769
+ result.errors.push(
770
+ `--skip-overlap:变更文件全部与主仓未提交改动重叠,无可应用子集:\n ${conflictDirty.join('\n ')}\n` +
771
+ `请先提交/stash 主仓改动后重试,或 sillyspec worktree apply ${changeName} --stash-dirty(工具内置 stash→apply→恢复,保暂存区状态,SHA 兜底可审计)。`
772
+ );
773
+ return result;
774
+ }
775
+ result.warnings = (result.warnings || []).concat([
776
+ `--skip-overlap(5a 口径):再剔除 ${conflictDirty.length} 个重叠文件:${conflictDirty.join(', ')}`
777
+ ]);
778
+ } else {
779
+ const rescueDirty5a = computeRescueDirtyFiles(projectRoot);
523
780
  result.rescueCommands = generateRescueCommands({
524
- changedFiles,
525
- dirtyFiles: rescueDirty,
526
- hashMismatchFiles: result.hashMismatchFiles,
527
- deletedFiles: result.deletedFiles,
528
- worktreePath,
529
- projectRoot,
781
+ changedFiles, dirtyFiles: rescueDirty5a, hashMismatchFiles: result.hashMismatchFiles,
782
+ deletedFiles: result.deletedFiles, worktreePath, projectRoot,
530
783
  });
531
784
  result.errors.push(
532
- `主工作区以下未提交文件与本次 apply 的变更重叠,git apply 无法安全应用:\n ${overlapDirty.join('\n ')}\n` +
533
- `请先提交或暂存这些改动,再重新 apply:\n git add -A && git commit -m "..." 或 git stash\n` +
785
+ `主工作区有以下未 commit 的变更,会影响 apply:\n ${conflictDirty.join('\n ')}\n请先 commit 或 stash 这些变更。` +
786
+ `或应用非重叠部分:sillyspec worktree apply ${changeName} --skip-overlap` +
534
787
  (result.rescueCommands.commands.length > 0 || result.rescueCommands.warnings.length > 0
535
788
  ? `或手动 rescue(旁路 git apply,逐文件 cp 安全子集;cp 后需手动 sillyspec worktree cleanup ${changeName}):\n` +
536
789
  result.rescueCommands.commands.map(c => ` ${c}`).join('\n') +
@@ -539,210 +792,260 @@ export function applyWorktree(changeName, { cwd, checkOnly = false, merge = fals
539
792
  : '')
540
793
  );
541
794
  if (!checkOnly) return result; // checkOnly 收集不短路(一次报全);真实 apply 短路
542
- } else {
543
- // 无关脏文件放行(只校验重叠文件):--3way 若因 autocrlf 报 does not match index 会被
544
- // step7 catch 回滚(交集空前提下无损,见上注释),stash 后重试即可——不再硬挡 rescue 手动路径
545
- result.warnings = (result.warnings || []).concat([
546
- `主工作区有 ${dirtyFiles.length} 个与本次 apply 无关的未提交文件,已放行(只校验重叠文件):` +
547
- `${dirtyFiles.slice(0, 5).join(', ')}${dirtyFiles.length > 5 ? ' 等' : ''}` +
548
- `——若 apply --3way 因 CRLF/autocrlf 报 does not match index,可 git stash 后重试`
549
- ]);
795
+ }
550
796
  }
551
797
  }
552
- }
553
-
554
- // --- 5. 校验:主工作区文件 base hash 一致 ---
555
- // 5a. 检查主工作区是否有未 commit 的脏文件(会影响 apply)
556
- const mainDirtyRaw = gitQuiet(projectRoot, ['diff', '--name-only', 'HEAD']);
557
- const mainDirtyFiles = mainDirtyRaw ? mainDirtyRaw.split('\n').filter(Boolean) : [];
558
- if (mainDirtyFiles.length > 0) {
559
- // 如果脏文件和本次 apply 的文件有交集 → 报错
560
- const conflictDirty = mainDirtyFiles.filter(f => changedFiles.includes(f));
561
- if (conflictDirty.length > 0) {
562
- const rescueDirty5a = computeRescueDirtyFiles(projectRoot);
563
- result.rescueCommands = generateRescueCommands({
564
- changedFiles, dirtyFiles: rescueDirty5a, hashMismatchFiles: result.hashMismatchFiles,
565
- deletedFiles: result.deletedFiles, worktreePath, projectRoot,
566
- });
567
- result.errors.push(
568
- `主工作区有以下未 commit 的变更,会影响 apply:\n ${conflictDirty.join('\n ')}\n请先 commit 或 stash 这些变更。` +
569
- (result.rescueCommands.commands.length > 0 || result.rescueCommands.warnings.length > 0
570
- ? `或手动 rescue(旁路 git apply,逐文件 cp 安全子集;cp 后需手动 sillyspec worktree cleanup ${changeName}):\n` +
571
- result.rescueCommands.commands.map(c => ` ${c}`).join('\n') +
572
- (result.rescueCommands.warnings.length > 0 ? '\n' + result.rescueCommands.warnings.map(w => ` ${w}`).join('\n') : '') +
573
- `\n (共 ${result.rescueCommands.cpFileCount} 个可安全 cp,${result.rescueCommands.excludedCount} 个被排除)\n`
574
- : '')
575
- );
576
- if (!checkOnly) return result; // checkOnly 收集不短路(一次报全);真实 apply 短路
577
- }
578
- }
579
798
 
580
- // 5b hashMismatch 计算已前移到 step3.5(Grill P0),见上
799
+ // 5b hashMismatch 计算已前移到 step3.5(Grill P0),见上
581
800
 
582
- // --- 6. checkOnly 模式:到此返回 ---
583
- if (checkOnly) {
584
- result.ok = true;
585
- return result;
586
- }
587
-
588
- // --- 7. 生成 patch 并 apply ---
589
- // 确定要包含在 patch 中的文件:有清单用「实际变更 ∩ 清单(pathMatches 容差)」,无清单用全部变更。
590
- // 口径与 classifyAllowListViolations 一致(坑 apply-glob-manifest-passes-check-but-not-patch)。
591
- const patchFiles = resolvePatchFiles(changedFiles, allowSet, hasAllowList);
801
+ // --- 6. checkOnly 模式:到此返回 ---
802
+ if (checkOnly) {
803
+ result.ok = true;
804
+ return result;
805
+ }
592
806
 
593
- // 创建临时文件
594
- const tmpDir = mkdtempSync(join(tmpdir(), 'sillyspec-patch-'));
595
- const patchPath = join(tmpDir, 'apply.patch');
596
- 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);
597
811
 
598
- try {
599
- // patch 以 Buffer 聚合:git diff --binary 对二进制/非 UTF-8 文件输出任意字节序列,
600
- // 按 utf8 string 拼接会破坏 NUL 字节成 U+FFFD → corrupt patch(git-helper.js git() 注释
601
- // 同款坑;worktree.js 的 diff 采集已是 encoding:'buffer' 正确写法)。
602
- const patchParts = [];
603
-
604
- // 分 tracked 变更和 untracked 新文件生成 patch
605
- // 批量化:一次 ls-tree(deliverableBase tree 中存在的文件)+ 一次 ls-files(index 中存在的文件)
606
- // 建集合,替代 per-file cat-file -e / ls-files --error-unmatch(原至多 2N spawn → 固定 2)。
607
- // 语义等价:cat-file -e deliverableBase:f 成功 ⟺ f 在 ls-tree deliverableBase 输出(getBlobHashMap key);
608
- // ls-files --error-unmatch f 成功 ⟺ f 在 ls-files -- 输出。
609
- // tracked 判定用 deliverableBase(集合判定侧)
610
- const inTree = getBlobHashMap(worktreePath, deliverableBase, patchFiles);
611
- const inIndexList = patchFiles.length > 0
612
- ? (gitQuiet(worktreePath, ['ls-files', '--', ...patchFiles]) || '').split('\n').filter(Boolean)
613
- : [];
614
- const inIndex = new Set(inIndexList);
615
- const trackedFiles = patchFiles.filter(f => inTree.has(f) || inIndex.has(f));
616
- const trackedSet = new Set(trackedFiles);
617
- const untrackedPatchFiles = patchFiles.filter(f => !trackedSet.has(f));
618
-
619
- // tracked 文件:git diff patchBase(patch 生成锚点,默认 merge-base)
620
- // 数组形式,文件名逐个展开为独立 argv,不经 shell;
621
- // encoding:'buffer' 保留二进制补丁原样,timeout 放大到 60s 防大 diff 超时——原裸 execSync 无 timeout
622
- if (trackedFiles.length > 0) {
623
- patchParts.push(git(
624
- worktreePath,
625
- ['diff', '--binary', patchBase, '--', ...trackedFiles],
626
- { encoding: 'buffer', timeout: 60000 }
627
- ));
628
- }
812
+ // 创建临时文件
813
+ const tmpDir = mkdtempSync(join(tmpdir(), 'sillyspec-patch-'));
814
+ const patchPath = join(tmpDir, 'apply.patch');
815
+ result.patchPath = patchPath;
629
816
 
630
- // untracked 新文件:git add 到 index,git diff --cached,然后 reset(均数组形式,文件名逐个展开)
631
- if (untrackedPatchFiles.length > 0) {
632
- git(worktreePath, ['add', '--', ...untrackedPatchFiles]);
633
- try {
634
- // 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) {
635
842
  patchParts.push(git(
636
843
  worktreePath,
637
- ['diff', '--binary', '--cached', '--', ...untrackedPatchFiles],
844
+ ['diff', '--binary', patchBase, '--', ...trackedFiles],
638
845
  { encoding: 'buffer', timeout: 60000 }
639
846
  ));
640
- } finally {
641
- // 重置 index(不保留 staged 状态)
642
- gitQuiet(worktreePath, ['reset', 'HEAD', '--', ...untrackedPatchFiles]);
643
847
  }
644
- }
645
848
 
646
- const patchContent = Buffer.concat(patchParts);
647
- if (patchContent.length === 0) {
648
- // patch 为空(清单中部分文件可能没实际变更)
649
- result.ok = true;
650
- rmSync(tmpDir, { recursive: true, force: true });
651
- return result;
652
- }
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
+ }
653
864
 
654
- 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
+ }
655
872
 
656
- // apply --check 预检失败不再拦截(--check 只测 clean apply,--3way 能处理 clean apply 失败的
657
- // 三路合并场景——主干已提交推进时 --check 恒失败但 --3way 可合)。故跳过 --check,直接试 --3way。
873
+ writeFileSync(patchPath, patchContent);
658
874
 
659
- // 回滚准备:记录 patch 涉及的 tracked 文件(--3way 冲突后需恢复 HEAD 版,不留半成品冲突标记)。
660
- // tracked 文件冲突 → git checkout -- <f> 还原;untracked 新建文件(--3way 不会对其冲突)不在回滚范围,
661
- // 但若 --3way 部分成功后冲突,已创建的新文件需删,故记录 untracked 集合。
662
- const trackedPatchFiles = patchFiles.filter(f => {
663
- // 该文件在主仓库 HEAD 存在 → 是 tracked(--3way 冲突时留标记需 checkout 还原)
664
- return gitQuiet(projectRoot, ['cat-file', '-e', `HEAD:${f}`]) === null ? false : true;
665
- });
666
- const newPatchFiles = patchFiles.filter(f => !trackedPatchFiles.includes(f));
875
+ // apply --check 预检失败不再拦截(--check 只测 clean apply,--3way 能处理 clean apply 失败的
876
+ // 三路合并场景——主干已提交推进时 --check 恒失败但 --3way 可合)。故跳过 --check,直接试 --3way。
667
877
 
668
- // apply --3way 正式应用(主干已提交推进时自动三路合并)
669
- try {
670
- git(projectRoot, ['apply', '--3way', patchPath], { timeout: 30000 });
671
- } catch (e) {
672
- // --3way 冲突(exit 1,工作区已留冲突标记):回滚到 apply 前干净状态,不留半成品
673
- // FR-06:解析 git 原始 stderr 提取冲突文件列表(不静默吞掉)
674
- const rawStderr = e.message || '';
675
- const rollback = rollbackApply(projectRoot, trackedPatchFiles, newPatchFiles, rawStderr);
676
- // autocrlf 副作用单独点名:主仓无关未提交 dirty + CRLF 转换可触发 does not match index
677
- // (非文件内容冲突,交集空时 step4.5 已放行到这里)——回滚无损,stash 后重试即可
678
- 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
+ }
679
906
  result.errors.push(
680
- `apply --3way 失败(does not match index):多为主仓未提交文件 + Windows autocrlf 的 CRLF 副作用触发,非文件内容冲突。\n` +
681
- `已回滚工作区到 apply 前状态(无损,无关未提交文件未受影响)。\n` +
682
- `处理: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
+ `或手动解决后重试。`
683
913
  );
684
914
  if (rollback.error) result.warnings = (result.warnings || []).concat([`回滚警告: ${rollback.error}`]);
685
915
  return result;
686
916
  }
687
- result.errors.push(
688
- `apply --3way 冲突:以下文件与主干「已提交」推进重叠,无法自动合并:\n` +
689
- ` ${rollback.conflicts.length > 0 ? rollback.conflicts.join('\n ') : '(未能获取冲突文件列表)'}\n` +
690
- `已回滚工作区到 apply 前状态(无半成品冲突标记)。\n` +
691
- `可选:用 --merge 自动三方合并兜底(git merge sillyspec/${changeName},会引入合并提交):\n` +
692
- ` sillyspec worktree apply ${changeName} --merge\n` +
693
- `或手动解决后重试。`
694
- );
695
- if (rollback.error) result.warnings = (result.warnings || []).concat([`回滚警告: ${rollback.error}`]);
696
- return result;
697
- }
698
917
 
699
- result.ok = true;
700
-
701
- // --- 7.5 提交复用 pathspec(坑 apply-commit-pathspec-sweep,2026-08-21 实证)---
702
- // apply 后主仓常混有无关未提交文件(他者会话/并行 quick),agent 习惯 `git add <目录>/`
703
- // 会把无关文件扫进暂存需手工剔除。落盘本变更精确 pathspec 供提交直接复用:
704
- // 文件 + result 字段(CLI 输出可照抄 git add -- … / 长清单用 --pathspec-from-file)。
705
- try {
706
- const commitFiles = [...new Set(patchFiles)].sort().filter(Boolean);
707
- result.commitPathspec = commitFiles;
708
- const runtimeRoot = join(projectRoot, '.sillyspec', '.runtime');
709
- mkdirSync(runtimeRoot, { recursive: true });
710
- const pathspecFile = join(runtimeRoot, `apply-pathspec-${changeName}.txt`);
711
- writeFileSync(pathspecFile, commitFiles.join('\n') + '\n');
712
- result.pathspecFile = pathspecFile;
713
- } catch { /* pathspec 落盘失败不影响 apply 结果 */ }
714
-
715
- // --- 8. 成功后自动 cleanup(失败不影响整体结果) ---
716
- try {
717
- wm.cleanup(changeName, { force: true });
718
- } catch (cleanupErr) {
719
- result.warnings = result.warnings || [];
720
- result.warnings.push(`cleanup 失败(不影响应用结果): ${cleanupErr.message}`);
721
- }
918
+ result.ok = true;
722
919
 
723
- } catch (e) {
724
- // ENOBUFS 自动降级(坑 apply-spawnsync-enobufs,2026-08-22 实证:大 diff 的 binary patch
725
- // 超 maxBuffer 抛 ENOBUFS,此前只能 agent 手动 git merge 绕行)——git apply 路径走不通时
726
- // 自动落 applyByMerge(既有 --merge 兜底,语义同为三方合并)
727
- if (/ENOBUFS/i.test(String(e.message || e.code || ''))) {
728
- result.warnings = (result.warnings || []).concat(
729
- [`patch 生成超出进程缓冲区(ENOBUFS,超大 diff)——自动降级 git merge 路径应用`]
730
- );
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)。
731
924
  try {
732
- return applyByMerge(result, changeName, projectRoot, wm);
733
- } catch (mergeErr) {
734
- result.errors.push(`ENOBUFS 降级 merge 也失败: ${mergeErr.message}`);
735
- return result;
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))) {
941
+ result.warnings.push(
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
+ }
960
+ } else {
961
+ consumeCleanup(wm.cleanup(changeName, { force: true }));
962
+ }
963
+ } catch (cleanupErr) {
964
+ result.warnings = result.warnings || [];
965
+ result.warnings.push(`cleanup 失败(不影响应用结果;Windows 手动清理先解 junction 再删,勿 rm -rf): ${cleanupErr.message}`);
736
966
  }
967
+
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
+ }
983
+ }
984
+ result.errors.push(`patch 生成/应用异常: ${e.message}`);
985
+ return result;
986
+ } finally {
987
+ // 清理临时目录
988
+ try { rmSync(tmpDir, { recursive: true, force: true }); } catch {}
737
989
  }
738
- result.errors.push(`patch 生成/应用异常: ${e.message}`);
990
+
739
991
  return result;
740
992
  } finally {
741
- // 清理临时目录
742
- try { rmSync(tmpDir, { recursive: true, force: true }); } catch {}
993
+ // stash 恢复(含 --merge 早退 / 各拦截 return / 异常路径——finally 全覆盖,绝不遗漏)
994
+ if (stashInfo) restoreMainStash(projectRoot, stashInfo);
743
995
  }
996
+ }
744
997
 
745
- 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
+ }
746
1049
  }
747
1050
 
748
1051
  /**
@@ -966,7 +1269,14 @@ function preAlignBaselineToMain({ meta, branch, projectRoot, result }) {
966
1269
  * @param {object} wm - WorktreeManager 实例
967
1270
  * @returns {object} result(merged=true 表示走了 merge 降级)
968
1271
  */
969
- function applyByMerge(result, changeName, projectRoot, wm) {
1272
+ // opts.keepConflicts(坑 merge-conflict-abort-no-chance,2026-08-23 实证:--merge 遇冲突直接
1273
+ // abort 回滚,用户想手工解决只能自己重新 git merge——冲突现场与解决上下文全部丢失):
1274
+ // true(显式 --merge 路径)→ 冲突时保留 merge-in-progress 现场 + 完整解决指引(编辑冲突 →
1275
+ // git add + git commit;或 git merge --abort 放弃)。worktree/分支/meta 本就保留。
1276
+ // false(ENOBUFS 自动降级路径,默认)→ 维持 abort——自动降级无人善后冲突状态,回滚到
1277
+ // 干净态让用户显式重来更安全。
1278
+ export function applyByMerge(result, changeName, projectRoot, wm, opts = {}) {
1279
+ const { keepConflicts = false } = opts;
970
1280
  const meta = wm.getMeta(changeName);
971
1281
  const changedFiles = result.changedFiles || [];
972
1282
  // 用 meta.branch(native-worktree 模式分支名可能不是 sillyspec/<change>),不硬编码。
@@ -978,12 +1288,36 @@ function applyByMerge(result, changeName, projectRoot, wm) {
978
1288
  try {
979
1289
  git(projectRoot, ['merge', '--no-ff', branch], { timeout: 30000 });
980
1290
  } catch (e) {
981
- // merge 冲突:取冲突文件列表 + abort 回滚(不 cleanup,保留 worktree)
1291
+ // merge 失败两形态须区分(原实现混为一谈:dirty 拒绝启动也被当「冲突」报):
1292
+ // ① 未启动:主仓有会被合并覆盖的未提交改动,git 直接拒绝(无 MERGE_HEAD)——没有现场
1293
+ // 可保留也无需 abort,指引 commit/stash 或 --skip-overlap
1294
+ // ② 真冲突:merge 已启动留 MERGE_HEAD + 冲突标记——keepConflicts 时保留现场供手工解决
982
1295
  let conflictFiles = [];
983
1296
  try {
984
1297
  const cf = gitQuiet(projectRoot, ['diff', '--name-only', '--diff-filter=U']);
985
1298
  conflictFiles = cf ? cf.split('\n').filter(Boolean) : [];
986
1299
  } catch {}
1300
+ const mergeInProgress = gitQuiet(projectRoot, ['rev-parse', '-q', '--verify', 'MERGE_HEAD']) !== null;
1301
+ if (!mergeInProgress) {
1302
+ result.errors.push(
1303
+ `git merge ${branch} 未执行成功——主仓有会被合并覆盖的未提交改动,git 拒绝启动合并(无冲突现场)。\n` +
1304
+ `git 输出: ${String(e.message || '').split('\n').slice(0, 3).join(' | ').slice(0, 300)}\n` +
1305
+ `请先 commit/stash 主仓改动后重试,或用 --skip-overlap 应用非重叠子集,或 sillyspec worktree apply ${changeName} --stash-dirty(自动 stash→apply→恢复,保暂存区状态,SHA 兜底)。`
1306
+ );
1307
+ return result;
1308
+ }
1309
+ if (keepConflicts) {
1310
+ // 保留冲突现场(显式 --merge):主仓处于 merge-in-progress(MERGE_HEAD + unmerged index +
1311
+ // 冲突标记),用户可直接手工解决——解决前 git 操作受限由指引明示,sillyspec 主仓命令
1312
+ // (apply/cleanup 等)也会被 dirty/merge 状态挡住,属预期。
1313
+ result.errors.push(
1314
+ `git merge ${branch} 冲突,已在主仓保留冲突现场(未 abort)。冲突文件:\n` +
1315
+ (conflictFiles.length ? ` ${conflictFiles.join('\n ')}\n` : ` (未能获取冲突文件列表——git diff --name-only --diff-filter=U 查看)\n`) +
1316
+ `手工解决:编辑上述冲突文件 → git add <file> → git commit 完成合并(worktree/分支已保留,解决后无需重跑 apply)。\n` +
1317
+ `放弃合并:git merge --abort 回到合并前状态后重试。注意:解决前主仓处于 merge 中状态,其他 sillyspec 主仓命令会被阻挡。`
1318
+ );
1319
+ return result;
1320
+ }
987
1321
  try { gitQuiet(projectRoot, ['merge', '--abort']); } catch {}
988
1322
  result.errors.push(
989
1323
  `git merge ${branch} 冲突,请手动解决。冲突文件:\n` +
@@ -1089,20 +1423,28 @@ export function assessApplyRisk(changeName, { cwd } = {}) {
1089
1423
  const incidentalSet = new Set(
1090
1424
  parseFileChangeListDetailed(designPath).filter(e => e.incidental).map(e => e.path)
1091
1425
  );
1426
+ // review.json 声明偏差文件(坑 apply-undeclared-deviation-block):与顺带修复同等待遇——
1427
+ // reviewer 声明(已过 git 证据校验)的执行期偏差豁免 allowed_paths 严格校验,降 warning 注明来源。
1428
+ const reviewDeclaredSet = new Set(collectReviewDeclaredFiles(projectRoot, changeName).get('main') || []);
1092
1429
 
1093
- // 检查 2: 变更在 allowed_paths 内(仅在 TaskCard 存在时);顺带修复文件豁免。
1430
+ // 检查 2: 变更在 allowed_paths 内(仅在 TaskCard 存在时);顺带修复/review 声明文件豁免。
1094
1431
  // 匹配换 pathMatches(与 Gate1/plan-postcheck 同语义容差),消除原字面前缀弱匹配漂移。
1095
1432
  if (allowedPaths.size > 0) {
1096
1433
  const isIncidental = f => [...incidentalSet].some(ap => pathMatches(f, ap));
1434
+ const isReviewDeclared = f => [...reviewDeclaredSet].some(ap => pathMatches(f, ap));
1097
1435
  const outsideAll = changedFiles.filter(f => ![...allowedPaths].some(allowed => pathMatches(f, allowed)));
1098
- const outsidePaths = outsideAll.filter(f => !isIncidental(f));
1436
+ const outsidePaths = outsideAll.filter(f => !isIncidental(f) && !isReviewDeclared(f));
1099
1437
  const exempted = outsideAll.filter(f => isIncidental(f));
1438
+ const reviewExempted = outsideAll.filter(f => !isIncidental(f) && isReviewDeclared(f));
1100
1439
  if (outsidePaths.length > 0) {
1101
1440
  reasons.push(`变更文件超出 allowed_paths:\n ${outsidePaths.join('\n ')}`);
1102
1441
  }
1103
1442
  if (exempted.length > 0) {
1104
1443
  warnings.push(`顺带修复文件(已豁免 allowed_paths,来源 design §6 标记):${exempted.join(', ')}`);
1105
1444
  }
1445
+ if (reviewExempted.length > 0) {
1446
+ warnings.push(`review 声明偏差文件(已豁免 allowed_paths,来源 task review.json changedFiles,过 git 证据校验):${reviewExempted.join(', ')}`);
1447
+ }
1106
1448
  }
1107
1449
 
1108
1450
  // 检查 4+5: 高风险文件模式