@pennixrv/trellis 0.7.2-beta.3 → 0.7.2-beta.31

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 (477) hide show
  1. package/README.md +14 -0
  2. package/dist/cli/index.js +4 -0
  3. package/dist/cli/index.js.map +1 -1
  4. package/dist/commands/ablate.d.ts.map +1 -1
  5. package/dist/commands/ablate.js +13 -0
  6. package/dist/commands/ablate.js.map +1 -1
  7. package/dist/commands/init.d.ts +2 -0
  8. package/dist/commands/init.d.ts.map +1 -1
  9. package/dist/commands/init.js +138 -120
  10. package/dist/commands/init.js.map +1 -1
  11. package/dist/commands/teamwork/adapters/acp.d.ts.map +1 -1
  12. package/dist/commands/teamwork/adapters/acp.js +3 -0
  13. package/dist/commands/teamwork/adapters/acp.js.map +1 -1
  14. package/dist/commands/teamwork/adapters/index.d.ts +1 -1
  15. package/dist/commands/teamwork/adapters/index.d.ts.map +1 -1
  16. package/dist/commands/teamwork/artifact.d.ts +2 -0
  17. package/dist/commands/teamwork/artifact.d.ts.map +1 -1
  18. package/dist/commands/teamwork/artifact.js +4 -2
  19. package/dist/commands/teamwork/artifact.js.map +1 -1
  20. package/dist/commands/teamwork/batch-reservation.d.ts.map +1 -1
  21. package/dist/commands/teamwork/batch-reservation.js +16 -8
  22. package/dist/commands/teamwork/batch-reservation.js.map +1 -1
  23. package/dist/commands/teamwork/batch.d.ts +15 -1
  24. package/dist/commands/teamwork/batch.d.ts.map +1 -1
  25. package/dist/commands/teamwork/batch.js +279 -24
  26. package/dist/commands/teamwork/batch.js.map +1 -1
  27. package/dist/commands/teamwork/coordinator.d.ts +3 -0
  28. package/dist/commands/teamwork/coordinator.d.ts.map +1 -1
  29. package/dist/commands/teamwork/coordinator.js +22 -3
  30. package/dist/commands/teamwork/coordinator.js.map +1 -1
  31. package/dist/commands/teamwork/create.d.ts +1 -0
  32. package/dist/commands/teamwork/create.d.ts.map +1 -1
  33. package/dist/commands/teamwork/create.js +4 -0
  34. package/dist/commands/teamwork/create.js.map +1 -1
  35. package/dist/commands/teamwork/evidence-references.d.ts +19 -0
  36. package/dist/commands/teamwork/evidence-references.d.ts.map +1 -0
  37. package/dist/commands/teamwork/evidence-references.js +249 -0
  38. package/dist/commands/teamwork/evidence-references.js.map +1 -0
  39. package/dist/commands/teamwork/foreground-wait.d.ts +4 -1
  40. package/dist/commands/teamwork/foreground-wait.d.ts.map +1 -1
  41. package/dist/commands/teamwork/foreground-wait.js +15 -1
  42. package/dist/commands/teamwork/foreground-wait.js.map +1 -1
  43. package/dist/commands/teamwork/index.d.ts.map +1 -1
  44. package/dist/commands/teamwork/index.js +47 -5
  45. package/dist/commands/teamwork/index.js.map +1 -1
  46. package/dist/commands/teamwork/list.d.ts +1 -0
  47. package/dist/commands/teamwork/list.d.ts.map +1 -1
  48. package/dist/commands/teamwork/list.js +4 -1
  49. package/dist/commands/teamwork/list.js.map +1 -1
  50. package/dist/commands/teamwork/prompt.js +1 -1
  51. package/dist/commands/teamwork/prompt.js.map +1 -1
  52. package/dist/commands/teamwork/rm.d.ts +27 -4
  53. package/dist/commands/teamwork/rm.d.ts.map +1 -1
  54. package/dist/commands/teamwork/rm.js +155 -51
  55. package/dist/commands/teamwork/rm.js.map +1 -1
  56. package/dist/commands/teamwork/run.d.ts.map +1 -1
  57. package/dist/commands/teamwork/run.js +10 -1
  58. package/dist/commands/teamwork/run.js.map +1 -1
  59. package/dist/commands/teamwork/runtime.d.ts +1 -1
  60. package/dist/commands/teamwork/runtime.d.ts.map +1 -1
  61. package/dist/commands/teamwork/runtime.js +14 -4
  62. package/dist/commands/teamwork/runtime.js.map +1 -1
  63. package/dist/commands/teamwork/spawn.d.ts.map +1 -1
  64. package/dist/commands/teamwork/spawn.js +4 -1
  65. package/dist/commands/teamwork/spawn.js.map +1 -1
  66. package/dist/commands/teamwork/supervisor/stdout.d.ts.map +1 -1
  67. package/dist/commands/teamwork/supervisor/stdout.js +7 -0
  68. package/dist/commands/teamwork/supervisor/stdout.js.map +1 -1
  69. package/dist/commands/teamwork/supervisor.d.ts +1 -1
  70. package/dist/commands/teamwork/supervisor.d.ts.map +1 -1
  71. package/dist/commands/teamwork/teammate-adapters.d.ts +3 -0
  72. package/dist/commands/teamwork/teammate-adapters.d.ts.map +1 -1
  73. package/dist/commands/teamwork/teammate-adapters.js +14 -5
  74. package/dist/commands/teamwork/teammate-adapters.js.map +1 -1
  75. package/dist/commands/teamwork/teammate-launch.d.ts +3 -1
  76. package/dist/commands/teamwork/teammate-launch.d.ts.map +1 -1
  77. package/dist/commands/teamwork/teammate-launch.js +7 -5
  78. package/dist/commands/teamwork/teammate-launch.js.map +1 -1
  79. package/dist/commands/teamwork/workers.d.ts +8 -0
  80. package/dist/commands/teamwork/workers.d.ts.map +1 -0
  81. package/dist/commands/teamwork/workers.js +67 -0
  82. package/dist/commands/teamwork/workers.js.map +1 -0
  83. package/dist/commands/update.d.ts.map +1 -1
  84. package/dist/commands/update.js +188 -59
  85. package/dist/commands/update.js.map +1 -1
  86. package/dist/commands/workflow.d.ts.map +1 -1
  87. package/dist/commands/workflow.js +5 -7
  88. package/dist/commands/workflow.js.map +1 -1
  89. package/dist/configurators/codebuddy.d.ts +1 -8
  90. package/dist/configurators/codebuddy.d.ts.map +1 -1
  91. package/dist/configurators/codebuddy.js +2 -12
  92. package/dist/configurators/codebuddy.js.map +1 -1
  93. package/dist/configurators/codex.d.ts +0 -36
  94. package/dist/configurators/codex.d.ts.map +1 -1
  95. package/dist/configurators/codex.js +13 -106
  96. package/dist/configurators/codex.js.map +1 -1
  97. package/dist/configurators/copilot.d.ts +1 -12
  98. package/dist/configurators/copilot.d.ts.map +1 -1
  99. package/dist/configurators/copilot.js +2 -20
  100. package/dist/configurators/copilot.js.map +1 -1
  101. package/dist/configurators/cursor.d.ts +1 -8
  102. package/dist/configurators/cursor.d.ts.map +1 -1
  103. package/dist/configurators/cursor.js +2 -12
  104. package/dist/configurators/cursor.js.map +1 -1
  105. package/dist/configurators/droid.d.ts +1 -8
  106. package/dist/configurators/droid.d.ts.map +1 -1
  107. package/dist/configurators/droid.js +2 -12
  108. package/dist/configurators/droid.js.map +1 -1
  109. package/dist/configurators/dsh.d.ts +1 -21
  110. package/dist/configurators/dsh.d.ts.map +1 -1
  111. package/dist/configurators/dsh.js +4 -37
  112. package/dist/configurators/dsh.js.map +1 -1
  113. package/dist/configurators/gemini.d.ts +1 -16
  114. package/dist/configurators/gemini.d.ts.map +1 -1
  115. package/dist/configurators/gemini.js +3 -21
  116. package/dist/configurators/gemini.js.map +1 -1
  117. package/dist/configurators/grok.d.ts +1 -12
  118. package/dist/configurators/grok.d.ts.map +1 -1
  119. package/dist/configurators/grok.js +2 -18
  120. package/dist/configurators/grok.js.map +1 -1
  121. package/dist/configurators/kimi.d.ts +1 -21
  122. package/dist/configurators/kimi.d.ts.map +1 -1
  123. package/dist/configurators/kimi.js +2 -38
  124. package/dist/configurators/kimi.js.map +1 -1
  125. package/dist/configurators/kiro.d.ts +1 -9
  126. package/dist/configurators/kiro.d.ts.map +1 -1
  127. package/dist/configurators/kiro.js +1 -9
  128. package/dist/configurators/kiro.js.map +1 -1
  129. package/dist/configurators/omp.d.ts.map +1 -1
  130. package/dist/configurators/omp.js +1 -5
  131. package/dist/configurators/omp.js.map +1 -1
  132. package/dist/configurators/pi.d.ts.map +1 -1
  133. package/dist/configurators/pi.js +2 -5
  134. package/dist/configurators/pi.js.map +1 -1
  135. package/dist/configurators/qoder.d.ts +1 -10
  136. package/dist/configurators/qoder.d.ts.map +1 -1
  137. package/dist/configurators/qoder.js +3 -15
  138. package/dist/configurators/qoder.js.map +1 -1
  139. package/dist/configurators/reasonix.d.ts +1 -12
  140. package/dist/configurators/reasonix.d.ts.map +1 -1
  141. package/dist/configurators/reasonix.js +3 -22
  142. package/dist/configurators/reasonix.js.map +1 -1
  143. package/dist/configurators/shared.d.ts +1 -24
  144. package/dist/configurators/shared.d.ts.map +1 -1
  145. package/dist/configurators/shared.js +5 -184
  146. package/dist/configurators/shared.js.map +1 -1
  147. package/dist/configurators/snow.d.ts +1 -20
  148. package/dist/configurators/snow.d.ts.map +1 -1
  149. package/dist/configurators/snow.js +2 -25
  150. package/dist/configurators/snow.js.map +1 -1
  151. package/dist/configurators/trae.d.ts +1 -14
  152. package/dist/configurators/trae.d.ts.map +1 -1
  153. package/dist/configurators/trae.js +3 -19
  154. package/dist/configurators/trae.js.map +1 -1
  155. package/dist/configurators/workflow.d.ts +5 -0
  156. package/dist/configurators/workflow.d.ts.map +1 -1
  157. package/dist/configurators/workflow.js +85 -57
  158. package/dist/configurators/workflow.js.map +1 -1
  159. package/dist/configurators/zcode.d.ts +1 -13
  160. package/dist/configurators/zcode.d.ts.map +1 -1
  161. package/dist/configurators/zcode.js +2 -18
  162. package/dist/configurators/zcode.js.map +1 -1
  163. package/dist/migrations/manifests/0.5.0-beta.5.json +1 -212
  164. package/dist/migrations/manifests/0.7.2-beta.10.json +9 -0
  165. package/dist/migrations/manifests/0.7.2-beta.11.json +9 -0
  166. package/dist/migrations/manifests/0.7.2-beta.12.json +9 -0
  167. package/dist/migrations/manifests/0.7.2-beta.13.json +9 -0
  168. package/dist/migrations/manifests/0.7.2-beta.14.json +9 -0
  169. package/dist/migrations/manifests/0.7.2-beta.15.json +9 -0
  170. package/dist/migrations/manifests/0.7.2-beta.16.json +9 -0
  171. package/dist/migrations/manifests/0.7.2-beta.17.json +9 -0
  172. package/dist/migrations/manifests/0.7.2-beta.18.json +9 -0
  173. package/dist/migrations/manifests/0.7.2-beta.19.json +11 -0
  174. package/dist/migrations/manifests/0.7.2-beta.20.json +9 -0
  175. package/dist/migrations/manifests/0.7.2-beta.21.json +9 -0
  176. package/dist/migrations/manifests/0.7.2-beta.22.json +9 -0
  177. package/dist/migrations/manifests/0.7.2-beta.23.json +9 -0
  178. package/dist/migrations/manifests/0.7.2-beta.24.json +8 -0
  179. package/dist/migrations/manifests/0.7.2-beta.25.json +8 -0
  180. package/dist/migrations/manifests/0.7.2-beta.26.json +8 -0
  181. package/dist/migrations/manifests/0.7.2-beta.27.json +8 -0
  182. package/dist/migrations/manifests/0.7.2-beta.28.json +8 -0
  183. package/dist/migrations/manifests/0.7.2-beta.29.json +8 -0
  184. package/dist/migrations/manifests/0.7.2-beta.30.json +10 -0
  185. package/dist/migrations/manifests/0.7.2-beta.31.json +9 -0
  186. package/dist/migrations/manifests/0.7.2-beta.4.json +9 -0
  187. package/dist/migrations/manifests/0.7.2-beta.5.json +9 -0
  188. package/dist/migrations/manifests/0.7.2-beta.6.json +9 -0
  189. package/dist/migrations/manifests/0.7.2-beta.7.json +9 -0
  190. package/dist/migrations/manifests/0.7.2-beta.8.json +9 -0
  191. package/dist/migrations/manifests/0.7.2-beta.9.json +9 -0
  192. package/dist/migrations/retired-native-paths.d.ts +109 -0
  193. package/dist/migrations/retired-native-paths.d.ts.map +1 -0
  194. package/dist/migrations/retired-native-paths.js +263 -0
  195. package/dist/migrations/retired-native-paths.js.map +1 -0
  196. package/dist/templates/claude/index.d.ts +1 -16
  197. package/dist/templates/claude/index.d.ts.map +1 -1
  198. package/dist/templates/claude/index.js +5 -32
  199. package/dist/templates/claude/index.js.map +1 -1
  200. package/dist/templates/claude/settings.json +0 -22
  201. package/dist/templates/codebuddy/index.d.ts +2 -3
  202. package/dist/templates/codebuddy/index.d.ts.map +1 -1
  203. package/dist/templates/codebuddy/index.js +2 -3
  204. package/dist/templates/codebuddy/index.js.map +1 -1
  205. package/dist/templates/codebuddy/settings.json +0 -10
  206. package/dist/templates/codex/config.toml +4 -19
  207. package/dist/templates/codex/hooks/session-start.py +25 -30
  208. package/dist/templates/codex/hooks/turn-guard.py +74 -0
  209. package/dist/templates/codex/hooks.json +57 -6
  210. package/dist/templates/codex/index.d.ts +0 -5
  211. package/dist/templates/codex/index.d.ts.map +1 -1
  212. package/dist/templates/codex/index.js +0 -13
  213. package/dist/templates/codex/index.js.map +1 -1
  214. package/dist/templates/common/bundled-skills/trellis-decision-space-construction-and-merging/SKILL.md +2 -0
  215. package/dist/templates/common/bundled-skills/trellis-decision-space-construction-and-merging/workflow.md +13 -3
  216. package/dist/templates/common/bundled-skills/trellis-delivery-review-and-closeout/SKILL.md +2 -0
  217. package/dist/templates/common/bundled-skills/trellis-delivery-review-and-closeout/workflow.md +17 -9
  218. package/dist/templates/common/bundled-skills/trellis-goal-exploration-and-requirements/SKILL.md +2 -0
  219. package/dist/templates/common/bundled-skills/trellis-goal-exploration-and-requirements/workflow.md +7 -3
  220. package/dist/templates/common/bundled-skills/trellis-meta/SKILL.md +7 -7
  221. package/dist/templates/common/bundled-skills/trellis-meta/references/customize-local/change-agents.md +9 -51
  222. package/dist/templates/common/bundled-skills/trellis-meta/references/customize-local/change-context-loading.md +3 -15
  223. package/dist/templates/common/bundled-skills/trellis-meta/references/customize-local/change-hooks.md +1 -2
  224. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/bundled-skills.md +1 -1
  225. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/context-injection.md +4 -9
  226. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/generated-files.md +2 -2
  227. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/multi-agent-teamwork.md +6 -0
  228. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/overview.md +1 -1
  229. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/spec-system.md +10 -8
  230. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/agents.md +9 -79
  231. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/hooks-and-settings.md +2 -4
  232. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/overview.md +3 -6
  233. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/platform-map.md +24 -103
  234. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/skills-and-commands.md +1 -1
  235. package/dist/templates/common/bundled-skills/trellis-session-insight/SKILL.md +1 -1
  236. package/dist/templates/common/bundled-skills/trellis-solution-design-and-convergence/SKILL.md +2 -0
  237. package/dist/templates/common/bundled-skills/trellis-solution-design-and-convergence/workflow.md +27 -6
  238. package/dist/templates/common/bundled-skills/trellis-spec-bootstrap/SKILL.md +9 -7
  239. package/dist/templates/common/bundled-skills/trellis-spec-bootstrap/references/mcp-setup.md +12 -84
  240. package/dist/templates/common/bundled-skills/trellis-spec-bootstrap/references/repository-analysis.md +5 -25
  241. package/dist/templates/common/bundled-skills/trellis-spec-bootstrap/references/spec-task-planning.md +5 -9
  242. package/dist/templates/common/bundled-skills/trellis-spec-bootstrap/references/spec-writing.md +8 -0
  243. package/dist/templates/common/bundled-skills/trellis-task-implementation/SKILL.md +2 -0
  244. package/dist/templates/common/bundled-skills/trellis-task-implementation/workflow.md +7 -3
  245. package/dist/templates/common/bundled-skills/trellis-teamwork/SKILL.md +8 -1
  246. package/dist/templates/common/bundled-skills/trellis-teamwork/references/teammate-processes.md +21 -1
  247. package/dist/templates/common/bundled-skills/trellis-teamwork/references/teamwork-plan-construction.md +13 -2
  248. package/dist/templates/common/bundled-skills/trellis-worktree-delegation/SKILL.md +14 -0
  249. package/dist/templates/common/bundled-skills/trellis-worktree-delegation/workflow.md +86 -0
  250. package/dist/templates/common/commands/continue.md +16 -1
  251. package/dist/templates/common/commands/start.md +2 -0
  252. package/dist/templates/common/skills/before-dev.md +3 -1
  253. package/dist/templates/common/skills/check.md +3 -1
  254. package/dist/templates/common/skills/request-intake.md +14 -1
  255. package/dist/templates/copilot/hooks/session-start.py +11 -30
  256. package/dist/templates/cursor/hooks.json +0 -7
  257. package/dist/templates/cursor/index.d.ts +1 -11
  258. package/dist/templates/cursor/index.d.ts.map +1 -1
  259. package/dist/templates/cursor/index.js +2 -10
  260. package/dist/templates/cursor/index.js.map +1 -1
  261. package/dist/templates/droid/index.d.ts +2 -3
  262. package/dist/templates/droid/index.d.ts.map +1 -1
  263. package/dist/templates/droid/index.js +2 -3
  264. package/dist/templates/droid/index.js.map +1 -1
  265. package/dist/templates/droid/settings.json +0 -10
  266. package/dist/templates/dsh/DSH.md +2 -33
  267. package/dist/templates/dsh/index.d.ts +1 -19
  268. package/dist/templates/dsh/index.d.ts.map +1 -1
  269. package/dist/templates/dsh/index.js +2 -21
  270. package/dist/templates/dsh/index.js.map +1 -1
  271. package/dist/templates/gemini/index.d.ts +1 -11
  272. package/dist/templates/gemini/index.d.ts.map +1 -1
  273. package/dist/templates/gemini/index.js +2 -10
  274. package/dist/templates/gemini/index.js.map +1 -1
  275. package/dist/templates/kiro/index.d.ts +1 -13
  276. package/dist/templates/kiro/index.d.ts.map +1 -1
  277. package/dist/templates/kiro/index.js +1 -13
  278. package/dist/templates/kiro/index.js.map +1 -1
  279. package/dist/templates/markdown/agents.md +9 -14
  280. package/dist/templates/markdown/index.d.ts +1 -0
  281. package/dist/templates/markdown/index.d.ts.map +1 -1
  282. package/dist/templates/markdown/index.js +1 -0
  283. package/dist/templates/markdown/index.js.map +1 -1
  284. package/dist/templates/markdown/spec/index.md.txt +20 -0
  285. package/dist/templates/omp/extensions/trellis/index.ts.txt +27 -60
  286. package/dist/templates/omp/index.d.ts +0 -2
  287. package/dist/templates/omp/index.d.ts.map +1 -1
  288. package/dist/templates/omp/index.js +1 -4
  289. package/dist/templates/omp/index.js.map +1 -1
  290. package/dist/templates/opencode/lib/session-utils.js +17 -5
  291. package/dist/templates/opencode/lib/trellis-context.js +12 -321
  292. package/dist/templates/opencode/plugins/inject-shell-session-context.js +93 -0
  293. package/dist/templates/opencode/plugins/inject-workflow-state.js +19 -17
  294. package/dist/templates/opencode/plugins/session-start.js +2 -6
  295. package/dist/templates/pi/extensions/trellis/index.ts.txt +17 -1436
  296. package/dist/templates/pi/index.d.ts +1 -2
  297. package/dist/templates/pi/index.d.ts.map +1 -1
  298. package/dist/templates/pi/index.js +2 -5
  299. package/dist/templates/pi/index.js.map +1 -1
  300. package/dist/templates/qoder/index.d.ts +2 -3
  301. package/dist/templates/qoder/index.d.ts.map +1 -1
  302. package/dist/templates/qoder/index.js +2 -3
  303. package/dist/templates/qoder/index.js.map +1 -1
  304. package/dist/templates/shared-hooks/guard-teamwork-wait.py +118 -12
  305. package/dist/templates/shared-hooks/index.d.ts +2 -56
  306. package/dist/templates/shared-hooks/index.d.ts.map +1 -1
  307. package/dist/templates/shared-hooks/index.js +4 -70
  308. package/dist/templates/shared-hooks/index.js.map +1 -1
  309. package/dist/templates/shared-hooks/inject-shell-session-context.py +46 -1
  310. package/dist/templates/shared-hooks/inject-spec-context.py +6 -35
  311. package/dist/templates/shared-hooks/inject-workflow-state.py +66 -104
  312. package/dist/templates/shared-hooks/session-start.py +8 -6
  313. package/dist/templates/snow/SNOW.md +6 -18
  314. package/dist/templates/snow/hooks/write-trellis-context.py +51 -133
  315. package/dist/templates/snow/index.d.ts +2 -21
  316. package/dist/templates/snow/index.d.ts.map +1 -1
  317. package/dist/templates/snow/index.js +3 -24
  318. package/dist/templates/snow/index.js.map +1 -1
  319. package/dist/templates/template-utils.d.ts +1 -2
  320. package/dist/templates/template-utils.d.ts.map +1 -1
  321. package/dist/templates/template-utils.js +1 -11
  322. package/dist/templates/template-utils.js.map +1 -1
  323. package/dist/templates/trae/index.d.ts +2 -3
  324. package/dist/templates/trae/index.d.ts.map +1 -1
  325. package/dist/templates/trae/index.js +2 -3
  326. package/dist/templates/trae/index.js.map +1 -1
  327. package/dist/templates/trellis/agents/delegated-worktree-primary-agent.md +22 -22
  328. package/dist/templates/trellis/agents/teammate.md +6 -2
  329. package/dist/templates/trellis/agents/worktree-delegation-node.md +32 -0
  330. package/dist/templates/trellis/config.yaml +7 -36
  331. package/dist/templates/trellis/gitignore.txt +4 -0
  332. package/dist/templates/trellis/index.d.ts +1 -0
  333. package/dist/templates/trellis/index.d.ts.map +1 -1
  334. package/dist/templates/trellis/index.js +9 -0
  335. package/dist/templates/trellis/index.js.map +1 -1
  336. package/dist/templates/trellis/scripts/common/active_task.py +23 -31
  337. package/dist/templates/trellis/scripts/common/config.py +16 -36
  338. package/dist/templates/trellis/scripts/common/git_context.py +13 -4
  339. package/dist/templates/trellis/scripts/common/io.py +2 -2
  340. package/dist/templates/trellis/scripts/common/markdown_format.py +107 -0
  341. package/dist/templates/trellis/scripts/common/packages_context.py +29 -1
  342. package/dist/templates/trellis/scripts/common/session_context.py +25 -50
  343. package/dist/templates/trellis/scripts/common/task_context.py +5 -3
  344. package/dist/templates/trellis/scripts/common/task_continuity.py +66 -9
  345. package/dist/templates/trellis/scripts/common/task_move.py +11 -5
  346. package/dist/templates/trellis/scripts/common/task_runtime.py +211 -0
  347. package/dist/templates/trellis/scripts/common/task_store.py +12 -82
  348. package/dist/templates/trellis/scripts/common/task_turn.py +518 -0
  349. package/dist/templates/trellis/scripts/common/task_workflow.py +383 -395
  350. package/dist/templates/trellis/scripts/common/workflow_phase.py +3 -36
  351. package/dist/templates/trellis/scripts/common/workflow_selection.py +35 -40
  352. package/dist/templates/trellis/scripts/common/worktree_delegation.py +690 -0
  353. package/dist/templates/trellis/scripts/common/worktree_delegation_contract.py +446 -0
  354. package/dist/templates/trellis/scripts/common/worktree_delegation_messages.py +376 -0
  355. package/dist/templates/trellis/scripts/common/worktree_delegation_transport.py +57 -0
  356. package/dist/templates/trellis/scripts/markdown_format.py +40 -0
  357. package/dist/templates/trellis/scripts/task.py +73 -10
  358. package/dist/templates/trellis/workflow.md +52 -11
  359. package/dist/templates/zcode/config.json +0 -10
  360. package/dist/templates/zcode/index.d.ts +3 -22
  361. package/dist/templates/zcode/index.d.ts.map +1 -1
  362. package/dist/templates/zcode/index.js +3 -24
  363. package/dist/templates/zcode/index.js.map +1 -1
  364. package/dist/types/ai-tools.d.ts +0 -4
  365. package/dist/types/ai-tools.d.ts.map +1 -1
  366. package/dist/types/ai-tools.js +4 -109
  367. package/dist/types/ai-tools.js.map +1 -1
  368. package/dist/utils/ablation-store.d.ts.map +1 -1
  369. package/dist/utils/ablation-store.js +41 -1
  370. package/dist/utils/ablation-store.js.map +1 -1
  371. package/dist/utils/asset-backup.d.ts +1 -0
  372. package/dist/utils/asset-backup.d.ts.map +1 -1
  373. package/dist/utils/asset-backup.js +131 -31
  374. package/dist/utils/asset-backup.js.map +1 -1
  375. package/dist/utils/atomic-write.d.ts +1 -1
  376. package/dist/utils/atomic-write.d.ts.map +1 -1
  377. package/dist/utils/atomic-write.js +8 -2
  378. package/dist/utils/atomic-write.js.map +1 -1
  379. package/dist/utils/codex-config-ownership.d.ts +13 -0
  380. package/dist/utils/codex-config-ownership.d.ts.map +1 -0
  381. package/dist/utils/codex-config-ownership.js +64 -0
  382. package/dist/utils/codex-config-ownership.js.map +1 -0
  383. package/dist/utils/file-writer.d.ts +2 -0
  384. package/dist/utils/file-writer.d.ts.map +1 -1
  385. package/dist/utils/file-writer.js +1 -1
  386. package/dist/utils/file-writer.js.map +1 -1
  387. package/dist/utils/managed-markdown.d.ts +5 -0
  388. package/dist/utils/managed-markdown.d.ts.map +1 -0
  389. package/dist/utils/managed-markdown.js +64 -0
  390. package/dist/utils/managed-markdown.js.map +1 -0
  391. package/dist/utils/managed-removal.d.ts +2 -0
  392. package/dist/utils/managed-removal.d.ts.map +1 -1
  393. package/dist/utils/managed-removal.js +62 -8
  394. package/dist/utils/managed-removal.js.map +1 -1
  395. package/dist/utils/manifest-prune.d.ts.map +1 -1
  396. package/dist/utils/manifest-prune.js +5 -12
  397. package/dist/utils/manifest-prune.js.map +1 -1
  398. package/dist/utils/project-init.d.ts +26 -0
  399. package/dist/utils/project-init.d.ts.map +1 -0
  400. package/dist/utils/project-init.js +484 -0
  401. package/dist/utils/project-init.js.map +1 -0
  402. package/dist/utils/retired-native-assets.d.ts +17 -0
  403. package/dist/utils/retired-native-assets.d.ts.map +1 -0
  404. package/dist/utils/retired-native-assets.js +221 -0
  405. package/dist/utils/retired-native-assets.js.map +1 -0
  406. package/dist/utils/uninstall-scrubbers.d.ts.map +1 -1
  407. package/dist/utils/uninstall-scrubbers.js +6 -12
  408. package/dist/utils/uninstall-scrubbers.js.map +1 -1
  409. package/package.json +2 -2
  410. package/dist/templates/claude/agents/trellis-check.md +0 -115
  411. package/dist/templates/claude/agents/trellis-implement.md +0 -110
  412. package/dist/templates/claude/agents/trellis-research.md +0 -137
  413. package/dist/templates/codebuddy/agents/trellis-check.md +0 -115
  414. package/dist/templates/codebuddy/agents/trellis-implement.md +0 -110
  415. package/dist/templates/codebuddy/agents/trellis-research.md +0 -137
  416. package/dist/templates/codex/agents/trellis-check.toml +0 -56
  417. package/dist/templates/codex/agents/trellis-implement.toml +0 -37
  418. package/dist/templates/codex/agents/trellis-research.toml +0 -78
  419. package/dist/templates/cursor/agents/trellis-check.md +0 -114
  420. package/dist/templates/cursor/agents/trellis-implement.md +0 -109
  421. package/dist/templates/cursor/agents/trellis-research.md +0 -136
  422. package/dist/templates/droid/droids/trellis-check.md +0 -107
  423. package/dist/templates/droid/droids/trellis-implement.md +0 -102
  424. package/dist/templates/droid/droids/trellis-research.md +0 -137
  425. package/dist/templates/dsh/agents/trellis-check.md +0 -99
  426. package/dist/templates/dsh/agents/trellis-implement.md +0 -106
  427. package/dist/templates/dsh/agents/trellis-research.md +0 -134
  428. package/dist/templates/gemini/agents/trellis-check.md +0 -107
  429. package/dist/templates/gemini/agents/trellis-implement.md +0 -102
  430. package/dist/templates/gemini/agents/trellis-research.md +0 -136
  431. package/dist/templates/grok/agents/trellis-check.md +0 -105
  432. package/dist/templates/grok/agents/trellis-implement.md +0 -116
  433. package/dist/templates/grok/agents/trellis-research.md +0 -146
  434. package/dist/templates/grok/index.d.ts +0 -16
  435. package/dist/templates/grok/index.d.ts.map +0 -1
  436. package/dist/templates/grok/index.js +0 -19
  437. package/dist/templates/grok/index.js.map +0 -1
  438. package/dist/templates/kimi/agents/trellis-check.md +0 -103
  439. package/dist/templates/kimi/agents/trellis-implement.md +0 -115
  440. package/dist/templates/kimi/agents/trellis-research.md +0 -144
  441. package/dist/templates/kimi/index.d.ts +0 -20
  442. package/dist/templates/kimi/index.d.ts.map +0 -1
  443. package/dist/templates/kimi/index.js +0 -23
  444. package/dist/templates/kimi/index.js.map +0 -1
  445. package/dist/templates/kiro/agents/trellis-check.json +0 -26
  446. package/dist/templates/kiro/agents/trellis-implement.json +0 -26
  447. package/dist/templates/kiro/agents/trellis-research.json +0 -30
  448. package/dist/templates/omp/agents/trellis-check.md +0 -41
  449. package/dist/templates/omp/agents/trellis-implement.md +0 -45
  450. package/dist/templates/omp/agents/trellis-research.md +0 -30
  451. package/dist/templates/opencode/agents/trellis-check.md +0 -122
  452. package/dist/templates/opencode/agents/trellis-implement.md +0 -118
  453. package/dist/templates/opencode/agents/trellis-research.md +0 -145
  454. package/dist/templates/opencode/plugins/inject-subagent-context.js +0 -569
  455. package/dist/templates/pi/agents/trellis-check.md +0 -37
  456. package/dist/templates/pi/agents/trellis-implement.md +0 -42
  457. package/dist/templates/pi/agents/trellis-research.md +0 -25
  458. package/dist/templates/qoder/agents/trellis-check.md +0 -108
  459. package/dist/templates/qoder/agents/trellis-implement.md +0 -103
  460. package/dist/templates/qoder/agents/trellis-research.md +0 -137
  461. package/dist/templates/reasonix/agents/trellis-check.md +0 -36
  462. package/dist/templates/reasonix/agents/trellis-implement.md +0 -41
  463. package/dist/templates/reasonix/index.d.ts +0 -13
  464. package/dist/templates/reasonix/index.d.ts.map +0 -1
  465. package/dist/templates/reasonix/index.js +0 -16
  466. package/dist/templates/reasonix/index.js.map +0 -1
  467. package/dist/templates/shared-hooks/inject-subagent-context.py +0 -1217
  468. package/dist/templates/snow/agents/trellis-check.md +0 -135
  469. package/dist/templates/snow/agents/trellis-implement.md +0 -153
  470. package/dist/templates/snow/agents/trellis-research.md +0 -114
  471. package/dist/templates/snow/hooks/beforeSubAgentStart.json +0 -15
  472. package/dist/templates/trae/agents/trellis-check.md +0 -108
  473. package/dist/templates/trae/agents/trellis-implement.md +0 -103
  474. package/dist/templates/trae/agents/trellis-research.md +0 -137
  475. package/dist/templates/zcode/agents/trellis-check.md +0 -109
  476. package/dist/templates/zcode/agents/trellis-implement.md +0 -111
  477. package/dist/templates/zcode/agents/trellis-research.md +0 -133
@@ -8,15 +8,15 @@ import copy
8
8
  from datetime import datetime, timezone
9
9
  import hashlib
10
10
  import json
11
- import os
12
11
  import re
13
- import shutil
14
12
  import subprocess
15
13
  import sys
16
14
  from pathlib import Path
17
15
 
16
+ from .config import markdown_format_gate_enabled
18
17
  from .git import run_git
19
18
  from .io import read_json_checked, write_json
19
+ from .markdown_format import inspect_markdown
20
20
  from .paths import FILE_TASK_JSON, get_repo_root
21
21
  from .task_utils import is_within_tasks_dir, resolve_task_dir, run_task_hooks
22
22
 
@@ -80,6 +80,12 @@ def _state(meta: dict) -> dict:
80
80
  state = meta.get("task_workflow")
81
81
  if not isinstance(state, dict) or state.get("schema_version") != 1:
82
82
  raise TaskWorkflowError("TASK_PHASE_NOT_INITIALIZED", "task phase workflow is not initialized")
83
+ if "coverage_contract_version" in state and (
84
+ type(state["coverage_contract_version"]) is not int or state["coverage_contract_version"] != 1
85
+ ):
86
+ raise TaskWorkflowError("TASK_PHASE_TASK_INVALID", "unsupported coverage contract version")
87
+ if "complexity_reduction" in state and not _evidence_binding_shape(state["complexity_reduction"]):
88
+ raise TaskWorkflowError("TASK_PHASE_TASK_INVALID", "invalid complexity reduction evidence")
83
89
  if not isinstance(state.get("phases"), dict) or not isinstance(state.get("phase_ids"), list):
84
90
  raise TaskWorkflowError("TASK_PHASE_TASK_INVALID", "task phase workflow has an invalid shape")
85
91
  try:
@@ -126,6 +132,12 @@ def _state(meta: dict) -> dict:
126
132
  or not ROUTE_REVISION.fullmatch(str(skip.get("input_revision", "")))
127
133
  or not isinstance(skip.get("artifact_revision"), str)
128
134
  or not re.fullmatch(r"[a-f0-9]{64}", skip["artifact_revision"])
135
+ or ("basis" in skip and not _evidence_binding_shape(skip["basis"]))
136
+ or (("contract_ref" in skip or "contract_revision" in skip) and (
137
+ phase_id != PHASE_IDS[2] or skip.get("contract_ref") not in skip["evidence_refs"]
138
+ or not isinstance(skip.get("contract_revision"), str)
139
+ or not re.fullmatch(r"[a-f0-9]{64}", skip["contract_revision"])
140
+ ))
129
141
  or (
130
142
  phase_id in state["phases"]
131
143
  and skip["artifact_revision"] != state["phases"][phase_id].get("artifact_revision")
@@ -176,25 +188,18 @@ def implementation_start_ready(data: dict, task_dir: Path) -> bool:
176
188
  return False
177
189
  _require_current_requirements_confirmation(task_dir, state)
178
190
  _require_current_accepted_artifacts(task_dir, state)
179
- if PHASE_IDS[2] not in phase_ids:
180
- skip_records = state.get("skip_records")
181
- skipped_design = skip_records.get(PHASE_IDS[2]) if isinstance(skip_records, dict) else None
182
- evidence = skipped_design.get("evidence_refs") if isinstance(skipped_design, dict) else None
183
- return isinstance(evidence, list) and contract_ref in evidence
184
- design = state.get("phases", {}).get(PHASE_IDS[2])
185
- if not (
186
- isinstance(design, dict)
187
- and design.get("status") == "accepted"
188
- and design.get("outcome_kind") == "implementation_contract"
189
- and design.get("result_ref") == contract_ref
190
- ):
191
- return False
192
- artifact_refs = design.get("artifact_refs")
193
- if not isinstance(artifact_refs, list) or any(not isinstance(ref, str) for ref in artifact_refs):
194
- return False
195
- if _artifact_digest(task_dir, artifact_refs) != design.get("artifact_revision"):
196
- raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "Solution Design and Convergence Phase implementation contract changed after acceptance; refresh and accept the current artifact before implementation")
197
- return True
191
+ _require_current_omissions(task_dir, state)
192
+ return _matches_contract(state, contract_ref)
193
+
194
+
195
+ def _matches_contract(state: dict, contract_ref: str) -> bool:
196
+ design = state["phases"].get(PHASE_IDS[2])
197
+ if isinstance(design, dict) and design["status"] == "accepted":
198
+ return design.get("outcome_kind") == "implementation_contract" and design.get("result_ref") == contract_ref
199
+ if design is None or design.get("status") == "skipped":
200
+ record = state["skip_records"].get(PHASE_IDS[2], {})
201
+ return record.get("contract_ref", contract_ref) == contract_ref and contract_ref in record.get("evidence_refs", [])
202
+ return False
198
203
 
199
204
 
200
205
  def _save(task_file: Path, data: dict) -> None:
@@ -207,31 +212,10 @@ def _save(task_file: Path, data: dict) -> None:
207
212
 
208
213
  @contextlib.contextmanager
209
214
  def _task_lock(task_dir: Path):
210
- lock_file = get_repo_root() / ".trellis/.runtime/task-phase" / f"{task_dir.name}.lock"
211
- lock_file.parent.mkdir(parents=True, exist_ok=True)
212
- with lock_file.open("a+b") as handle:
213
- if os.name == "nt":
214
- import msvcrt
215
-
216
- handle.seek(0)
217
- if handle.read(1) == b"":
218
- handle.write(b"\0")
219
- handle.flush()
220
- handle.seek(0)
221
- msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
222
- try:
223
- yield
224
- finally:
225
- handle.seek(0)
226
- msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
227
- else:
228
- import fcntl
215
+ from .task_move import layout_lock
229
216
 
230
- fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
231
- try:
232
- yield
233
- finally:
234
- fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
217
+ with layout_lock(get_repo_root()):
218
+ yield
235
219
 
236
220
 
237
221
  def _expected_route(state: dict, value: str | None) -> None:
@@ -347,7 +331,7 @@ def _invalidate_from(state: dict, first_phase: str, keep_first: bool = False) ->
347
331
  state["closeout_disposition"] = None
348
332
 
349
333
 
350
- def _artifact_digest(task_dir: Path, refs: list[str]) -> str:
334
+ def _artifact_digest(task_dir: Path, refs: list[str], *, format_errors: list[str] | None = None) -> str:
351
335
  if not refs:
352
336
  return EMPTY_ARTIFACT_REVISION
353
337
  digest = hashlib.sha256()
@@ -364,6 +348,13 @@ def _artifact_digest(task_dir: Path, refs: list[str]) -> str:
364
348
  content = resolved.read_bytes()
365
349
  except (OSError, ValueError) as error:
366
350
  raise TaskWorkflowError("TASK_PHASE_ARTIFACT_INVALID", f"cannot read task artifact {value}: {error}") from error
351
+ if format_errors is not None and candidate.suffix.lower() in {".md", ".markdown"}:
352
+ try:
353
+ text = content.decode("utf-8")
354
+ except UnicodeError as error:
355
+ format_errors.append(f"{value}: cannot decode Markdown as UTF-8: {error}")
356
+ else:
357
+ format_errors.extend(issue.diagnostic(value, text) for issue in inspect_markdown(text))
367
358
  digest.update(value.encode("utf-8"))
368
359
  digest.update(b"\0")
369
360
  digest.update(content)
@@ -371,6 +362,20 @@ def _artifact_digest(task_dir: Path, refs: list[str]) -> str:
371
362
  return digest.hexdigest()
372
363
 
373
364
 
365
+ def _check_candidate(task_dir: Path, refs: list[str], *expected_revisions: str | None) -> str:
366
+ try:
367
+ enabled = markdown_format_gate_enabled(get_repo_root(task_dir))
368
+ except (OSError, ValueError) as error:
369
+ raise TaskWorkflowError("TASK_PHASE_MARKDOWN_CONFIG", str(error)) from error
370
+ errors: list[str] = []
371
+ revision = _artifact_digest(task_dir, refs, format_errors=errors if enabled else None)
372
+ if any(expected is not None and expected != revision for expected in expected_revisions):
373
+ raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "artifact revision changed; rebind the current phase candidate with phase artifact")
374
+ if errors:
375
+ raise TaskWorkflowError("TASK_PHASE_MARKDOWN_FORMAT", "\n".join(errors))
376
+ return revision
377
+
378
+
374
379
  def _require_current_accepted_artifacts(task_dir: Path, state: dict) -> None:
375
380
  for phase_id in state["phase_ids"]:
376
381
  record = state["phases"][phase_id]
@@ -454,6 +459,7 @@ def _init(args: argparse.Namespace, task_dir: Path, data: dict, meta: dict) -> i
454
459
  input_revision = "1"
455
460
  meta["task_workflow"] = {
456
461
  "schema_version": 1,
462
+ "coverage_contract_version": 1,
457
463
  "task_route_revision": "1",
458
464
  "task_kind": args.task_kind,
459
465
  "complexity": args.complexity,
@@ -487,29 +493,138 @@ def _show(state: dict) -> int:
487
493
  return 0
488
494
 
489
495
 
490
- def _require_acceptance_coverage(task_dir: Path, contract_ref: str) -> None:
491
- _artifact_digest(task_dir, [contract_ref])
492
- lines = (task_dir / contract_ref).read_text(encoding="utf-8").splitlines()
493
- heading = next((index for index, line in enumerate(lines) if line.strip() == "## 验收覆盖"), None)
494
- headers = ["接受条件", "工作包", "Owner", "验证入口", "交付证据", "停止条件"]
495
- if heading is not None:
496
- section = []
497
- for line in lines[heading + 1:]:
498
- if line.startswith("#"):
499
- break
500
- if line.strip():
501
- section.append(line.strip())
502
- rows = [line.strip("|").split("|") for line in section if line.startswith("|") and line.endswith("|")]
503
- rows = [[cell.strip() for cell in row] for row in rows]
504
- if (
505
- len(rows) >= 3
506
- and rows[0] == headers
496
+ def _read_phase_text(task_dir: Path, ref: str) -> str:
497
+ _artifact_digest(task_dir, [ref])
498
+ try:
499
+ return (task_dir / ref).read_text(encoding="utf-8")
500
+ except (OSError, UnicodeError) as error:
501
+ raise TaskWorkflowError("TASK_PHASE_ARTIFACT_INVALID", f"cannot read {ref}: {error}") from error
502
+
503
+
504
+ def _table(text: str, heading: str, headers: list[str]) -> list[list[str]]:
505
+ headings = re.split(r"(?m)^#{1,2}[ \t]+", text)
506
+ sections = [section.splitlines()[1:] for section in headings[1:] if section.splitlines()[0].strip() == heading]
507
+ rows = [[cell.strip() for cell in line.strip()[1:-1].split("|")]
508
+ for section in sections for line in section if line.strip().startswith("|") and line.strip().endswith("|")]
509
+ if (len(sections) == 1 and len(rows) >= 3 and rows[0] == headers
507
510
  and len(rows[1]) == len(headers)
508
511
  and all(re.fullmatch(r":?-{3,}:?", cell) for cell in rows[1])
509
- and all(len(row) == len(headers) and all(row) for row in rows[2:])
510
- ):
511
- return
512
- raise TaskWorkflowError("TASK_PHASE_COVERAGE_REQUIRED", "implementation contract requires ## 验收覆盖 with nonempty rows: " + " | ".join(headers))
512
+ and all(len(row) == len(headers) and all(row) for row in rows[2:])):
513
+ return rows[2:]
514
+ raise TaskWorkflowError("TASK_PHASE_COVERAGE_REQUIRED", f"## {heading} requires nonempty rows: " + " | ".join(headers))
515
+
516
+
517
+ def _require_acceptance_coverage(task_dir: Path, contract_ref: str) -> list[list[str]]:
518
+ return _table(_read_phase_text(task_dir, contract_ref), "验收覆盖",
519
+ ["接受条件", "工作包", "Owner", "验证入口", "交付证据", "停止条件"])
520
+
521
+
522
+ _ACCEPTANCE_ID = re.compile(r"^\**([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*[0-9])(?:\**(?=[::\s]|$)|(?=[::]))")
523
+ _CHECKLIST_ITEM = re.compile(r"^\s*[-*+]\s+\[[ xX]\]\s+(.+)$")
524
+ _OPTIONAL_PHASES = PHASE_IDS[1:3]
525
+
526
+
527
+ def _evidence_binding_shape(value: object) -> bool:
528
+ return (isinstance(value, dict) and isinstance(value.get("refs"), list)
529
+ and bool(value["refs"]) and all(isinstance(ref, str) and ref for ref in value["refs"])
530
+ and all(isinstance(value.get(key), str) and re.fullmatch(r"[a-f0-9]{64}", value[key])
531
+ for key in ("digest", "requirements")))
532
+
533
+
534
+ def _coverage_enabled(state: dict) -> bool:
535
+ return state.get("coverage_contract_version") == 1 and state["complexity"] == "complex"
536
+
537
+
538
+ def _requirements_ids(task_dir: Path, ref: str) -> set[str]:
539
+ text = _read_phase_text(task_dir, ref)
540
+ match = re.search(r"(?m)^##\s+(?:Acceptance Criteria|验收条件|验收标准)\s*$", text)
541
+ lines = re.split(r"(?m)^##\s+", text[match.end():], maxsplit=1)[0].splitlines() if match else []
542
+ items = [item[1] for ln in lines if (item := _CHECKLIST_ITEM.match(ln))]
543
+ ids = [found[1] for item in items if (found := _ACCEPTANCE_ID.match(item))]
544
+ if not ids or len(ids) != len(items) or len(set(ids)) != len(ids):
545
+ raise TaskWorkflowError("TASK_PHASE_COVERAGE_IDS_REQUIRED", "number every acceptance criterion once (for example A1, A2) in the confirmed requirements")
546
+ return set(ids)
547
+
548
+
549
+ def _check_coverage(task_dir: Path, state: dict, phase: str, outcome: str, ref: str) -> None:
550
+ if phase == PHASE_IDS[2] and outcome == "implementation_contract":
551
+ rows = _require_acceptance_coverage(task_dir, ref)
552
+ elif not _coverage_enabled(state):
553
+ return
554
+ elif phase == PHASE_IDS[1]:
555
+ rows = _table(_read_phase_text(task_dir, ref), "决策覆盖", ["接受条件", "处置", "证据"])
556
+ else:
557
+ rows = _table(_read_phase_text(task_dir, ref), "验收覆盖", ["接受条件", "结论", "证据"])
558
+ if not _coverage_enabled(state):
559
+ return
560
+ requirement_ref = _required_text(state["phases"][PHASE_IDS[0]].get("result_ref"), "accepted requirements result")
561
+ expected = _requirements_ids(task_dir, requirement_ref)
562
+ actual = [found[1] if (found := _ACCEPTANCE_ID.match(row[0])) else "" for row in rows]
563
+ if len(actual) != len(set(actual)) or set(actual) != expected:
564
+ raise TaskWorkflowError("TASK_PHASE_COVERAGE_MISMATCH", f"coverage IDs: missing {sorted(expected - set(actual))}; unknown {sorted(set(actual) - expected)}; IDs must be unique")
565
+ if phase == PHASE_IDS[1] or outcome != "implementation_contract":
566
+ refs = {row[2] for row in rows}
567
+ _artifact_digest(task_dir, sorted(refs))
568
+ bound = {value for key, record in state["phases"].items() if key == phase or record["status"] == "accepted"
569
+ for value in record["artifact_refs"]}
570
+ if not refs <= bound:
571
+ raise TaskWorkflowError("TASK_PHASE_COVERAGE_EVIDENCE_REQUIRED", f"bind coverage evidence with phase artifact first: {sorted(refs - bound)}")
572
+
573
+
574
+ def _omission_basis(task_dir: Path, phase: str, refs: list[str], requirement: dict) -> dict:
575
+ paths = [ref for ref in refs if Path(ref).suffix.lower() == ".md"]
576
+ if not paths:
577
+ raise TaskWorkflowError("TASK_PHASE_OMISSION_EVIDENCE_REQUIRED", f"{phase} needs task-local Markdown evidence")
578
+ heading = "降级依据" if phase == "complexity_reduction" else "省略依据"
579
+ headers = ["适用对象", "不再适用的理由" if phase == "complexity_reduction" else "省略理由", "依据", "重入条件"]
580
+ supporting = set(paths)
581
+ found = False
582
+ for ref in paths:
583
+ text = _read_phase_text(task_dir, ref)
584
+ if not re.search(rf"(?m)^##[ \t]+{heading}[ \t]*$", text):
585
+ continue
586
+ for row in _table(text, heading, headers):
587
+ if row[0] == phase:
588
+ found = True
589
+ supporting.add(row[2])
590
+ if not found:
591
+ raise TaskWorkflowError("TASK_PHASE_OMISSION_EVIDENCE_REQUIRED", f"## {heading} needs a row for {phase}")
592
+ return {"refs": sorted(supporting), "digest": _artifact_digest(task_dir, sorted(supporting)),
593
+ "requirements": requirement["artifact_revision"]}
594
+
595
+
596
+ def _bind_omissions(task_dir: Path, state: dict) -> None:
597
+ if not _coverage_enabled(state):
598
+ return
599
+ requirement = state["phases"][PHASE_IDS[0]]
600
+ for phase in _OPTIONAL_PHASES:
601
+ skip = state["skip_records"].get(phase)
602
+ if skip is not None and "basis" not in skip:
603
+ skip["basis"] = _omission_basis(task_dir, phase, skip["evidence_refs"], requirement)
604
+
605
+
606
+ def _require_current_omissions(task_dir: Path, state: dict) -> None:
607
+ # Withdrawal retires implementation authority; its safe closeout is not an implementation omission.
608
+ if _is_withdrawal_route(state):
609
+ return
610
+ skipped = state.get("skip_records", {}).get(PHASE_IDS[2], {})
611
+ if "contract_ref" in skipped and _artifact_digest(task_dir, [skipped["contract_ref"]]) != skipped.get("contract_revision"):
612
+ raise TaskWorkflowError("TASK_PHASE_STALE_OMISSION", "the contract bound to design omission changed")
613
+ if not _coverage_enabled(state) and state.get("complexity_reduction") is None:
614
+ return
615
+ requirement = state["phases"][PHASE_IDS[0]]
616
+ current = state.get("current_phase_id")
617
+ check = {}
618
+ if _coverage_enabled(state):
619
+ check.update({phase: state["skip_records"][phase].get("basis") for phase in _OPTIONAL_PHASES
620
+ if phase in state["skip_records"] and (current is None or PHASE_IDS.index(phase) <= PHASE_IDS.index(current))})
621
+ if state.get("complexity_reduction") is not None:
622
+ check["complexity reduction"] = state["complexity_reduction"]
623
+ for phase, basis in check.items():
624
+ if (not isinstance(basis, dict) or not _evidence_binding_shape(basis)
625
+ or basis["requirements"] != requirement["artifact_revision"]
626
+ or basis.get("digest") != _artifact_digest(task_dir, basis["refs"])):
627
+ raise TaskWorkflowError("TASK_PHASE_STALE_OMISSION", f"review and rebind {phase} evidence via phase route before proceeding")
513
628
 
514
629
 
515
630
  def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -> int:
@@ -521,13 +636,23 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
521
636
  if data.get("status") in {"completed", "cancelled"}:
522
637
  raise TaskWorkflowError("TASK_PHASE_TASK_TERMINAL", f"task is already {data['status']}")
523
638
 
639
+ if action == "preflight":
640
+ return _preflight(args, task_dir, state)
641
+
524
642
  _expected_route(state, args.expected_route_revision)
525
643
  reviewed_delivery = (
526
644
  state.get("current_phase_id") is None
527
645
  and action in {"return", "route"}
528
646
  and state["phases"].get(PHASE_IDS[4], {}).get("status") == "accepted"
529
647
  )
530
- if reviewed_delivery:
648
+ skipped_delivery = (
649
+ state.get("current_phase_id") is None
650
+ and action == "return" and args.target_phase == PHASE_IDS[4]
651
+ and args.return_kind == "contract_change"
652
+ and state["phases"][PHASE_IDS[4]]["status"] == "skipped"
653
+ and state.get("closeout_disposition") is None
654
+ )
655
+ if reviewed_delivery or skipped_delivery:
531
656
  current, record = PHASE_IDS[4], state["phases"][PHASE_IDS[4]]
532
657
  else:
533
658
  current, record = _phase(state)
@@ -536,7 +661,7 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
536
661
  rerouting_to_requirements = action == "route" and args.target_phase == PHASE_IDS[0]
537
662
  if current != PHASE_IDS[0] and not returning_to_requirements and not rerouting_to_requirements:
538
663
  _require_current_requirements_confirmation(task_dir, state)
539
- if action not in {"show", "resume", "route", "authorize", "admission"} and record.get("status") != "active" and not reviewed_delivery and not accepted_design_return:
664
+ if action not in {"show", "resume", "route", "authorize", "admission"} and record.get("status") != "active" and not (reviewed_delivery or skipped_delivery or accepted_design_return):
540
665
  raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "only the active phase can be changed")
541
666
 
542
667
  if action == "artifact":
@@ -577,8 +702,15 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
577
702
  elif action == "skip":
578
703
  reason = _required_text(args.reason, "--reason")
579
704
  evidence = _refs(args.evidence_ref, "--evidence-ref", required=True)
580
- if current == PHASE_IDS[0]:
581
- raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "The Goal Exploration and Requirements Confirmation Phase must reach minimum alignment and acceptance and cannot be skipped")
705
+ if current not in PHASE_IDS[1:3]:
706
+ raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", f"Required phase cannot be skipped: {current}")
707
+ contract_fields = {}
708
+ if current == PHASE_IDS[2] and PHASE_IDS[3] in state["phase_ids"]:
709
+ contract_ref = _required_text(args.contract_ref, "--contract-ref")
710
+ if contract_ref not in evidence:
711
+ raise TaskWorkflowError("TASK_PHASE_CONTRACT_NOT_ACCEPTED", "include the implementation contract among the skip evidence")
712
+ _check_coverage(task_dir, state, PHASE_IDS[2], "implementation_contract", contract_ref)
713
+ contract_fields = {"contract_ref": contract_ref, "contract_revision": _artifact_digest(task_dir, [contract_ref])}
582
714
  record.update({"status": "skipped", "reason": reason, "evidence_refs": evidence})
583
715
  state["skip_records"][current] = {
584
716
  "reason": reason,
@@ -586,14 +718,17 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
586
718
  "task_route_revision": state["task_route_revision"],
587
719
  "input_revision": state["input_revision"],
588
720
  "artifact_revision": record["artifact_revision"],
721
+ **contract_fields,
589
722
  }
723
+ _bind_omissions(task_dir, state)
724
+ _require_current_omissions(task_dir, state)
590
725
  _advance(state, current)
591
726
  elif action == "accept":
592
727
  _require_current_accepted_artifacts(task_dir, state)
728
+ if current != PHASE_IDS[0]:
729
+ _require_current_omissions(task_dir, state)
593
730
  artifact_revision = _required_text(args.artifact_revision, "--artifact-revision")
594
- current_revision = _artifact_digest(task_dir, record["artifact_refs"])
595
- if artifact_revision != record["artifact_revision"] or current_revision != record["artifact_revision"]:
596
- raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "artifact revision changed; refresh the phase artifact before acceptance")
731
+ _check_candidate(task_dir, record["artifact_refs"], record["artifact_revision"], artifact_revision)
597
732
  evidence = _refs(args.evidence_ref, "--evidence-ref", required=True)
598
733
  result_ref = _required_text(args.result_ref, "--result-ref")
599
734
  outcome = _required_text(args.outcome_kind, "--outcome-kind")
@@ -602,15 +737,26 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
602
737
  raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "Goal Exploration and Requirements Confirmation Phase can advance only with phase_result=accepted")
603
738
  if current == PHASE_IDS[2] and outcome not in {"implementation_contract", "analysis_conclusion", "no_go"}:
604
739
  raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "Solution Design and Convergence Phase must remain active for pending_user_decision or deferred; accept implementation_contract, analysis_conclusion, or no_go")
740
+ if current == PHASE_IDS[2] and (outcome == "implementation_contract") != (PHASE_IDS[3] in state["phase_ids"]):
741
+ raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "design result conflicts with the route; align the route before accepting")
605
742
  if result_ref not in record["artifact_refs"]:
606
743
  raise TaskWorkflowError("TASK_PHASE_RESULT_NOT_BOUND", "--result-ref must be included in the current phase artifact refs")
607
- if current == PHASE_IDS[2] and outcome == "implementation_contract":
608
- _require_acceptance_coverage(task_dir, result_ref)
744
+ if current == PHASE_IDS[0] and _coverage_enabled(state):
745
+ _requirements_ids(task_dir, result_ref)
746
+ _bind_omissions(task_dir, state)
747
+ elif current in _OPTIONAL_PHASES:
748
+ _check_coverage(task_dir, state, current, outcome, result_ref)
609
749
  if current == PHASE_IDS[3]:
610
- authorization = state.get("implementation_authorization")
611
- if not isinstance(authorization, dict) or authorization.get("task_route_revision") != state["task_route_revision"]:
750
+ if not implementation_start_ready(data, task_dir):
612
751
  raise TaskWorkflowError("TASK_PHASE_IMPLEMENTATION_NOT_AUTHORIZED", "Task Implementation and Test Verification Phase requires a current implementation authorization")
752
+ if data.get("status") != "in_progress":
753
+ raise TaskWorkflowError("TASK_PHASE_IMPLEMENTATION_NOT_STARTED", "enter in_progress with task.py start before accepting implementation")
754
+ _assert_delegated_resources_closed(task_dir, data)
613
755
  if current == PHASE_IDS[4]:
756
+ _require_current_omissions(task_dir, state)
757
+ readiness = _required_implementation_error(data, state)
758
+ if readiness:
759
+ raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", readiness)
614
760
  if args.closeout_disposition not in {"delivery_ready", "no_go", "cancelled"}:
615
761
  raise TaskWorkflowError("TASK_PHASE_INVALID_INPUT", "Delivery Review and On-Site Closeout Phase requires --closeout-disposition delivery_ready, no_go, or cancelled")
616
762
  if outcome != args.closeout_disposition:
@@ -646,7 +792,7 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
646
792
  execution_rework = return_kind == "execution_rework"
647
793
  if target not in state["phase_ids"] or (
648
794
  state["phase_ids"].index(target) >= state["phase_ids"].index(current)
649
- and not ((reviewed_delivery or accepted_design_return or execution_rework) and target == current)
795
+ and not ((reviewed_delivery or skipped_delivery or accepted_design_return or execution_rework) and target == current)
650
796
  ):
651
797
  raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "return target must be an earlier phase in the current route")
652
798
  reason = _required_text(args.reason, "--reason")
@@ -683,7 +829,15 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
683
829
  reason = _required_text(args.reason, "--reason")
684
830
  target = _required_text(args.target_phase, "--target-phase")
685
831
  evidence = _refs(args.evidence_ref, "--evidence-ref", required=True)
832
+ if target not in PHASE_ID_SET:
833
+ raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "--target-phase must be a declared phase")
686
834
  old_ids = state["phase_ids"]
835
+ old_skips = state["skip_records"]
836
+ was_guarded = _coverage_enabled(state)
837
+ if args.enable_coverage and target != PHASE_IDS[0]:
838
+ raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "enabling coverage for an existing task requires returning to requirements")
839
+ if args.enable_coverage:
840
+ state["coverage_contract_version"] = 1
687
841
  changed = [phase for phase in PHASE_IDS if (phase in old_ids) != (phase in phases)]
688
842
  classification_changed = any(
689
843
  new != state[field]
@@ -699,10 +853,13 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
699
853
  and bool(evidence)
700
854
  and args.return_kind == "withdrawal"
701
855
  )
702
- if not changed and not classification_changed and target == current and not reviewed_delivery:
856
+ if not changed and not classification_changed and target == current and not (reviewed_delivery or args.enable_coverage):
703
857
  raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "the updated route and target are unchanged")
704
858
  earliest_change = min((PHASE_IDS.index(phase) for phase in changed), default=PHASE_IDS.index(target))
705
- if target not in PHASE_ID_SET or (PHASE_IDS.index(target) > earliest_change and not withdrawal_route):
859
+ if (PHASE_IDS[3] in changed and PHASE_IDS[2] in phases
860
+ and state["phases"].get(PHASE_IDS[2], {}).get("status") == "accepted"):
861
+ earliest_change = min(earliest_change, 2)
862
+ if PHASE_IDS.index(target) > earliest_change and not withdrawal_route:
706
863
  raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "--target-phase must cover the earliest affected route change")
707
864
  omitted = [phase for phase in PHASE_IDS if phase not in phases]
708
865
  old_phases = state["phases"]
@@ -714,6 +871,14 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
714
871
  state["project_context"] = project_context
715
872
  state["phase_ids"] = phases
716
873
  state["phases"] = {phase: old_phases.get(phase, _phase_record(state["input_revision"])) for phase in phases}
874
+ if not withdrawal_route and _coverage_enabled(state) and not was_guarded and target != PHASE_IDS[0]:
875
+ _requirements_ids(task_dir, _required_text(old_phases[PHASE_IDS[0]].get("result_ref"), "accepted requirements result"))
876
+ if withdrawal_route or _coverage_enabled(state):
877
+ state.pop("complexity_reduction", None)
878
+ elif was_guarded or state.get("complexity_reduction") is not None:
879
+ state["complexity_reduction"] = _omission_basis(
880
+ task_dir, "complexity_reduction", evidence, old_phases[PHASE_IDS[0]]
881
+ )
717
882
  affected = [phase for phase in phases if PHASE_IDS.index(phase) >= PHASE_IDS.index(target)]
718
883
  for phase_id in affected:
719
884
  state["phases"][phase_id].update({
@@ -729,7 +894,6 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
729
894
  and PHASE_IDS.index(previous_current) < PHASE_IDS.index(target)
730
895
  ):
731
896
  state["current_phase_id"] = previous_current
732
- state["phases"][previous_current]["status"] = "active"
733
897
  else:
734
898
  next_current = next((phase for phase in phases if PHASE_IDS.index(phase) >= PHASE_IDS.index(target)), None)
735
899
  state["current_phase_id"] = next_current
@@ -751,9 +915,9 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
751
915
  }
752
916
  for phase_id in omitted:
753
917
  phase_record = state["phases"].get(phase_id, old_phases.get(phase_id, _phase_record(state["input_revision"])))
918
+ preserved = old_skips.get(phase_id) if PHASE_IDS.index(phase_id) < PHASE_IDS.index(target) else None
754
919
  state["skip_records"][phase_id] = {
755
- "reason": reason,
756
- "evidence_refs": evidence,
920
+ **(preserved or {"reason": reason, "evidence_refs": evidence}),
757
921
  "task_route_revision": state["task_route_revision"],
758
922
  "input_revision": state["input_revision"],
759
923
  "artifact_revision": phase_record["artifact_revision"],
@@ -785,24 +949,27 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
785
949
  "evidence_refs": evidence,
786
950
  "task_route_revision": state["task_route_revision"],
787
951
  }
952
+ if not withdrawal_route and state["phases"][PHASE_IDS[0]]["status"] == "accepted":
953
+ _bind_omissions(task_dir, state)
954
+ _require_current_omissions(task_dir, state)
788
955
  elif action == "authorize":
789
- if current not in {PHASE_IDS[2], PHASE_IDS[3]}:
956
+ if current not in {PHASE_IDS[2], PHASE_IDS[3]} or PHASE_IDS[3] not in state["phase_ids"]:
790
957
  raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "implementation authorization is recorded at the Task Implementation and Test Verification Phase entry")
958
+ if current == PHASE_IDS[3] and record["status"] != "active":
959
+ raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "resume the implementation phase before authorizing")
791
960
  contract_ref = _required_text(args.contract_ref, "--contract-ref")
792
961
  approval_ref = _required_text(args.approval_ref, "--approval-ref")
793
- design = state["phases"].get(PHASE_IDS[2])
794
- if PHASE_IDS[2] in state["phase_ids"]:
795
- if not isinstance(design, dict) or design.get("status") != "accepted" or design.get("outcome_kind") != "implementation_contract" or design.get("result_ref") != contract_ref:
796
- raise TaskWorkflowError("TASK_PHASE_CONTRACT_NOT_ACCEPTED", "authorize the accepted implementation contract from Solution Design and Convergence Phase")
797
- artifact_refs = design.get("artifact_refs")
798
- if not isinstance(artifact_refs, list) or any(not isinstance(ref, str) for ref in artifact_refs):
799
- raise TaskWorkflowError("TASK_PHASE_TASK_INVALID", "accepted Solution Design and Convergence Phase artifact references are invalid")
800
- if _artifact_digest(task_dir, artifact_refs) != design.get("artifact_revision"):
801
- raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "Solution Design and Convergence Phase implementation contract changed after acceptance; refresh and accept the current artifact before authorization")
802
- elif contract_ref not in state.get("skip_records", {}).get(PHASE_IDS[2], {}).get("evidence_refs", []):
803
- raise TaskWorkflowError("TASK_PHASE_CONTRACT_NOT_ACCEPTED", "when Solution Design and Convergence Phase is omitted, the implementation contract must be among its route evidence")
804
- _require_acceptance_coverage(task_dir, contract_ref)
805
- state["implementation_authorization"] = {"contract_ref": contract_ref, "contract_revision": _artifact_digest(task_dir, [contract_ref]), "approval_ref": approval_ref, "task_route_revision": state["task_route_revision"]}
962
+ if not _matches_contract(state, contract_ref):
963
+ raise TaskWorkflowError("TASK_PHASE_CONTRACT_NOT_ACCEPTED", "authorize the accepted implementation contract or the contract bound to design omission evidence")
964
+ _require_current_accepted_artifacts(task_dir, state)
965
+ _require_current_omissions(task_dir, state)
966
+ _check_coverage(task_dir, state, PHASE_IDS[2], "implementation_contract", contract_ref)
967
+ contract_revision = _artifact_digest(task_dir, [contract_ref])
968
+ if args.artifact_revision is not None:
969
+ approved_revision = design_preflight(task_dir, state, "implementation_contract", contract_ref, None)["artifact_revision"]
970
+ if args.artifact_revision != approved_revision:
971
+ raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "authorization refers to a different candidate")
972
+ state["implementation_authorization"] = {"contract_ref": contract_ref, "contract_revision": contract_revision, "approval_ref": approval_ref, "task_route_revision": state["task_route_revision"]}
806
973
  if current == PHASE_IDS[2]:
807
974
  _advance(state, current)
808
975
  else:
@@ -826,7 +993,79 @@ def cmd_phase(args: argparse.Namespace) -> int:
826
993
  return 1
827
994
 
828
995
 
829
- DELEGATION_DEPENDENCIES = {"pennix-lifecycle", "paseo", "git"}
996
+ def _preflight(args: argparse.Namespace, task_dir: Path, state: dict) -> int:
997
+ if args.expected_route_revision is not None:
998
+ _expected_route(state, args.expected_route_revision)
999
+ print(json.dumps(phase_preflight(task_dir, state, args.outcome_kind,
1000
+ args.result_ref or args.contract_ref, args.artifact_revision), ensure_ascii=False))
1001
+ return 0
1002
+
1003
+
1004
+ def phase_preflight(task_dir: Path, state: dict, outcome: str | None, ref: str | None, revision: str | None) -> dict:
1005
+ """Validate a candidate before asking; never accept or mutate phase state."""
1006
+ current = state.get("current_phase_id")
1007
+ if current == PHASE_IDS[2] or (current == PHASE_IDS[3] and
1008
+ (ref is None or _matches_contract(state, ref))):
1009
+ return design_preflight(task_dir, state, outcome, ref, revision)
1010
+ current, record = _phase(state)
1011
+ if current != PHASE_IDS[0]:
1012
+ _require_current_requirements_confirmation(task_dir, state)
1013
+ _require_current_accepted_artifacts(task_dir, state)
1014
+ _require_current_omissions(task_dir, state)
1015
+ outcome = outcome or "accepted"
1016
+ if current == PHASE_IDS[0] and outcome != "accepted":
1017
+ raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "requirements preflight requires phase_result=accepted")
1018
+ ref = _required_text(ref or record.get("result_ref"), "--result-ref")
1019
+ if ref not in record["artifact_refs"]:
1020
+ raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "bind the current phase candidate with phase artifact before preflight")
1021
+ candidate = _check_candidate(task_dir, record["artifact_refs"], record["artifact_revision"], revision)
1022
+ if current == PHASE_IDS[0]:
1023
+ if _coverage_enabled(state):
1024
+ _requirements_ids(task_dir, ref)
1025
+ elif current == PHASE_IDS[1]:
1026
+ _check_coverage(task_dir, state, current, outcome, ref)
1027
+ return {
1028
+ "status": "ready", "task": task_dir.name, "phase_id": current,
1029
+ "route_revision": state["task_route_revision"], "input_revision": state["input_revision"],
1030
+ "outcome_kind": outcome, "result_ref": ref, "artifact_revision": candidate,
1031
+ }
1032
+
1033
+
1034
+ def design_preflight(task_dir: Path, state: dict, outcome: str | None, ref: str | None, revision: str | None) -> dict:
1035
+ current = state.get("current_phase_id")
1036
+ if current not in {PHASE_IDS[2], PHASE_IDS[3]}:
1037
+ raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "preflight requires design or the implementation entry after design omission")
1038
+ _require_current_requirements_confirmation(task_dir, state)
1039
+ _require_current_accepted_artifacts(task_dir, state)
1040
+ _require_current_omissions(task_dir, state)
1041
+ design = state["phases"].get(PHASE_IDS[2], {})
1042
+ outcome = outcome or design.get("outcome_kind") or "implementation_contract"
1043
+ if (outcome not in {"implementation_contract", "analysis_conclusion", "no_go"}
1044
+ or (outcome == "implementation_contract") != (PHASE_IDS[3] in state["phase_ids"])):
1045
+ raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "preflight result conflicts with the route")
1046
+ ref = _required_text(ref or design.get("result_ref"), "--result-ref or --contract-ref")
1047
+ if current == PHASE_IDS[2]:
1048
+ if ref not in design["artifact_refs"]:
1049
+ raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "bind the current design candidate with phase artifact before preflight")
1050
+ candidate = _check_candidate(task_dir, design["artifact_refs"], design["artifact_revision"], revision)
1051
+ else:
1052
+ if not _matches_contract(state, ref):
1053
+ raise TaskWorkflowError("TASK_PHASE_CONTRACT_NOT_ACCEPTED", "preflight requires the contract in the design omission record")
1054
+ if design.get("status") == "accepted":
1055
+ candidate = _artifact_digest(task_dir, [ref])
1056
+ if revision is not None and revision != candidate:
1057
+ raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "candidate changed since review")
1058
+ else:
1059
+ candidate = _check_candidate(task_dir, [ref], revision)
1060
+ _check_coverage(task_dir, state, PHASE_IDS[2], outcome, ref)
1061
+ return {
1062
+ "status": "ready", "task": task_dir.name, "route_revision": state["task_route_revision"],
1063
+ "input_revision": state["input_revision"], "outcome_kind": outcome, "result_ref": ref,
1064
+ "artifact_revision": candidate, "requirements_revision": state["phases"][PHASE_IDS[0]]["artifact_revision"],
1065
+ "decision_revision": state["phases"].get(PHASE_IDS[1], {}).get("artifact_revision"),
1066
+ "omissions": {phase: skip.get("basis") for phase, skip in state["skip_records"].items() if phase in _OPTIONAL_PHASES},
1067
+ "complexity_reduction": state.get("complexity_reduction"),
1068
+ }
830
1069
 
831
1070
 
832
1071
  def _git_output(args: list[str], cwd: Path) -> str:
@@ -862,300 +1101,6 @@ def _paseo_list(args: list[str], cwd: Path, code: str) -> list[dict]:
862
1101
  return value
863
1102
 
864
1103
 
865
- def _delegation_binding(repo_root: Path, child_dir: Path, child_data: dict, result_path: str) -> dict:
866
- if not isinstance(result_path, str) or Path(result_path).is_absolute() or ".." in Path(result_path).parts or not result_path.startswith(".trellis/delegated-results/"):
867
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_INVALID", "result path must stay under .trellis/delegated-results/")
868
- try:
869
- contract_path = (child_dir / "prd.md").resolve(strict=True)
870
- contract_path.relative_to(child_dir.resolve())
871
- role_path = (repo_root / ".trellis/agents/delegated-worktree-primary-agent.md").resolve(strict=True)
872
- role_path.relative_to((repo_root / ".trellis/agents").resolve())
873
- if not contract_path.is_file() or not role_path.is_file() or contract_path.stat().st_size + role_path.stat().st_size > 1048576:
874
- raise ValueError("delegated contract and role must be regular files within the size budget")
875
- contract = contract_path.read_bytes()
876
- role = role_path.read_bytes()
877
- except (OSError, ValueError) as error:
878
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_INVALID", str(error)) from error
879
- if not contract.strip() or not role.strip():
880
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_INVALID", "child PRD and delegated role must be nonempty")
881
- return {
882
- "contract_sha256": hashlib.sha256(contract).hexdigest(),
883
- "role_sha256": hashlib.sha256(role).hexdigest(),
884
- "branch": _required_text(child_data.get("branch"), "child branch"),
885
- "base_commit": _git_output(["rev-parse", "--verify", "--end-of-options", f"{_required_text(child_data.get('base_branch'), 'child base_branch')}^{{commit}}"], repo_root),
886
- "result_path": result_path,
887
- }
888
-
889
-
890
- def cmd_delegate_bind(args: argparse.Namespace) -> int:
891
- try:
892
- repo_root = get_repo_root().resolve()
893
- child_dir = _task_dir(args.child_task)
894
- child, _ = _load(child_dir)
895
- if not isinstance(child.get("parent"), str) or not child["parent"].strip():
896
- raise TaskWorkflowError("TASK_DELEGATE_PARENT_LINK_INVALID", "child task has no parent link")
897
- parent_dir = _task_dir(child["parent"])
898
- parent, meta = _load(parent_dir)
899
- if child_dir.name not in parent.get("children", []) or not implementation_start_ready(parent, parent_dir):
900
- raise TaskWorkflowError("TASK_DELEGATE_IMPLEMENTATION_NOT_AUTHORIZED", "bind only a linked child within current parent implementation authorization")
901
- state = _state(meta)
902
- authorization = state["implementation_authorization"]
903
- result_path = args.result_path or f".trellis/delegated-results/{child_dir.name}.md"
904
- binding = _delegation_binding(repo_root, child_dir, child, result_path)
905
- binding.update({"authorization_ref": authorization["approval_ref"], "parent_contract_revision": authorization["contract_revision"], "task_route_revision": state["task_route_revision"]})
906
- meta.setdefault("delegation_authorizations", {})[child_dir.name] = binding
907
- _save(parent_dir / FILE_TASK_JSON, parent)
908
- print(json.dumps(binding, ensure_ascii=False))
909
- return 0
910
- except TaskWorkflowError as error:
911
- print(f"{error.code}: {error}", file=sys.stderr)
912
- return 1
913
-
914
-
915
- def cmd_delegate_start(args: argparse.Namespace) -> int:
916
- try:
917
- repo_root = get_repo_root().resolve()
918
- child_dir = _task_dir(args.child_task)
919
- child_data, _ = _load(child_dir)
920
- parent_ref = child_data.get("parent")
921
- if not isinstance(parent_ref, str) or not parent_ref.strip():
922
- raise TaskWorkflowError("TASK_DELEGATE_PARENT_LINK_INVALID", "child task has no parent link")
923
- parent_dir = _task_dir(parent_ref)
924
- lock_dirs = sorted((parent_dir, child_dir), key=str)
925
- with _task_lock(lock_dirs[0]), _task_lock(lock_dirs[1]):
926
- parent_data, parent_meta = _load(parent_dir)
927
- child_data, child_meta = _load(child_dir)
928
- if child_data.get("parent") != parent_dir.name or child_dir.name not in parent_data.get("children", []):
929
- raise TaskWorkflowError("TASK_DELEGATE_PARENT_LINK_INVALID", "parent and child task links do not match")
930
- from .task_continuity import assert_task_mutation_allowed
931
-
932
- assert_task_mutation_allowed(repo_root, parent_dir, parent_data)
933
- if child_data.get("status") not in {"planning", "in_progress"}:
934
- raise TaskWorkflowError("TASK_DELEGATE_CHILD_TERMINAL", "only a planning or in-progress child task can be delegated")
935
- if parent_data.get("status") != "in_progress" or not implementation_start_ready(parent_data, parent_dir):
936
- raise TaskWorkflowError("TASK_DELEGATE_IMPLEMENTATION_NOT_AUTHORIZED", "parent task is not at an authorized Task Implementation and Test Verification Phase entry")
937
-
938
- state = _state(parent_meta)
939
- admission = state.get("route_dependency_admission")
940
- if not isinstance(admission, dict):
941
- raise TaskWorkflowError("TASK_DELEGATE_ADMISSION_REQUIRED", "parent task has no current route dependency admission")
942
- dependencies = admission.get("dependencies", [])
943
- if (
944
- admission.get("admission_state") != "ready"
945
- or admission.get("task_route_revision") != state.get("task_route_revision")
946
- or not DELEGATION_DEPENDENCIES.issubset(set(dependencies))
947
- or not admission.get("evidence_refs")
948
- ):
949
- raise TaskWorkflowError("TASK_DELEGATE_ADMISSION_REQUIRED", "route dependency admission must be current, ready, evidenced, and include Pennix Lifecycle, Paseo, and Git")
950
-
951
- contract_path = child_dir / "prd.md"
952
- try:
953
- resolved_contract = contract_path.resolve(strict=True)
954
- resolved_contract.relative_to(child_dir.resolve())
955
- contract_bytes = resolved_contract.read_bytes()
956
- contract = contract_bytes.decode("utf-8")
957
- except (OSError, UnicodeError, ValueError) as error:
958
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_INVALID", f"child task prd.md is unavailable: {error}") from error
959
- if not contract.strip():
960
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_INVALID", "child task prd.md is empty")
961
-
962
- branch_value = child_data.get("branch")
963
- base_value = child_data.get("base_branch")
964
- if not isinstance(branch_value, str) or not isinstance(base_value, str):
965
- raise TaskWorkflowError("TASK_DELEGATE_GIT_INVALID", "child task branch and base_branch must be set")
966
- branch = _required_text(branch_value, "child task branch")
967
- base_branch = _required_text(base_value, "child task base_branch")
968
- if branch == base_branch:
969
- raise TaskWorkflowError("TASK_DELEGATE_GIT_INVALID", "child task branch and base_branch must differ")
970
- _git_output(["check-ref-format", "--branch", branch], repo_root)
971
- _git_output(["check-ref-format", "--branch", base_branch], repo_root)
972
- top_level = Path(_git_output(["rev-parse", "--show-toplevel"], repo_root)).resolve()
973
- if top_level != repo_root:
974
- raise TaskWorkflowError("TASK_DELEGATE_GIT_INVALID", "Trellis repository root does not match the Git checkout")
975
- base_commit = _git_output(["rev-parse", "--verify", "--end-of-options", f"{base_branch}^{{commit}}"], repo_root)
976
- branch_exists, _, _ = run_git(["show-ref", "--verify", "--quiet", f"refs/heads/{branch}"], cwd=repo_root)
977
- if branch_exists not in {0, 1}:
978
- raise TaskWorkflowError("TASK_DELEGATE_GIT_INVALID", "could not check whether the child task branch already exists")
979
-
980
- if shutil.which("paseo") is None:
981
- raise TaskWorkflowError("TASK_DELEGATE_PASEO_UNAVAILABLE", "Paseo CLI is not available on PATH")
982
- try:
983
- version = subprocess.run(["paseo", "--version"], cwd=repo_root, capture_output=True, text=True, encoding="utf-8")
984
- except OSError as error:
985
- raise TaskWorkflowError("TASK_DELEGATE_PASEO_UNAVAILABLE", f"could not run Paseo: {error}") from error
986
- if version.returncode != 0:
987
- raise TaskWorkflowError("TASK_DELEGATE_PASEO_UNAVAILABLE", (version.stderr or version.stdout).strip() or "Paseo CLI preflight failed")
988
- _paseo_list(["agent", "ls", "--all", "--global", "--background", "--json"], repo_root, "TASK_DELEGATE_PASEO_UNAVAILABLE")
989
- role_path = repo_root / ".trellis" / "agents" / "delegated-worktree-primary-agent.md"
990
- try:
991
- role = role_path.read_text(encoding="utf-8")
992
- except (OSError, UnicodeError) as error:
993
- raise TaskWorkflowError("TASK_DELEGATE_ROLE_MISSING", f"delegated worktree role is unavailable: {error}") from error
994
-
995
- authorization = state.get("implementation_authorization")
996
- if not isinstance(authorization, dict) or not isinstance(authorization.get("approval_ref"), str):
997
- raise TaskWorkflowError("TASK_DELEGATE_AUTHORIZATION_INVALID", "current implementation authorization is invalid")
998
- contract_digest = hashlib.sha256(contract_bytes).hexdigest()
999
- bindings = parent_meta.get("delegation_authorizations", {})
1000
- binding = bindings.get(child_dir.name) if isinstance(bindings, dict) else None
1001
- if not isinstance(binding, dict):
1002
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_NOT_BOUND", "freeze this child through delegate-bind before dispatch")
1003
- actual = _delegation_binding(repo_root, child_dir, child_data, binding.get("result_path", ""))
1004
- if any(binding.get(key) != value for key, value in actual.items()) or actual["contract_sha256"] != contract_digest or actual["role_sha256"] != hashlib.sha256(role.encode("utf-8")).hexdigest() or binding.get("authorization_ref") != authorization["approval_ref"] or binding.get("parent_contract_revision") != authorization["contract_revision"] or binding.get("task_route_revision") != state["task_route_revision"]:
1005
- raise TaskWorkflowError("TASK_DELEGATE_STALE_CONTRACT", "child PRD, role, Git base, output path, or parent authorization changed; review and bind the child again")
1006
- prompt_bytes = len((role + contract).encode("utf-8"))
1007
- if prompt_bytes > (24000 if os.name == "nt" else 96000):
1008
- raise TaskWorkflowError("TASK_DELEGATE_PROMPT_TOO_LARGE", "delegated prompt exceeds the native Paseo argv budget; narrow the contract before creating resources")
1009
- previous = child_meta.get("delegated_worktree_execution_record")
1010
- reuse_workspace = False
1011
- workspace_id = None
1012
- worktree = None
1013
- if previous is not None:
1014
- if not isinstance(previous, dict):
1015
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "existing execution mapping is invalid; reconcile it before starting another run")
1016
- if previous.get("authorization_ref") == authorization["approval_ref"]:
1017
- raise TaskWorkflowError("TASK_DELEGATE_REAUTHORIZATION_REQUIRED", "reconcile the prior execution and record fresh implementation authorization before retrying")
1018
- if (
1019
- previous.get("parent_task_id") != parent_dir.name
1020
- or previous.get("parent_task_route_revision") != state["task_route_revision"]
1021
- or previous.get("implementation_contract_sha256") != contract_digest
1022
- or previous.get("branch") != branch
1023
- ):
1024
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the prior execution belongs to a different route, contract, or branch; create a newly authorized child task")
1025
- previous_workspace_id = previous.get("workspace_id")
1026
- previous_worktree_path = previous.get("worktree_path")
1027
- if not isinstance(previous_workspace_id, str) or not previous_workspace_id.strip() or not isinstance(previous_worktree_path, str) or not previous_worktree_path.strip():
1028
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the prior execution mapping is incomplete; reconcile the Paseo workspace and worktree before retrying")
1029
- previous_worktree = Path(previous_worktree_path).expanduser().resolve()
1030
- agents = _paseo_list([
1031
- "agent", "ls", "--all", "--global", "--background", "--json",
1032
- "--label", f"trellis.task_id={previous.get('label_task_id', child_dir.name)}",
1033
- ], repo_root, "TASK_DELEGATE_RECONCILIATION_REQUIRED")
1034
- for agent in agents:
1035
- agent_id = agent.get("id")
1036
- if agent.get("status") != "closed":
1037
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "a Paseo agent for this child task is not confirmed closed")
1038
- if agent_id == previous.get("agent_id"):
1039
- agent_cwd = agent.get("cwd")
1040
- if not isinstance(agent_cwd, str) or Path(agent_cwd).expanduser().resolve() != previous_worktree:
1041
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the recorded Paseo agent does not match the mapped worktree")
1042
- if previous.get("agent_id") and not any(agent.get("id") == previous.get("agent_id") for agent in agents):
1043
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the recorded Paseo agent is not present for reconciliation")
1044
- workspaces = _paseo_list(["workspace", "ls", "--background", "--json"], repo_root, "TASK_DELEGATE_RECONCILIATION_REQUIRED")
1045
- workspace_row = next((item for item in workspaces if item.get("workspaceId") == previous_workspace_id), None)
1046
- if workspace_row is not None:
1047
- workspace_cwd = workspace_row.get("cwd")
1048
- if not isinstance(workspace_cwd, str) or Path(workspace_cwd).expanduser().resolve() != previous_worktree or not previous_worktree.is_dir():
1049
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the recorded Paseo workspace does not match its existing worktree")
1050
- worktree = previous_worktree
1051
- worktree_root = Path(_git_output(["rev-parse", "--show-toplevel"], worktree)).resolve()
1052
- common_dir = Path(_git_output(["rev-parse", "--git-common-dir"], repo_root))
1053
- worktree_common_dir = Path(_git_output(["rev-parse", "--git-common-dir"], worktree))
1054
- common_dir = (common_dir if common_dir.is_absolute() else repo_root / common_dir).resolve()
1055
- worktree_common_dir = (worktree_common_dir if worktree_common_dir.is_absolute() else worktree / worktree_common_dir).resolve()
1056
- if (
1057
- worktree_root != worktree
1058
- or worktree_common_dir != common_dir
1059
- or _git_output(["branch", "--show-current"], worktree) != branch
1060
- or _git_output(["rev-parse", "HEAD"], worktree) != base_commit
1061
- or _git_output(["status", "--porcelain", "--untracked-files=all"], worktree)
1062
- ):
1063
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the prior worktree is not clean at the authorized branch and Git base; preserve and reconcile it before retrying")
1064
- workspace_id = previous_workspace_id
1065
- reuse_workspace = True
1066
- else:
1067
- if previous_worktree.exists() or branch_exists == 0:
1068
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the prior workspace is unavailable but its worktree or branch remains; reconcile it before rebuilding")
1069
- elif branch_exists == 0:
1070
- raise TaskWorkflowError("TASK_DELEGATE_GIT_INVALID", f"child task branch already exists: {branch}")
1071
-
1072
- record = {
1073
- "parent_task_id": parent_dir.name,
1074
- "parent_task_route_revision": state["task_route_revision"],
1075
- "authorization_ref": authorization["approval_ref"],
1076
- "implementation_contract_ref": "prd.md",
1077
- "implementation_contract_sha256": contract_digest,
1078
- "branch": branch,
1079
- "base_commit": base_commit,
1080
- "workspace_id": workspace_id,
1081
- "worktree_path": str(worktree) if worktree else None,
1082
- "agent_id": None,
1083
- "label_task_id": child_dir.name,
1084
- "role_sha256": actual["role_sha256"],
1085
- "result_path": actual["result_path"],
1086
- "status": "starting",
1087
- "started_at": datetime.now(timezone.utc).isoformat(),
1088
- }
1089
- if previous is not None:
1090
- child_meta.setdefault("delegated_worktree_execution_history", []).append(previous)
1091
- child_meta["delegated_worktree_execution_record"] = record
1092
- _save(child_dir / FILE_TASK_JSON, child_data)
1093
-
1094
- try:
1095
- if not reuse_workspace:
1096
- workspace = _paseo_json([
1097
- "workspace", "create", "--isolation", "worktree", "--path", str(repo_root),
1098
- "--mode", "branch-off", "--worktree-slug", child_dir.name,
1099
- "--new-branch", branch, "--base", base_commit,
1100
- "--title", child_data.get("title") or child_dir.name, "--json",
1101
- ], repo_root, "TASK_DELEGATE_WORKSPACE_FAILED")
1102
- if not isinstance(workspace, dict):
1103
- raise TaskWorkflowError("TASK_DELEGATE_WORKSPACE_FAILED", "Paseo returned an invalid workspace response")
1104
- workspace_id = workspace.get("workspaceId")
1105
- worktree_path = workspace.get("cwd")
1106
- if not isinstance(workspace_id, str) or not workspace_id.strip() or not isinstance(worktree_path, str) or not worktree_path.strip():
1107
- raise TaskWorkflowError("TASK_DELEGATE_WORKSPACE_FAILED", "Paseo workspace response lacks workspaceId or cwd")
1108
- worktree = Path(worktree_path).expanduser()
1109
- if not worktree.is_absolute():
1110
- worktree = repo_root / worktree
1111
- worktree = worktree.resolve()
1112
- record.update({"workspace_id": workspace_id, "worktree_path": str(worktree), "status": "workspace_created"})
1113
- _save(child_dir / FILE_TASK_JSON, child_data)
1114
- if not isinstance(worktree, Path) or not isinstance(workspace_id, str):
1115
- raise TaskWorkflowError("TASK_DELEGATE_WORKSPACE_FAILED", "Paseo workspace mapping is incomplete")
1116
- worktree_root = Path(_git_output(["rev-parse", "--show-toplevel"], worktree)).resolve()
1117
- common_dir = Path(_git_output(["rev-parse", "--git-common-dir"], repo_root))
1118
- worktree_common_dir = Path(_git_output(["rev-parse", "--git-common-dir"], worktree))
1119
- common_dir = (common_dir if common_dir.is_absolute() else repo_root / common_dir).resolve()
1120
- worktree_common_dir = (worktree_common_dir if worktree_common_dir.is_absolute() else worktree / worktree_common_dir).resolve()
1121
- if worktree_root != worktree or worktree_common_dir != common_dir:
1122
- raise TaskWorkflowError("TASK_DELEGATE_WORKSPACE_FAILED", "Paseo workspace is not a worktree of the task repository")
1123
- if _git_output(["branch", "--show-current"], worktree) != branch or _git_output(["rev-parse", "HEAD"], worktree) != base_commit:
1124
- raise TaskWorkflowError("TASK_DELEGATE_WORKSPACE_FAILED", "Paseo worktree branch or base does not match the child task")
1125
-
1126
- prompt = (
1127
- "Follow the delegated worktree role below. The child task's prd.md is the sole task-specific implementation contract; "
1128
- "the parent authorization and Git baseline are execution metadata. Do not accept task phases or change task lifecycle state.\n\n"
1129
- f"Parent task: {parent_dir.name}\nParent route revision: {state['task_route_revision']}\n"
1130
- f"Authorized contract: prd.md\nBranch: {branch}\nBase commit: {base_commit}\n\n"
1131
- f"Assigned result artifact: {actual['result_path']}\n"
1132
- f"{role}\n\n## Child task prd.md\n{contract}"
1133
- )
1134
- agent = _paseo_json([
1135
- "run", "--workspace", workspace_id, "--no-wait", "--json",
1136
- "--title", child_data.get("title") or child_dir.name,
1137
- "--label", f"trellis.task_id={child_dir.name}",
1138
- "--label", f"trellis.parent_task_id={parent_dir.name}", prompt,
1139
- ], repo_root, "TASK_DELEGATE_AGENT_START_FAILED")
1140
- if not isinstance(agent, dict):
1141
- raise TaskWorkflowError("TASK_DELEGATE_AGENT_START_FAILED", "Paseo returned an invalid agent response")
1142
- agent_id = agent.get("agentId")
1143
- if not isinstance(agent_id, str) or not agent_id.strip():
1144
- raise TaskWorkflowError("TASK_DELEGATE_AGENT_START_FAILED", "Paseo run response lacks agentId")
1145
- record.update({"agent_id": agent_id, "status": "running"})
1146
- _save(child_dir / FILE_TASK_JSON, child_data)
1147
- except TaskWorkflowError as error:
1148
- record["status"] = "reconciliation_required"
1149
- record["last_error"] = {"code": error.code, "reason": str(error)}
1150
- _save(child_dir / FILE_TASK_JSON, child_data)
1151
- raise
1152
-
1153
- print(json.dumps(record, ensure_ascii=False))
1154
- return 0
1155
- except TaskWorkflowError as error:
1156
- print(f"{error.code}: {error}", file=sys.stderr)
1157
- return 1
1158
-
1159
1104
  def cmd_cancel_task(args: argparse.Namespace) -> int:
1160
1105
  try:
1161
1106
  task_dir = _task_dir(args.task_dir)
@@ -1240,6 +1185,16 @@ def cmd_reopen_task(args: argparse.Namespace) -> int:
1240
1185
  return 1
1241
1186
 
1242
1187
 
1188
+ def _required_implementation_error(data: dict, state: dict) -> str | None:
1189
+ if PHASE_IDS[3] in state["phase_ids"]:
1190
+ implementation = state["phases"].get(PHASE_IDS[3])
1191
+ if not isinstance(implementation, dict) or implementation.get("status") != "accepted":
1192
+ return "the required implementation phase must be accepted before closeout"
1193
+ if data.get("status") not in {"in_progress", "completed"}:
1194
+ return "the required implementation phase did not enter in_progress"
1195
+ return None
1196
+
1197
+
1243
1198
  def task_closeout_readiness(data: dict, disposition: str) -> str | None:
1244
1199
  if "meta" in data and not isinstance(data["meta"], dict):
1245
1200
  return "task metadata is malformed"
@@ -1251,6 +1206,9 @@ def task_closeout_readiness(data: dict, disposition: str) -> str | None:
1251
1206
  return "task phase workflow data is malformed"
1252
1207
  if state.get("current_phase_id") is not None:
1253
1208
  return "the current task phase route is not complete"
1209
+ implementation_error = _required_implementation_error(data, state)
1210
+ if implementation_error:
1211
+ return implementation_error
1254
1212
  for phase_id in state["phase_ids"]:
1255
1213
  phase = state["phases"].get(phase_id)
1256
1214
  if not isinstance(phase, dict) or phase.get("status") not in {"accepted", "skipped"}:
@@ -1306,6 +1264,14 @@ def _validate_child_dispositions(
1306
1264
  raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", f"child task link is inconsistent: {child_id}")
1307
1265
  if choice == "integrated" and child_data.get("status") != "completed":
1308
1266
  raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", f"child task is not completed and integrated: {child_id}")
1267
+ if choice == "integrated":
1268
+ from .worktree_delegation import resolve_record
1269
+ delegated = resolve_record(get_repo_root(), child_dir, child_data)
1270
+ if delegated and delegated.get("binding", {}).get("format_version") == 3 and (
1271
+ delegated.get("status") != "retired"
1272
+ or delegated.get("closure_evidence", {}).get("disposition") != "integrated"
1273
+ or not delegated.get("owner_acceptance")):
1274
+ raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", f"child source is retained but not owner-accepted: {child_id}")
1309
1275
  if choice == "cancelled" and child_data.get("status") != "cancelled":
1310
1276
  raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", f"child task must be cancelled through its own flow: {child_id}")
1311
1277
  return choices
@@ -1377,15 +1343,36 @@ def _assert_delegated_resources_closed(task_dir: Path, data: dict) -> None:
1377
1343
  if not isinstance(children, list):
1378
1344
  raise TaskWorkflowError("TASK_PHASE_RESOURCE_ACTIVE", "linked child task list is malformed")
1379
1345
  for task_id in [task_dir.name, *children]:
1380
- _, child_meta = _load(_task_dir(task_id))
1381
- _assert_delegated_record_closed(task_id, child_meta.get("delegated_worktree_execution_record"))
1346
+ child_dir = _task_dir(task_id)
1347
+ child_data, _ = _load(child_dir)
1348
+ from .worktree_delegation import resolve_record
1349
+ _assert_delegated_record_closed(task_id, resolve_record(get_repo_root(), child_dir, child_data))
1382
1350
 
1383
1351
 
1384
1352
  def _assert_delegated_record_closed(task_id: str, record) -> None:
1385
1353
  if record is None:
1386
1354
  return
1387
1355
  if isinstance(record, dict) and record.get("status") == "retired" and isinstance(record.get("closure_evidence"), dict):
1356
+ if record.get("binding", {}).get("format_version") == 2 and record.get("agent_id") and (
1357
+ record["closure_evidence"].get("observation", {}).get("agent", {}).get("status") != "closed"):
1358
+ raise TaskWorkflowError("TASK_PHASE_RESOURCE_ACTIVE", f"legacy Agent for {task_id} must be closed natively, then refreshed with retained reconciliation")
1359
+ if record.get("binding", {}).get("format_version") == 3:
1360
+ evidence = record["closure_evidence"]
1361
+ closure = evidence.get("native_closure", {})
1362
+ absent = (evidence.get("native_agent_absent") is True and not record.get("agent_id")
1363
+ and evidence.get("agent_scan", {}).get("complete") is True
1364
+ and evidence.get("agent_scan", {}).get("pages", 0) > 0)
1365
+ if record.get("intent") or record.get("safety_intent") or record.get("closure_recheck_pending") or (
1366
+ not evidence.get("resource_absent") and not absent and (
1367
+ closure.get("observation", {}).get("agent", {}).get("status") != "closed"
1368
+ or closure.get("observation", {}).get("agent", {}).get("activeTurn")
1369
+ or closure.get("queue", {}).get("items") != []
1370
+ or closure.get("background", {}).get("items") != []
1371
+ or closure.get("inputs_resolved") is not True)):
1372
+ raise TaskWorkflowError("TASK_PHASE_RESOURCE_ACTIVE", f"delegated runtime/inputs for {task_id} are not confirmed closed")
1388
1373
  return
1374
+ if isinstance(record, dict) and "binding" in record:
1375
+ raise TaskWorkflowError("TASK_PHASE_RESOURCE_ACTIVE", f"protocol v1 delegation for {task_id} must be explicitly reconciled before closing or moving")
1389
1376
  agent_id = record.get("agent_id") if isinstance(record, dict) else None
1390
1377
  if not isinstance(agent_id, str) or not agent_id.strip():
1391
1378
  raise TaskWorkflowError("TASK_PHASE_RESOURCE_ACTIVE", f"delegated execution status is unknown for {task_id}; preserve the current state")
@@ -1416,6 +1403,7 @@ def cmd_complete_task(args: argparse.Namespace) -> int:
1416
1403
  if disposition not in {"delivery_ready", "no_go"}:
1417
1404
  raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", "Delivery Review and On-Site Closeout Phase must accept delivery_ready or no_go before complete")
1418
1405
  _require_current_accepted_artifacts(task_dir, state)
1406
+ _require_current_omissions(task_dir, state)
1419
1407
  readiness_error = task_closeout_readiness(data, disposition)
1420
1408
  if readiness_error:
1421
1409
  raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", readiness_error)