@tea-agent/loop-agent 0.1.0-fe-test.3 → 0.1.0-fe-test.5

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 (485) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +607 -93
  3. package/README.md +11 -5
  4. package/bin/loop-agent.js +7 -3
  5. package/dist/adapters/context-transfer/optional-pi-handoff.js +31 -0
  6. package/dist/adapters/context-transfer/pi-session.js +61 -0
  7. package/dist/application/dag/generate-task-dag.js +90 -21
  8. package/dist/application/dag/run-dag.js +41 -0
  9. package/dist/application/task-lifecycle/advance.js +40 -5
  10. package/dist/application/task-lifecycle/observe.js +171 -17
  11. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  12. package/dist/application/task-lifecycle/recommendations.js +13 -2
  13. package/dist/build-stamp.json +3 -3
  14. package/dist/cli/command-definitions.js +44 -10
  15. package/dist/cli/program.js +82 -6
  16. package/dist/cli/update/notifier.js +2 -2
  17. package/dist/cli/update/runtime-activity.js +1 -29
  18. package/dist/cli.js +2 -1
  19. package/dist/commands/client-recovery.js +11 -36
  20. package/dist/commands/dag-artifact.js +284 -0
  21. package/dist/commands/dag-context.js +184 -0
  22. package/dist/commands/dag-follow-up.js +138 -0
  23. package/dist/commands/dag-rerun-task.js +2 -0
  24. package/dist/commands/dag-rerun.js +261 -2
  25. package/dist/commands/init-model-catalog.js +486 -0
  26. package/dist/commands/init-upgrade.js +265 -97
  27. package/dist/commands/init.js +455 -28
  28. package/dist/commands/inspect-next.js +8 -0
  29. package/dist/commands/task-advance.js +73 -1
  30. package/dist/commands/task-source-prepare.js +5 -0
  31. package/dist/commands/task-status.js +1 -0
  32. package/dist/executors/dag-pi-executor.js +4323 -231
  33. package/dist/executors/pi-event-serializer.js +42 -1
  34. package/dist/executors/pi-executor.js +70 -6
  35. package/dist/executors/pi-extension-resolver.js +245 -0
  36. package/dist/executors/pi-playwright-cli-tool.js +74 -28
  37. package/dist/executors/pi-read-budget-policy.js +239 -0
  38. package/dist/executors/pi-sdk-executor.js +263 -59
  39. package/dist/executors/pi-writer-tool-policy.js +57 -1
  40. package/dist/executors/shell-executor.js +1456 -240
  41. package/dist/executors/shell-write-guard.js +14 -0
  42. package/dist/executors/workspace-write-snapshot.js +68 -0
  43. package/dist/governance/checks.js +1 -0
  44. package/dist/{worker → infrastructure}/console/app-data.js +4 -0
  45. package/dist/infrastructure/console/artifact-revision-store.js +430 -0
  46. package/dist/infrastructure/console/context-export-store.js +160 -0
  47. package/dist/infrastructure/console/dir-lock.js +132 -0
  48. package/dist/infrastructure/console/operation-store.js +417 -0
  49. package/dist/infrastructure/harness/artifact-store.js +10 -1
  50. package/dist/infrastructure/harness/atomic-write.js +35 -2
  51. package/dist/shared/context-transfer/artifact-revision.js +172 -0
  52. package/dist/shared/context-transfer.js +418 -0
  53. package/dist/shared/dag-failure-category.js +150 -0
  54. package/dist/shared/dag-prompt-override.js +27 -0
  55. package/dist/shared/openspec-spec.js +70 -4
  56. package/dist/shared/operator/capabilities.js +65 -4
  57. package/dist/shared/operator/safe-run-summary.js +1 -0
  58. package/dist/shared/path-safety.js +93 -0
  59. package/dist/shared/pi-context-pressure/checkpoint.js +116 -0
  60. package/dist/shared/pi-context-pressure/compaction-policy.js +151 -0
  61. package/dist/shared/pi-context-pressure/env.js +58 -0
  62. package/dist/shared/pi-context-pressure/extension.js +100 -0
  63. package/dist/shared/pi-context-pressure/index.js +7 -0
  64. package/dist/shared/pi-context-pressure/overflow.js +252 -0
  65. package/dist/shared/pi-context-pressure/sift-bridge.js +386 -0
  66. package/dist/shared/pi-context-pressure/telemetry.js +51 -0
  67. package/dist/shared/playwright-cli-command-policy.js +15 -0
  68. package/dist/shared/preview.js +28 -4
  69. package/dist/shared/update/console-notifier.js +100 -0
  70. package/dist/{cli → shared}/update/npm-client.js +70 -15
  71. package/dist/{cli → shared}/update/state.js +41 -13
  72. package/dist/task/config-types.js +125 -6
  73. package/dist/task/contract/adopt.js +4 -0
  74. package/dist/task/contract/apply.js +11 -1
  75. package/dist/task/contract/constants.js +3 -0
  76. package/dist/task/contract/diff.js +26 -0
  77. package/dist/task/contract/hash.js +3 -0
  78. package/dist/task/contract/import-revision.js +4 -0
  79. package/dist/task/contract/observe.js +25 -4
  80. package/dist/task/contract/paths.js +2 -1
  81. package/dist/task/contract/project.js +23 -1
  82. package/dist/task/contract/schema.js +9 -1
  83. package/dist/task/contract/transaction.js +12 -0
  84. package/dist/task/frontend-project-capability.js +203 -20
  85. package/dist/task/runtime.js +5 -2
  86. package/dist/task/source-prepare/build-draft.js +18 -3
  87. package/dist/task/source-prepare/completeness.js +188 -0
  88. package/dist/task/source-prepare/fragment-inventory.js +513 -0
  89. package/dist/task/source-prepare/index.js +3 -0
  90. package/dist/task/source-prepare/ledger-reconciliation.js +127 -0
  91. package/dist/task/source-prepare/ledger-review.js +214 -0
  92. package/dist/task/source-prepare/ledger.js +545 -0
  93. package/dist/task/source-prepare/parse-intent.js +24 -4
  94. package/dist/task/source-prepare/prepare.js +368 -2
  95. package/dist/task/source-prepare/semantic-intake.js +25 -5
  96. package/dist/task/source-prepare/source-fidelity-pi.js +384 -0
  97. package/dist/task/source-prepare/types.js +22 -0
  98. package/dist/task/source-references.js +22 -1
  99. package/dist/task/task-demand-routing.js +3 -0
  100. package/dist/worker/cli.js +18 -2
  101. package/dist/worker/console/chat/assistant-content.js +7 -0
  102. package/dist/worker/console/chat/chat-event-store.js +159 -18
  103. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  104. package/dist/worker/console/chat/context-panel.js +7 -0
  105. package/dist/worker/console/chat/deferred-turn.js +103 -0
  106. package/dist/worker/console/chat/goal-round-driver.js +72 -0
  107. package/dist/worker/console/chat/goals.js +300 -0
  108. package/dist/worker/console/chat/model-resolver.js +7 -4
  109. package/dist/worker/console/chat/operation-card.js +8 -1
  110. package/dist/worker/console/chat/pi-console-config.js +81 -10
  111. package/dist/worker/console/chat/pi-runtime.js +868 -30
  112. package/dist/worker/console/chat/provider-error.js +99 -0
  113. package/dist/worker/console/chat/repo-browser.js +101 -12
  114. package/dist/worker/console/chat/resource-preferences-store.js +1 -1
  115. package/dist/worker/console/chat/routes.js +1451 -145
  116. package/dist/worker/console/chat/sdd-data-alignment.js +222 -0
  117. package/dist/worker/console/chat/semantic-activity.js +25 -24
  118. package/dist/worker/console/chat/session-catalog.js +50 -0
  119. package/dist/worker/console/chat/session-stats.js +275 -0
  120. package/dist/worker/console/chat/session-store.js +348 -76
  121. package/dist/worker/console/chat/shortcuts.js +26 -3
  122. package/dist/worker/console/chat/sift-bridge.js +1 -0
  123. package/dist/worker/console/chat/todos.js +115 -0
  124. package/dist/worker/console/chat/tool-preview.js +42 -0
  125. package/dist/worker/console/chat/turn-process.js +185 -112
  126. package/dist/worker/console/chat/user-questions.js +266 -0
  127. package/dist/worker/console/chat/workspace-landing.js +79 -0
  128. package/dist/worker/console/console-handoff.js +82 -0
  129. package/dist/worker/console/console-update-and-init.js +115 -0
  130. package/dist/worker/console/console-update-runtime.js +84 -0
  131. package/dist/worker/console/context-transfer-diagnostics.js +198 -0
  132. package/dist/worker/console/dag-confirmation.js +1 -1
  133. package/dist/worker/console/dag-execution-receipt.js +54 -3
  134. package/dist/worker/console/doctor.js +1 -1
  135. package/dist/worker/console/draft-store.js +50 -1
  136. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  137. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  138. package/dist/worker/console/human-gate-token.js +1 -1
  139. package/dist/worker/console/index.js +6 -3
  140. package/dist/worker/console/inspect-split.js +18 -0
  141. package/dist/worker/console/interview/assessment.js +1 -1
  142. package/dist/worker/console/interview/session.js +1 -1
  143. package/dist/worker/console/native-directory-picker.js +13 -0
  144. package/dist/worker/console/operation-run-facts.js +19 -3
  145. package/dist/worker/console/operation-runner.js +45 -4
  146. package/dist/worker/console/operation-sse.js +1 -1
  147. package/dist/worker/console/operation-wait.js +1 -1
  148. package/dist/worker/console/operator-actions.js +534 -15
  149. package/dist/worker/console/operator-selection.js +6 -2
  150. package/dist/worker/console/operator-surface-health.js +2 -1
  151. package/dist/worker/console/operator-user-error.js +171 -2
  152. package/dist/worker/console/pi-plugins.catalog.json +73658 -0
  153. package/dist/worker/console/pi-plugins.js +238 -0
  154. package/dist/worker/console/pi-readiness.js +7 -6
  155. package/dist/worker/console/prd-intake-bridge.js +13 -0
  156. package/dist/worker/console/recovery-cta.js +4 -4
  157. package/dist/worker/console/recovery-error-copy.js +4 -4
  158. package/dist/worker/console/routes.js +1231 -10
  159. package/dist/worker/console/security.js +102 -13
  160. package/dist/worker/console/server.js +762 -159
  161. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BmOEx0gA.js → abnfDiagram-N423BO3Z-BZogYNl1.js} +1 -1
  162. package/dist/worker/console/static/assets/{arc-BGiVVe8b.js → arc-DcJTLe2v.js} +1 -1
  163. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-nDdu4rgJ.js → architectureDiagram-T3A2C74G-B39EQQ9n.js} +1 -1
  164. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bb5u0BWf.js → blockDiagram-VBNYF7ZC-CitCGV56.js} +1 -1
  165. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BlhC0j94.js → c4Diagram-5PPSVZJV-rvWuOHLG.js} +1 -1
  166. package/dist/worker/console/static/assets/channel-CXqdP5pW.js +1 -0
  167. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Ai8_qQXI.js → chunk-2GRJ4B5K-DGXplIJs.js} +1 -1
  168. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-B9gyCjqX.js → chunk-2Q5K7J3B-ur9OqjPn.js} +1 -1
  169. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bzbj3zGH.js → chunk-5RXB4S5H-D1KqU_Vi.js} +1 -1
  170. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BT415PvT.js → chunk-5VM5RSS4-BlVZrbtM.js} +1 -1
  171. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D_A5_5QL.js → chunk-6Q2QTUOP-BAzz3nQy.js} +1 -1
  172. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-srJkaP3f.js → chunk-GF5L2VYU-CP_nYuCV.js} +1 -1
  173. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-UYGvEP4l.js → chunk-JWPE2WC7-CWvKQ80X.js} +1 -1
  174. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-B8luBrrz.js → chunk-KBJHAD2P-CyUki8wp.js} +1 -1
  175. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DN7wXZSq.js → chunk-RYQCIY6F-5NYzNKfY.js} +1 -1
  176. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DXKyMuKS.js → chunk-XXDRQBXY-DHdUgjS-.js} +1 -1
  177. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9C3agF7.js +1 -0
  178. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9C3agF7.js +1 -0
  179. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-dqvoynXj.js → cose-bilkent-JH36ORCC-ANQ5g_t6.js} +1 -1
  180. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2--PcyL34A.js → cynefin-VYW2F7L2-CruT_4-0.js} +1 -1
  181. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-DvWs_hTY.js → cynefinDiagram-MW4NZA55-rbFo77ID.js} +1 -1
  182. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-DxeIxbyO.js → dagre-VZM6K2ZE-asstxBQs.js} +1 -1
  183. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DPCG61Of.js → diagram-7IWD3JNH-DzTyBZwI.js} +1 -1
  184. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmuU50-U.js → diagram-B4RE2ZJO-gw8ccH3B.js} +1 -1
  185. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B61XLD_v.js → diagram-LBJQPF4R-B8RpZzOf.js} +1 -1
  186. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BB7HTRRY.js → diagram-Q27KOJAE-B1zJkCS9.js} +1 -1
  187. package/dist/worker/console/static/assets/{diagram-UB23O5K3-DvkboAIp.js → diagram-UB23O5K3-B6JLWZmO.js} +1 -1
  188. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-BdJ_y1fL.js → ebnfDiagram-BXEA7PRR-q2iZP-Ps.js} +1 -1
  189. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-9bUBZTRi.js → erDiagram-JOGREHBK-B3dbbktQ.js} +1 -1
  190. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-Dw4L4RBa.js → flowDiagram-UKHOOZJN-C-zc6-kB.js} +1 -1
  191. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Jr82N_QP.js → ganttDiagram-PKOTCBZU-BSolnot9.js} +1 -1
  192. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DAz9wFLr.js → gitGraphDiagram-DS77QQ5N-Bo8jGxTk.js} +1 -1
  193. package/dist/worker/console/static/assets/index-CAZ2fC_X.css +1 -0
  194. package/dist/worker/console/static/assets/index-DhfjOafu.js +449 -0
  195. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CBB5Np7y.js → infoDiagram-6WML65LV-DQaZqJOH.js} +1 -1
  196. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-D8IOp94y.js → ishikawaDiagram-WSZJBQD7-DsdX1WnE.js} +1 -1
  197. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Dgd3AHGG.js → journeyDiagram-NVQOT4AX-CP5EYDZL.js} +1 -1
  198. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BmYOxLE9.js → kanban-definition-27J2QSJJ-DAm14Dr8.js} +1 -1
  199. package/dist/worker/console/static/assets/{linear-DfYTEF6J.js → linear-gZECoLc5.js} +1 -1
  200. package/dist/worker/console/static/assets/{mermaid.core-BjuFPRqa.js → mermaid.core-BRJNIM6p.js} +5 -5
  201. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CLyUViGd.js → mindmap-definition-FAOFIHXS-Cja3kLkR.js} +1 -1
  202. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BvX2Di4-.js → pegDiagram-VL7TDLO6-22ZGFisL.js} +1 -1
  203. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BFj0_OLv.js → pieDiagram-7S7Q4E2Y-BXin0Y1o.js} +1 -1
  204. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BIUrD_hx.js → quadrantDiagram-CIZ2JOQS-Cw6T69Yt.js} +1 -1
  205. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CHBB48fj.js → railroadDiagram-AXF67PYL-C1-gTieN.js} +1 -1
  206. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-sJrYw2Sf.js → requirementDiagram-LRYGKXZP--H5N2iI1.js} +1 -1
  207. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BzHH6fPR.js → sankeyDiagram-W5VNT64P-CgWAPeRz.js} +1 -1
  208. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-7QCnelCt.js → sequenceDiagram-SI44F4Z6-CrKqzGvt.js} +1 -1
  209. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-sDYSxn72.js → sizeCapture-X5ZJPWSS-BB3wG06K.js} +1 -1
  210. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-XpiUdwzm.js → stateDiagram-OKZ733FA-DjsGgdgY.js} +1 -1
  211. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Tp7V0U4q.js +1 -0
  212. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DvqgNPzD.js → swimlanes-SLNWSIFB-DYKEbvAR.js} +2 -2
  213. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DUZWZWi8.js +8 -0
  214. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-2TyOYNx0.js → timeline-definition-Z64GVDOM-eQOb5k9Y.js} +1 -1
  215. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-B-nM6wM2.js → vennDiagram-T6HMQDX7-B2-l9FIu.js} +1 -1
  216. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-B86wPdbr.js → wardleyDiagram-T6FBY63Y-BX2Cda3l.js} +1 -1
  217. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dr1C4AQz.js → xychartDiagram-ELKLHX3M-D9S892ph.js} +1 -1
  218. package/dist/worker/console/static/index.html +7 -2
  219. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  220. package/dist/worker/console/static-src/app/console-types.js +68 -4
  221. package/dist/worker/console/static-src/app/useConsoleShell.js +30 -12
  222. package/dist/worker/console/static-src/app/useOperatorActions.js +43 -7
  223. package/dist/worker/console/static-src/app/useRecoveryActions.js +2 -2
  224. package/dist/worker/console/static-src/app/useRecoveryConsole.js +45 -10
  225. package/dist/worker/console/static-src/app/useRunProgress.js +54 -0
  226. package/dist/worker/console/static-src/app/useTaskWizard.js +74 -2
  227. package/dist/worker/console/static-src/night/useNightBoard.js +8 -5
  228. package/dist/worker/console/static-src/operator-chat/cards/failure-category-advice.js +25 -0
  229. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +264 -13
  230. package/dist/worker/console/static-src/operator-chat/compaction-message.js +113 -0
  231. package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +22 -0
  232. package/dist/worker/console/static-src/operator-chat/details-dag-actions.js +122 -0
  233. package/dist/worker/console/static-src/operator-chat/input-history.js +78 -0
  234. package/dist/worker/console/static-src/operator-chat/mutation-gate.js +1 -1
  235. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +338 -0
  236. package/dist/worker/console/static-src/operator-chat/refs.js +3 -0
  237. package/dist/worker/console/static-src/operator-chat/runtime-selection-labels.js +27 -0
  238. package/dist/worker/console/static-src/operator-chat/runtime-snapshot-store.js +10 -0
  239. package/dist/worker/console/static-src/operator-chat/spatial-overlay.js +1 -2
  240. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +33 -1
  241. package/dist/worker/console/static-src/operator-chat/turn-submission.js +55 -0
  242. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +448 -109
  243. package/dist/worker/console/static-src/operator-chat/useChatStream.js +344 -27
  244. package/dist/worker/console/static-src/operator-chat/useChatThread.js +323 -11
  245. package/dist/worker/console/static-src/operator-chat/useComposer.js +45 -4
  246. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +97 -13
  247. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +57 -9
  248. package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +8 -2
  249. package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
  250. package/dist/worker/console/static-src/operator-chat/workspace-layout-mode.js +3 -3
  251. package/dist/worker/console/static-src/operator-chat/workspace-reorder.js +18 -0
  252. package/dist/worker/console/static-src/pages/tasks/run-id-resolution.js +79 -0
  253. package/dist/worker/console/static-src/pages/tasks/run-ownership-verify.js +23 -0
  254. package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +216 -0
  255. package/dist/worker/console/static-src/shell/console-update-reload.js +52 -0
  256. package/dist/worker/console/static-src/shell/useWorkspaces.js +415 -0
  257. package/dist/worker/console/static-src/shell/workspace-route.js +356 -0
  258. package/dist/worker/console/workspace-context.js +399 -0
  259. package/dist/worker/console/workspace-registry.js +487 -0
  260. package/dist/worker/continuation/worker-continuation.js +278 -0
  261. package/dist/worker/loop-agent/loop-agent-client.js +7 -3
  262. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  263. package/dist/worker/materialize/harness-task-lineage.js +5 -2
  264. package/dist/worker/observability/init-runtime-activity.js +26 -0
  265. package/dist/worker/observability/read-model.js +26 -0
  266. package/dist/worker/observe/health.js +1 -1
  267. package/dist/worker/observe/node-input.js +160 -3
  268. package/dist/worker/observe/node-process.js +377 -0
  269. package/dist/worker/observe/node-transparency.js +572 -0
  270. package/dist/worker/observe/routes.js +278 -3
  271. package/dist/worker/observe/server.js +4 -0
  272. package/dist/worker/observe/shell-handler-keys.js +34 -0
  273. package/dist/worker/observe/static/api.js +154 -4
  274. package/dist/worker/observe/static/app.js +18 -70
  275. package/dist/worker/observe/static/constants.js +26 -19
  276. package/dist/worker/observe/static/dag-context-reason-labels.d.ts +9 -0
  277. package/dist/worker/observe/static/dag-context-reason-labels.js +139 -0
  278. package/dist/worker/observe/static/dag-helpers.js +4 -2
  279. package/dist/worker/observe/static/dag-history-labels.js +5 -0
  280. package/dist/worker/observe/static/dag-inspector-humanize.d.ts +16 -0
  281. package/dist/worker/observe/static/dag-inspector-humanize.js +339 -0
  282. package/dist/worker/observe/static/dag-node-purpose.d.ts +6 -0
  283. package/dist/worker/observe/static/dag-node-purpose.js +208 -0
  284. package/dist/worker/observe/static/format.js +60 -0
  285. package/dist/worker/observe/static/index.html +10 -5
  286. package/dist/worker/observe/static/inspect-bootstrap.d.ts +8 -0
  287. package/dist/worker/observe/static/inspect-bootstrap.js +57 -0
  288. package/dist/worker/observe/static/inspect-workspace.js +374 -0
  289. package/dist/worker/observe/static/kpi.js +2 -2
  290. package/dist/worker/observe/static/markdown-render.js +20 -1
  291. package/dist/worker/observe/static/operator-chrome.css +168 -24
  292. package/dist/worker/observe/static/operator-chrome.d.ts +30 -5
  293. package/dist/worker/observe/static/operator-chrome.js +354 -101
  294. package/dist/worker/observe/static/prompt-restart-candidates.d.ts +18 -0
  295. package/dist/worker/observe/static/prompt-restart-candidates.js +38 -0
  296. package/dist/worker/observe/static/relations.js +7 -7
  297. package/dist/worker/observe/static/router.d.ts +57 -0
  298. package/dist/worker/observe/static/router.js +67 -1
  299. package/dist/worker/observe/static/run-processing.js +4 -2
  300. package/dist/worker/observe/static/shell-chrome.js +2 -2
  301. package/dist/worker/observe/static/state.d.ts +50 -0
  302. package/dist/worker/observe/static/state.js +191 -1
  303. package/dist/worker/observe/static/styles.css +1720 -86
  304. package/dist/worker/observe/static/views/dag-graph.js +5 -3
  305. package/dist/worker/observe/static/views/dag-inspector.js +2601 -188
  306. package/dist/worker/observe/static/views/dag.d.ts +13 -0
  307. package/dist/worker/observe/static/views/dag.js +39 -18
  308. package/dist/worker/observe/static/views/dags.js +10 -6
  309. package/dist/worker/observe/static/views/dashboard.js +18 -8
  310. package/dist/worker/observe/static/views/failures.js +5 -2
  311. package/dist/worker/observe/static/views/night.js +2 -2
  312. package/dist/worker/observe/static/views/pool.js +8 -2
  313. package/dist/worker/observe/static/views/run.js +15 -4
  314. package/dist/worker/observe/static/views/session-timeline.js +386 -25
  315. package/dist/worker/observe/static/views/task.js +63 -3
  316. package/dist/worker/outcomes/adapters.js +19 -0
  317. package/dist/worker/outcomes/types.js +1 -0
  318. package/dist/worker/pool/attempt-lease.js +97 -66
  319. package/dist/worker/pool/begin-attempt-with-lease.js +1 -0
  320. package/dist/worker/pool/reconcile.js +46 -1
  321. package/dist/worker/pool/run-store.js +2 -0
  322. package/dist/worker/pool/state-projection.js +2 -0
  323. package/dist/worker/task-spec/workflow-routing.js +8 -3
  324. package/dist/workflows/dag/artifact-bindings.js +149 -0
  325. package/dist/workflows/dag/artifact-revision-schema-registry.js +31 -0
  326. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +470 -31
  327. package/dist/workflows/dag/backend-test-markdown-workflow.js +189 -2
  328. package/dist/workflows/dag/backend-test-plan-protocol.js +210 -0
  329. package/dist/workflows/dag/backend-test-pytest-collection.js +168 -16
  330. package/dist/workflows/dag/backend-test-result-contract.js +5 -1
  331. package/dist/workflows/dag/backend-test-scenario-param.js +506 -73
  332. package/dist/workflows/dag/backend-test-scenario-partitions.js +135 -2
  333. package/dist/workflows/dag/backend-test-writer-completeness.js +131 -28
  334. package/dist/workflows/dag/budget-enforcement.js +10 -0
  335. package/dist/workflows/dag/context-receipt.js +305 -0
  336. package/dist/workflows/dag/context-transfer/context-bundle.js +423 -0
  337. package/dist/workflows/dag/context-transfer/operator-actions.js +61 -0
  338. package/dist/workflows/dag/context-transfer/renderers.js +93 -0
  339. package/dist/workflows/dag/contract-output-registry.js +15 -0
  340. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  341. package/dist/workflows/dag/convergence/controller.js +141 -0
  342. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  343. package/dist/workflows/dag/dynamic-runtime/loop-until.js +1 -1
  344. package/dist/workflows/dag/dynamic-runtime/map.js +17 -3
  345. package/dist/workflows/dag/failure-category.js +7 -116
  346. package/dist/workflows/dag/frontend-closeout.js +221 -0
  347. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  348. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  349. package/dist/workflows/dag/frontend-implementation-contract.js +1377 -141
  350. package/dist/workflows/dag/frontend-plan-render.js +26 -1
  351. package/dist/workflows/dag/frontend-prewrite-gate.js +376 -318
  352. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  353. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  354. package/dist/workflows/dag/frontend-recovery-controller.js +226 -0
  355. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  356. package/dist/workflows/dag/frontend-recovery-plan.js +21 -10
  357. package/dist/workflows/dag/frontend-recovery-run.js +166 -34
  358. package/dist/workflows/dag/frontend-repair.js +7 -424
  359. package/dist/workflows/dag/frontend-review-context.js +348 -20
  360. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  361. package/dist/workflows/dag/frontend-risk.js +15 -2
  362. package/dist/workflows/dag/frontend-shadow-dual-write.js +941 -0
  363. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  364. package/dist/workflows/dag/frontend-shape-facts.js +419 -0
  365. package/dist/workflows/dag/frontend-shape.js +435 -0
  366. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  367. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  368. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  369. package/dist/workflows/dag/frontend-test-case-checklist.js +32 -4
  370. package/dist/workflows/dag/frontend-test-case-generation-assessment.js +69 -0
  371. package/dist/workflows/dag/frontend-test-case-manifest.js +17 -5
  372. package/dist/workflows/dag/frontend-test-case-quality.js +11 -16
  373. package/dist/workflows/dag/frontend-test-environment-probe.js +230 -0
  374. package/dist/workflows/dag/frontend-test-html-report.js +3 -1
  375. package/dist/workflows/dag/frontend-test-l5-report.js +3 -1
  376. package/dist/workflows/dag/frontend-test-layout.js +159 -0
  377. package/dist/workflows/dag/frontend-test-markdown.js +61 -0
  378. package/dist/workflows/dag/frontend-test-result-contract.js +202 -42
  379. package/dist/workflows/dag/frontend-test-standard-scenarios.js +70 -0
  380. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  381. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  382. package/dist/workflows/dag/frontend-verification-trace.js +281 -29
  383. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  384. package/dist/workflows/dag/frontend-writer-admission.js +319 -0
  385. package/dist/workflows/dag/frontend-writer-rollback.js +32 -0
  386. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  387. package/dist/workflows/dag/init-hybrid.js +1771 -717
  388. package/dist/workflows/dag/interrupt-request.js +10 -3
  389. package/dist/workflows/dag/lifecycle.js +3 -3
  390. package/dist/workflows/dag/node-execution.js +1141 -32
  391. package/dist/workflows/dag/path-safety.js +1 -0
  392. package/dist/workflows/dag/prompt.js +158 -7
  393. package/dist/workflows/dag/recovery-lease.js +170 -0
  394. package/dist/workflows/dag/report.js +37 -1
  395. package/dist/workflows/dag/rerun-feedback.js +526 -0
  396. package/dist/workflows/dag/rerun-plan.js +790 -28
  397. package/dist/workflows/dag/rerun-run.js +700 -21
  398. package/dist/workflows/dag/rerun-task.js +311 -14
  399. package/dist/workflows/dag/retry-policy.js +336 -101
  400. package/dist/workflows/dag/runner.js +596 -121
  401. package/dist/workflows/dag/scheduler.js +133 -20
  402. package/dist/workflows/dag/skill-snapshot.js +17 -0
  403. package/dist/workflows/dag/structured-output-repair.js +712 -0
  404. package/dist/workflows/dag/types.js +600 -31
  405. package/dist/workflows/dag/validate.js +92 -32
  406. package/docs/README.md +2 -0
  407. package/docs/architecture/evolution.md +45 -0
  408. package/docs/architecture/runtime-boundaries.md +8 -7
  409. package/docs/architecture/worker-and-feature.md +1 -1
  410. package/docs/examples/README.md +5 -0
  411. package/docs/init-surface.manifest.json +36 -12
  412. package/docs/operations/README.md +1 -1
  413. package/docs/operations/local-development-environment.md +22 -5
  414. package/docs/skills/vetted-skill-registry.md +16 -0
  415. package/docs/templates/README.md +4 -2
  416. package/docs/templates/agent-dag-report.schema.json +8 -2
  417. package/docs/templates/agent-dag.schema.json +95 -1
  418. package/docs/templates/backend-test-dag.json +278 -244
  419. package/docs/templates/frontend-implementation-contract.schema.json +684 -24
  420. package/docs/templates/frontend-implementation-dag.json +89 -0
  421. package/docs/templates/frontend-test-case-checklist.md +2 -2
  422. package/docs/templates/frontend-test-dag.json +10 -12
  423. package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +1 -1
  424. package/docs/templates/init-managed-agents.md +13 -3
  425. package/docs/templates/product-line/task.yaml +1 -1
  426. package/docs/templates/spec-registry.schema.json +45 -0
  427. package/harness.json +2 -2
  428. package/package.json +19 -5
  429. package/scripts/next-info.mjs +356 -0
  430. package/scripts/next-publish-gate.mjs +238 -0
  431. package/scripts/release-source-binding.mjs +251 -0
  432. package/skills/analyze-product-requirements/SKILL.md +8 -5
  433. package/skills/analyze-product-requirements/references/acceptance-criteria.md +1 -1
  434. package/skills/analyze-product-requirements/references/clarification-and-knowledge.md +10 -6
  435. package/skills/analyze-product-requirements/references/example.md +50 -0
  436. package/skills/analyze-product-requirements/references/forward-test-cases.md +11 -7
  437. package/skills/analyze-product-requirements/references/kb-integration.md +5 -5
  438. package/skills/analyze-product-requirements/references/product-analysis-schema.md +8 -4
  439. package/skills/analyze-product-requirements/references/product-requirement-schema.md +2 -2
  440. package/skills/analyze-product-requirements/references/requirement-clarification-schema.md +1 -1
  441. package/skills/analyze-product-requirements/scripts/test-validators.mjs +11 -1
  442. package/skills/analyze-product-requirements/scripts/validate-product-analysis.mjs +20 -1
  443. package/skills/analyze-product-requirements/scripts/validate-requirement-clarification.mjs +9 -0
  444. package/skills/codebase-scout/SKILL.md +1 -1
  445. package/skills/fe-test-ui-scout/SKILL.md +65 -0
  446. package/skills/fe-test-ui-scout/references/ledger-schema.md +62 -0
  447. package/skills/fe-test-ui-scout/references/recon-protocol.md +54 -0
  448. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  449. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  450. package/skills/frontend-contract/SKILL.md +23 -0
  451. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  452. package/skills/frontend-design-review/SKILL.md +22 -41
  453. package/skills/frontend-plan/SKILL.md +26 -0
  454. package/skills/frontend-plan/references/decision-contract.md +37 -0
  455. package/skills/frontend-plan/references/design-decisions.md +17 -0
  456. package/skills/frontend-review/SKILL.md +20 -15
  457. package/skills/frontend-review/references/review-findings.md +6 -7
  458. package/skills/frontend-scout/SKILL.md +25 -0
  459. package/skills/frontend-scout/references/design-evidence.md +16 -0
  460. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  461. package/skills/frontend-verification/SKILL.md +1 -1
  462. package/skills/improve-codebase-architecture/SKILL.md +81 -0
  463. package/skills/improve-codebase-architecture/deepening.md +37 -0
  464. package/skills/improve-codebase-architecture/html-report.md +123 -0
  465. package/skills/improve-codebase-architecture/interface-design.md +44 -0
  466. package/skills/improve-codebase-architecture/language.md +53 -0
  467. package/skills/loop-agent/references/command-reference.md +32 -4
  468. package/skills/loop-agent/references/hybrid-dag.md +9 -2
  469. package/skills/playwright-cli/SKILL.md +23 -1
  470. package/skills/playwright-cli-case-generator/SKILL.md +50 -13
  471. package/dist/worker/console/operation-store.js +0 -169
  472. package/dist/worker/console/static/assets/channel-Tl-FkUqr.js +0 -1
  473. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BaehtRk4.js +0 -1
  474. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BaehtRk4.js +0 -1
  475. package/dist/worker/console/static/assets/index-B7Y-0g3J.css +0 -1
  476. package/dist/worker/console/static/assets/index-DkCrqaYg.js +0 -325
  477. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-eEhq2A8Y.js +0 -1
  478. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-la8AC7fo.js +0 -8
  479. package/dist/worker/console/static-src/operator-chat/activity-rail-presentation.js +0 -73
  480. package/dist/worker/console/static-src/operator-chat/useActivityRailTransition.js +0 -59
  481. package/skills/frontend-implementation/SKILL.md +0 -52
  482. package/skills/frontend-implementation/references/code-standards.md +0 -33
  483. package/skills/frontend-implementation/references/design-spec.md +0 -56
  484. package/skills/frontend-implementation/references/node-contracts.md +0 -31
  485. /package/dist/{worker → infrastructure}/console/repo-fingerprint.js +0 -0
@@ -1,8 +1,9 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
2
3
  import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
3
4
  import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
4
5
  import path from "node:path";
5
- import { writeDagNodeJsonArtifact, writeDagNodeTextArtifact, } from "../infrastructure/harness/artifact-store.js";
6
+ import { writeDagNodeJsonArtifact, writeDagNodeTextArtifact, writeDagRunJsonArtifact, } from "../infrastructure/harness/artifact-store.js";
6
7
  import { captureWorkspaceCheckpoint } from "../workflows/dag/workspace-checkpoint.js";
7
8
  import { truncateOutput } from "../shared/output-truncation.js";
8
9
  import { processTreeSpawnOptions, terminateProcessTree, } from "./process-tree.js";
@@ -14,31 +15,44 @@ import { buildRequirementCoverageGateShellCommand, expandShellPreset, buildVerdi
14
15
  import { materializeBackendTestAnalysisContract } from "../workflows/dag/backend-test-analysis-contract.js";
15
16
  import { extractBackendTestContractEnvelope } from "../workflows/dag/backend-test-contract-envelope.js";
16
17
  import { materializeFrontendImplementationContract } from "../workflows/dag/frontend-implementation-contract.js";
18
+ import { assertFrontendSourceBindingFresh, buildContractFromCommittedFacts, deterministicSha256, frontendImplementationContractSchema, serializeCompactDeterministicJson, sha256Hex, writeFrontendImplementationContractArtifact, buildFrontendVerifyCommandDirectory, } from "../workflows/dag/frontend-implementation-contract.js";
19
+ import { checkFrontendSourceFidelityLedger } from "../workflows/dag/frontend-source-fidelity-ledger.js";
17
20
  import { materializeFrontendTestResult, validateFrontendCaseEvidence, } from "../workflows/dag/frontend-test-result-contract.js";
21
+ import { copyFrontendTestStandardScenarios } from "../workflows/dag/frontend-test-standard-scenarios.js";
22
+ import { probeFrontendTestEnvironment } from "../workflows/dag/frontend-test-environment-probe.js";
18
23
  import { renderFrontendTestL5Report } from "../workflows/dag/frontend-test-l5-report.js";
19
24
  import { validateFrontendCaseChecklist } from "../workflows/dag/frontend-test-case-checklist.js";
25
+ import { assessFrontendCaseGeneration } from "../workflows/dag/frontend-test-case-generation-assessment.js";
20
26
  import { materializeFrontendTestCaseManifest } from "../workflows/dag/frontend-test-case-manifest.js";
21
27
  import { selectFrontendRerunCandidates } from "../workflows/dag/frontend-test-rerun-candidates.js";
22
28
  import { renderFrontendTestHtmlReport } from "../workflows/dag/frontend-test-html-report.js";
23
29
  import { formatFrontendVerificationTraceStdout, runFrontendVerificationTraceGate, } from "../workflows/dag/frontend-verification-trace.js";
24
- import { formatFrontendWorktreeDiffStdout, runFrontendWorktreeDiffGate, } from "../workflows/dag/frontend-worktree-diff.js";
25
- import { formatFrontendFailureAssessStdout, formatFrontendRepairContractStdout, runFrontendFailureAssessGate, runFrontendRepairContractGate, } from "../workflows/dag/frontend-repair.js";
26
- import { formatFrontendPrewriteGateStdout, runFrontendPrewriteGate, } from "../workflows/dag/frontend-prewrite-gate.js";
30
+ import { captureFrontendWorktreeBaseline, formatFrontendWorktreeDiffStdout, runFrontendWorktreeDiffGate, } from "../workflows/dag/frontend-worktree-diff.js";
31
+ import { readTypedEventStoreFromJsonl } from "../workflows/dag/frontend-typed-event-store.js";
32
+ import { classifyFrontendFailure, } from "../workflows/dag/frontend-repair.js";
33
+ import { evaluateFrontendDesignPolicy, } from "../workflows/dag/frontend-design-policy.js";
34
+ import { deriveFrontendWriterAdmissionShell, FRONTEND_WRITER_ADMISSION_RESULT_ARTIFACT, frontendWriterAdmissionResultV1Schema, } from "../workflows/dag/frontend-writer-admission.js";
35
+ import { deriveFrontendIntegrationFacts, buildFrontendTestHandoff, frontendCloseoutFactsSchema, renderFrontendCloseout, } from "../workflows/dag/frontend-closeout.js";
36
+ import { buildFrontendHumanDecisionEnvelope, evaluateHighAdmissionReceipt, routeVerificationConfig, } from "../workflows/dag/frontend-human-decision.js";
37
+ import { classifyFailureOwner, classifyIssueCategoryRestartPhase, classifyRestartPhase, } from "../workflows/dag/frontend-recovery-capsule.js";
38
+ import { pathMatchesPattern } from "../shared/git-progress.js";
27
39
  import { formatFrontendReviewContextStdout, runFrontendReviewContextGate, } from "../workflows/dag/frontend-review-context.js";
28
40
  import { materializeFrontendLintAssessment, materializeFrontendLintBaseline, } from "../workflows/dag/frontend-lint-baseline.js";
29
41
  import { formatTraceabilityGateStdout, materializeBackendTestCaseManifest, runBackendTestTraceabilityGate, } from "../workflows/dag/backend-test-case-manifest.js";
30
42
  import { materializeBackendTestExecutionContract } from "../workflows/dag/backend-test-execution-contract.js";
31
43
  import { resolveBackendTestLayout } from "../workflows/dag/backend-test-layout.js";
44
+ import { frontendTestLayoutFromSpec, } from "../workflows/dag/frontend-test-layout.js";
32
45
  import { backendTestGapDocSchema, ingestBackendTestGap, } from "../workflows/dag/backend-test-gap-fill.js";
33
- import { analyzeBackendTestCaseCoverage, analyzeBackendTestMarkdownPytestCorrespondence, materializeBackendTestCaseManifestFromFacts, } from "../workflows/dag/backend-test-case-coverage-analysis.js";
46
+ import { analyzeBackendTestCaseCoverage, analyzeBackendTestMarkdownPytestCorrespondence, classifyBackendTestCorrespondenceRepair, materializeBackendTestCaseManifestFromFacts, } from "../workflows/dag/backend-test-case-coverage-analysis.js";
34
47
  import { materializeBackendTestResultFromPytestHtml, materializeBackendTestResultFromRunDir, parsePytestHtmlReport, } from "../workflows/dag/backend-test-result-contract.js";
35
48
  import { collectBackendTestHumanCaseCatalog, collectBackendTestMappedPytestScripts, resolveBackendTestMappedPytestScripts, collectJacocoCoverage, hasBlockingBackendMarkdownSafetyFindings, hasBlockingBackendMarkdownModuleStemFindings, inspectBackendTestEnvironment, markdownFiles, requiredBackendMarkdownCaseAcIds, renderBackendTestFacts, renderBackendTestHtml, renderBackendTestL5Dashboard, redactBackendTestOutput, validateBackendMarkdownCases, validateBackendMarkdownTraceability, writeRunReport, } from "../workflows/dag/backend-test-markdown-workflow.js";
36
49
  import { applyDeterministicScenarioParamRepairs, assessBackendScenarioParamConsistency, classifyBackendTestFailureWithScenarioParam, readBackendScenarioParamFacts, renderBackendTestFailureAnalysis, writeBackendScenarioParamArtifacts, writeScenarioParamRepairAudit, } from "../workflows/dag/backend-test-scenario-param.js";
37
- import { assessBackendPytestCollection, assessMissingBackendPytestScripts, assessPriorityOnlyBackendPytestModules, assertBackendTestExecutionReadinessFresh, buildBackendPytestAssetInventory, buildBackendTestItemEligibility, materializeBackendTestExecutionReadiness, materializeEffectiveBackendPytestCollection, readBackendPytestCollectionFacts, readBackendTestExecutionReadiness, writeBackendPytestCollectionArtifacts, } from "../workflows/dag/backend-test-pytest-collection.js";
50
+ import { assessBackendPytestCollection, assessMissingBackendPytestScripts, assessPriorityOnlyBackendPytestModules, assertBackendTestExecutionReadinessFresh, buildBackendPytestAssetInventory, buildBackendTestItemEligibility, materializeBackendTestExecutionReadiness, materializeEffectiveBackendPytestCollection, readBackendPytestCollectionFacts, readBackendTestExecutionReadiness, summarizeBackendTestExclusions, writeBackendPytestCollectionArtifacts, } from "../workflows/dag/backend-test-pytest-collection.js";
38
51
  import { computeL5ReportMetrics } from "../workflows/dag/l5-report-metrics.js";
39
52
  import { buildBackendTestCanonicalResultFromInitialShellSnippet, materializeBackendTestClassification, } from "../workflows/dag/backend-test-classification-contract.js";
40
53
  import { backendTestSemanticReviewSchema, materializeBackendTestSemanticReview, } from "../workflows/dag/backend-test-semantic-review-contract.js";
41
54
  import { pathsChangedDuringRun, readGitStatusPorcelain, snapshotGitStatusPorcelain, validateShellWriteGuard, } from "./shell-write-guard.js";
55
+ import { captureWorkspaceWriteSnapshot, diffWorkspaceWriteSnapshots, } from "./workspace-write-snapshot.js";
42
56
  import { parseAndValidateFinalWriteSetApproval, } from "../workflows/dag/node-execution.js";
43
57
  import { buildShellProcessEnv } from "./shell-verification.js";
44
58
  import { readRunState } from "../workflows/dag/run-store.js";
@@ -46,6 +60,7 @@ import { readProjectGovernanceContext } from "../workflows/dag/project-governanc
46
60
  import { assertMavenPlanFresh, MavenPlanStaleError, } from "../verification/maven/index.js";
47
61
  async function runBackendScenarioParamPreflight(input) {
48
62
  const outputs = [];
63
+ const allowRepair = input.allowRepair !== false;
49
64
  const initial = await assessBackendScenarioParamConsistency({
50
65
  workspaceRoot: input.workspaceRoot,
51
66
  phase: "initial",
@@ -61,7 +76,7 @@ async function runBackendScenarioParamPreflight(input) {
61
76
  outputs.push(`scenarioParamInitial=${initialArtifacts.reportPath}`);
62
77
  let finalFacts;
63
78
  let finalMarkdown;
64
- if (initial.facts.repairEligible) {
79
+ if (allowRepair && initial.facts.repairEligible) {
65
80
  const repair = await applyDeterministicScenarioParamRepairs({
66
81
  workspaceRoot: input.workspaceRoot,
67
82
  facts: initial.facts,
@@ -122,6 +137,39 @@ function shouldReuseSuccessfulShellCommands(shell) {
122
137
  const DEFAULT_SHELL_TIMEOUT_MS = 300_000;
123
138
  const SUMMARY_STDOUT_MAX = 4_000;
124
139
  const SUMMARY_STDERR_MAX = 2_000;
140
+ const TEST_TIMEOUT_CLASSIFY_MAX_CHARS = 8_000;
141
+ const TEST_TIMEOUT_MARKERS = [
142
+ /Test timed out in \d+ms/i,
143
+ /Timeout of \d+ms exceeded/i,
144
+ ];
145
+ const DETERMINISTIC_NON_TIMEOUT_FAILURE_MARKERS = [
146
+ /AssertionError/i,
147
+ /expected:?\s/i,
148
+ /received:?\s/i,
149
+ /Snapshot /i,
150
+ /toMatchSnapshot/i,
151
+ /SyntaxError/i,
152
+ /TS\d{4}/,
153
+ /error TS/i,
154
+ /eslint/i,
155
+ /compile error/i,
156
+ /Failed to compile/i,
157
+ ];
158
+ function isIdentifiedTestCommand(command) {
159
+ return /(?:^|[\s"'`])(?:npx\s+)?vitest(?:\s|$)|(?:^|[\s"'`])npm(?:\.cmd)?\s+test(?:\s|$)|(?:^|[\s"'`])pnpm(?:\.cmd)?\s+test(?:\s|$)|(?:^|[\s"'`])yarn(?:\.cmd)?\s+test(?:\s|$)/i.test(command);
160
+ }
161
+ function classifyShellCommandFailure(input) {
162
+ if (input.processCategory !== "nonzero-exit")
163
+ return input.processCategory;
164
+ if (!isIdentifiedTestCommand(input.command))
165
+ return "nonzero-exit";
166
+ const sample = `${input.stdout}\n${input.stderr}`.slice(0, TEST_TIMEOUT_CLASSIFY_MAX_CHARS);
167
+ const hasTimeoutMarker = TEST_TIMEOUT_MARKERS.some((marker) => marker.test(sample));
168
+ if (!hasTimeoutMarker)
169
+ return "nonzero-exit";
170
+ const mixedDeterministicFailure = DETERMINISTIC_NON_TIMEOUT_FAILURE_MARKERS.some((marker) => marker.test(sample));
171
+ return mixedDeterministicFailure ? "nonzero-exit" : "test-timeout";
172
+ }
125
173
  const NODE_STDOUT_MAX = 12_000;
126
174
  const NODE_STDERR_MAX = 8_000;
127
175
  const MAX_BUFFERED_OUTPUT_BYTES = 64 * 1024;
@@ -328,16 +376,21 @@ export async function executeShellCommand(input) {
328
376
  });
329
377
  });
330
378
  child.on("close", (code) => {
331
- let failureCategory = "nonzero-exit";
379
+ let processCategory = "nonzero-exit";
332
380
  if (timedOut) {
333
- failureCategory = "timeout";
381
+ processCategory = "timeout";
334
382
  }
335
383
  else if (code === 0) {
336
- failureCategory = "success";
384
+ processCategory = "success";
337
385
  }
338
386
  finish({
339
387
  exitCode: code,
340
- failureCategory,
388
+ failureCategory: classifyShellCommandFailure({
389
+ command: input.command,
390
+ processCategory,
391
+ stdout: formatBoundedOutput(stdout),
392
+ stderr: formatBoundedOutput(stderr),
393
+ }),
341
394
  ok: code === 0 && !timedOut,
342
395
  });
343
396
  });
@@ -499,13 +552,22 @@ async function executeBackendTestPipeline(input, meta) {
499
552
  const started = Date.now();
500
553
  // Plan A: prefer the frozen layout carried by the compiled spec; fall back
501
554
  // to the historical default for hand-written legacy DAGs.
502
- const backendLayout = resolveBackendTestLayout(meta.spec.backendTestLayout
555
+ const baseBackendLayout = resolveBackendTestLayout(meta.spec.backendTestLayout
503
556
  ? {
504
557
  testRoot: meta.spec.backendTestLayout.testRoot,
505
558
  markdownRel: meta.spec.backendTestLayout.markdownRel,
506
559
  scriptRel: meta.spec.backendTestLayout.scriptRel,
507
560
  }
508
561
  : undefined);
562
+ const markdownPlanArtifact = path.join(meta.runDir, "generate-backend-md-plan-pi", "plan.md");
563
+ const backendLayout = existsSync(markdownPlanArtifact)
564
+ ? {
565
+ ...baseBackendLayout,
566
+ readmePath: path
567
+ .relative(input.cwd, markdownPlanArtifact)
568
+ .replaceAll(path.sep, "/"),
569
+ }
570
+ : baseBackendLayout;
509
571
  try {
510
572
  if (!pipeline)
511
573
  throw new Error("missing backend-test pipeline id");
@@ -705,7 +767,7 @@ async function executeBackendTestPipeline(input, meta) {
705
767
  // coverage findings stay advisory, but a declared filter axis missing
706
768
  // an each-value/omitted slot or its complement slot must block pytest
707
769
  // generation until the Markdown declares the slot.
708
- const partitionBlocking = coverage.facts.findings.filter((finding) => /^(?:MISSING_PARTITION|MISSING_PARTITION_SLOT|MISSING_COMPLEMENT_SLOT|MISSING_PARTITION_TABLE)/.test(finding));
770
+ const partitionBlocking = coverage.facts.findings.filter((finding) => /^(?:MISSING_PARTITION|MISSING_PARTITION_SLOT|MISSING_COMPLEMENT_SLOT|MISSING_PARTITION_TABLE|INVALID_PARTITION_DOMAIN|NO_FINITE_DOMAIN|PARTITION_SOURCE_MISMATCH)/.test(finding));
709
771
  if (partitionBlocking.length > 0) {
710
772
  return {
711
773
  ok: false,
@@ -820,26 +882,49 @@ async function executeBackendTestPipeline(input, meta) {
820
882
  const correspondenceFactsPath = path.join(contractsDir, "backend-test-markdown-pytest-correspondence-initial.json");
821
883
  await writeFile(correspondenceFactsPath, JSON.stringify(correspondence.facts, null, 2), "utf8");
822
884
  outputs.push(`initialCorrespondence=${correspondenceReportPath}`, `initialCorrespondenceFacts=${correspondenceFactsPath}`);
823
- if (correspondence.facts.status === "FAIL" && facts.status === "PASS") {
824
- const correspondenceRepairPaths = Array.from(new Set(correspondence.facts.entries
825
- .filter((entry) => entry.status !== "EXACT_1_TO_1")
826
- .flatMap((entry) => [entry.expectedScript, ...entry.actualScripts])
827
- .filter((candidate) => candidate.startsWith("testcase/") && candidate.endsWith(".py")))).sort();
828
- if (correspondenceRepairPaths.length > 0) {
829
- facts.status = "REPAIRABLE";
830
- facts.repairEligible = true;
831
- facts.repairPaths = Array.from(new Set([...facts.repairPaths, ...correspondenceRepairPaths])).sort();
885
+ if (correspondence.facts.status === "FAIL") {
886
+ const repair = classifyBackendTestCorrespondenceRepair(correspondence.facts, backendLayout);
887
+ if (repair.markdownBlockingEntries.length > 0) {
888
+ facts.status = "BLOCKED";
889
+ facts.repairEligible = false;
890
+ facts.repairPaths = [];
832
891
  facts.findings.push({
833
- kind: "markdown-pytest-correspondence",
892
+ kind: "markdown-correspondence-contract",
834
893
  classification: "test-asset-defect",
835
- repairability: "repairable",
836
- detail: correspondence.facts.entries
837
- .filter((entry) => entry.status !== "EXACT_1_TO_1")
838
- .flatMap((entry) => entry.findings)
894
+ repairability: "blocked",
895
+ detail: repair.markdownBlockingEntries
896
+ .map((entry) => `${entry.caseId ?? "unknown Case"}: ${entry.reasonCodes.join(", ")}`)
839
897
  .join("; ")
840
- .slice(0, 12_000) || "Markdown-to-pytest correspondence is incomplete",
898
+ .slice(0, 12_000),
841
899
  });
842
900
  }
901
+ else if (repair.pytestRepairPaths.length > 0 &&
902
+ (facts.status === "PASS" || facts.status === "REPAIRABLE")) {
903
+ facts.status = "REPAIRABLE";
904
+ facts.repairEligible = true;
905
+ facts.repairPaths = Array.from(new Set([...facts.repairPaths, ...repair.pytestRepairPaths])).sort();
906
+ const repairEntries = correspondence.facts.entries.filter((entry) => repair.pytestRepairEntries.some((candidate) => candidate.caseId === entry.caseId));
907
+ for (const entry of repairEntries.slice(0, 40)) {
908
+ const classified = repair.pytestRepairEntries.find((candidate) => candidate.caseId === entry.caseId);
909
+ facts.findings.push({
910
+ kind: "markdown-pytest-correspondence",
911
+ classification: "test-asset-defect",
912
+ repairability: "repairable",
913
+ detail: entry.findings.join("; ").slice(0, 2_000) || "Markdown-to-pytest correspondence is incomplete",
914
+ ...(entry.caseId ? { caseId: entry.caseId } : {}),
915
+ reasonCodes: classified?.reasonCodes ?? [],
916
+ repairPaths: classified?.paths ?? [],
917
+ payloadExpectedPaths: Array.from(new Set([
918
+ ...entry.payloadAssessment.requiredPaths,
919
+ ...entry.payloadAssessment.allowedPaths,
920
+ ])).sort(),
921
+ payloadObservedPaths: entry.payloadAssessment.observedPaths,
922
+ payloadMissingPaths: entry.payloadAssessment.missingPaths,
923
+ payloadUnexpectedPaths: entry.payloadAssessment.unexpectedPaths,
924
+ payloadEnumMismatches: entry.payloadAssessment.enumMismatches,
925
+ });
926
+ }
927
+ }
843
928
  }
844
929
  }
845
930
  catch (error) {
@@ -862,6 +947,19 @@ async function executeBackendTestPipeline(input, meta) {
862
947
  collectedItemCount: facts.collectedItemCount,
863
948
  missingMappedScripts: facts.missingMappedScripts,
864
949
  repairPaths: facts.repairPaths,
950
+ repairFindings: facts.findings.map((finding) => ({
951
+ kind: finding.kind,
952
+ repairability: finding.repairability,
953
+ detail: finding.detail,
954
+ ...(finding.caseId ? { caseId: finding.caseId } : {}),
955
+ ...(finding.reasonCodes ? { reasonCodes: finding.reasonCodes } : {}),
956
+ ...(finding.repairPaths ? { repairPaths: finding.repairPaths } : {}),
957
+ ...(finding.payloadExpectedPaths ? { payloadExpectedPaths: finding.payloadExpectedPaths } : {}),
958
+ ...(finding.payloadObservedPaths ? { payloadObservedPaths: finding.payloadObservedPaths } : {}),
959
+ ...(finding.payloadMissingPaths ? { payloadMissingPaths: finding.payloadMissingPaths } : {}),
960
+ ...(finding.payloadUnexpectedPaths ? { payloadUnexpectedPaths: finding.payloadUnexpectedPaths } : {}),
961
+ ...(finding.payloadEnumMismatches ? { payloadEnumMismatches: finding.payloadEnumMismatches } : {}),
962
+ })),
865
963
  factsPath: "contracts/backend-test-pytest-collection-initial.json",
866
964
  }),
867
965
  stderr: "",
@@ -875,14 +973,16 @@ async function executeBackendTestPipeline(input, meta) {
875
973
  effective = await materializeEffectiveBackendPytestCollection({
876
974
  workspaceRoot: input.cwd,
877
975
  initial,
976
+ layout: backendLayout,
878
977
  });
879
978
  }
880
979
  else if (initial.status === "REPAIRABLE") {
881
- const mappedScripts = await collectBackendTestMappedPytestScripts(input.cwd);
980
+ const mappedScripts = await collectBackendTestMappedPytestScripts(input.cwd, backendLayout);
882
981
  const scenario = await runBackendScenarioParamPreflight({
883
982
  workspaceRoot: input.cwd,
884
983
  runDir: meta.runDir,
885
984
  layout: backendLayout,
985
+ allowRepair: false,
886
986
  strictScenarioParamGate: Boolean((meta.spec.globalConstraints ?? []).some((item) => /strictScenarioParamGate\s*=\s*true/i.test(item))),
887
987
  });
888
988
  outputs.push(...scenario.outputs);
@@ -934,6 +1034,7 @@ async function executeBackendTestPipeline(input, meta) {
934
1034
  workspaceRoot: input.cwd,
935
1035
  initial,
936
1036
  final: finalFacts,
1037
+ layout: backendLayout,
937
1038
  });
938
1039
  }
939
1040
  else {
@@ -959,6 +1060,7 @@ async function executeBackendTestPipeline(input, meta) {
959
1060
  })
960
1061
  : { eligibleItemIds: effective.collectedItemIds, excludedItems: [] };
961
1062
  const eligibilityInputHashes = Object.fromEntries((correspondence?.facts.inputFiles ?? []).map((item) => [item.path, item.sha256]));
1063
+ const exclusionSummary = summarizeBackendTestExclusions(eligibility.excludedItems);
962
1064
  const eligibilityFactsPath = path.join(meta.runDir, "contracts", "backend-test-execution-eligibility.json");
963
1065
  await mkdir(path.dirname(eligibilityFactsPath), { recursive: true });
964
1066
  await writeFile(eligibilityFactsPath, `${JSON.stringify({
@@ -969,6 +1071,9 @@ async function executeBackendTestPipeline(input, meta) {
969
1071
  excludedItemCount: eligibility.excludedItems.length,
970
1072
  eligibleItemIds: eligibility.eligibleItemIds,
971
1073
  excludedItems: eligibility.excludedItems,
1074
+ exclusionSummary,
1075
+ pytestSpawned: false,
1076
+ businessTestBodyExecutedCount: 0,
972
1077
  inputHashes: eligibilityInputHashes,
973
1078
  }, null, 2)}\n`, "utf8");
974
1079
  const eligibilityReportPath = await writeRunReport(meta.runDir, "backend-test-execution-eligibility.md", [
@@ -981,6 +1086,10 @@ async function executeBackendTestPipeline(input, meta) {
981
1086
  `- Collected items: ${effective.collectedItemIds.length}`,
982
1087
  `- Eligible items: ${eligibility.eligibleItemIds.length}`,
983
1088
  `- Excluded items: ${eligibility.excludedItems.length}`,
1089
+ `- Excluded Cases: ${exclusionSummary.excludedCaseCount}`,
1090
+ `- Exclusion categories: ${Object.entries(exclusionSummary.excludedByReason).map(([category, count]) => `${category}=${count}`).join("; ") || "none"}`,
1091
+ "- pytest spawned: false",
1092
+ "- Business test bodies executed: 0",
984
1093
  "",
985
1094
  "## Excluded Items",
986
1095
  "",
@@ -996,6 +1105,7 @@ async function executeBackendTestPipeline(input, meta) {
996
1105
  scenarioParamRepairAttempt: scenarioFacts.repairAttempt,
997
1106
  eligibility,
998
1107
  eligibilityInputHashes,
1108
+ layout: backendLayout,
999
1109
  });
1000
1110
  return {
1001
1111
  ok: true,
@@ -1008,6 +1118,9 @@ async function executeBackendTestPipeline(input, meta) {
1008
1118
  executionReadinessStatus: readiness.status,
1009
1119
  eligibleItemCount: readiness.eligibleItemIds.length,
1010
1120
  excludedItemCount: readiness.excludedItems.length,
1121
+ exclusionSummary: readiness.exclusionSummary,
1122
+ pytestSpawned: readiness.pytestSpawned,
1123
+ businessTestBodyExecutedCount: readiness.businessTestBodyExecutedCount,
1011
1124
  factsPath: "contracts/backend-test-pytest-collection-effective.json",
1012
1125
  readinessPath: "contracts/backend-test-execution-readiness.json",
1013
1126
  reportPath: artifacts.reportPath,
@@ -1019,7 +1132,7 @@ async function executeBackendTestPipeline(input, meta) {
1019
1132
  else if (pipeline === "markdown-traceability") {
1020
1133
  let report;
1021
1134
  try {
1022
- report = await validateBackendMarkdownTraceability(input.cwd);
1135
+ report = await validateBackendMarkdownTraceability(input.cwd, backendLayout);
1023
1136
  }
1024
1137
  catch (error) {
1025
1138
  report = `# Backend Test Traceability\n\n## Status\n\nFAIL\n\n## Findings\n\n- Traceability validation could not complete: ${error instanceof Error ? error.message : String(error)}\n`;
@@ -1104,7 +1217,7 @@ async function executeBackendTestPipeline(input, meta) {
1104
1217
  }
1105
1218
  else if (pipeline === "markdown-execute-html") {
1106
1219
  const executionReadiness = await readBackendTestExecutionReadiness(path.join(meta.runDir, "contracts", "backend-test-execution-readiness.json"));
1107
- await assertBackendTestExecutionReadinessFresh(input.cwd, executionReadiness);
1220
+ await assertBackendTestExecutionReadinessFresh(input.cwd, executionReadiness, backendLayout);
1108
1221
  const mappedScripts = await collectBackendTestMappedPytestScripts(input.cwd, backendLayout);
1109
1222
  let eligibleItemIds = executionReadiness.eligibleItemIds;
1110
1223
  // Plan D gap-fill executeScope=affected: when a gap plan exists in
@@ -1130,7 +1243,33 @@ async function executeBackendTestPipeline(input, meta) {
1130
1243
  const pytestTargetsRelative = "reports/backend-test-pytest-targets.txt";
1131
1244
  const pytestTargetsAbsolute = path.join(meta.runDir, pytestTargetsRelative);
1132
1245
  await writeFile(pytestTargetsAbsolute, `${eligibleItemIds.join("\n")}\n`, "utf8");
1133
- const pytestTargetsArg = `@\"\${HARNESS_DAG_RUN_DIR}/${pytestTargetsRelative}\"`;
1246
+ const pytestLauncherRelative = "reports/backend-test-pytest-launcher.py";
1247
+ const pytestLauncherAbsolute = path.join(meta.runDir, pytestLauncherRelative);
1248
+ await writeFile(pytestLauncherAbsolute, [
1249
+ "import os",
1250
+ "import pathlib",
1251
+ "import sys",
1252
+ "",
1253
+ "sys.path[0] = os.getcwd()",
1254
+ "import pytest",
1255
+ "",
1256
+ "if len(sys.argv) != 3:",
1257
+ " print('usage: backend-test-pytest-launcher.py <targets-file> <html-file>', file=sys.stderr)",
1258
+ " raise SystemExit(4)",
1259
+ "targets_path = pathlib.Path(sys.argv[1])",
1260
+ "html_path = pathlib.Path(sys.argv[2])",
1261
+ "try:",
1262
+ " targets = targets_path.read_text(encoding='utf-8').splitlines()",
1263
+ "except (OSError, UnicodeError) as error:",
1264
+ " print(f'backend-test targets unreadable: {error}', file=sys.stderr)",
1265
+ " raise SystemExit(4)",
1266
+ "if not targets or any(not target or target != target.strip() for target in targets):",
1267
+ " print('backend-test targets must contain non-empty exact pytest node IDs', file=sys.stderr)",
1268
+ " raise SystemExit(4)",
1269
+ "pytest_args = [*targets, '-v', '-p', 'no:cacheprovider', f'--html={html_path}', '--self-contained-html']",
1270
+ "raise SystemExit(pytest.main(pytest_args))",
1271
+ "",
1272
+ ].join("\n"), "utf8");
1134
1273
  // Split into short bash -c commands (aligned with markdown-environment).
1135
1274
  // A single ultra-long compound command has been observed on Windows to
1136
1275
  // exit 0xC0000142 (STATUS_DLL_INIT_FAILED) in ~40ms with empty stdout/
@@ -1207,10 +1346,11 @@ async function executeBackendTestPipeline(input, meta) {
1207
1346
  'PYTHON_BIN="$(command -v python || command -v python3 || true)"',
1208
1347
  'if [ -z "${PYTHON_BIN}" ]; then echo "python/python3 is required for backend-test execution" | tee -a "${DIAG_FILE}" >&2; exit 127; fi',
1209
1348
  'echo "STEP=pytest-run"',
1210
- `echo "- pytestCommand: python -m pytest <${eligibleItemIds.length} eligibility-authorized-items> -v -p no:cacheprovider --html=reports/backend-test.html --self-contained-html" >> "\${DIAG_FILE}"`,
1349
+ `echo "- pytestCommand: controller launcher -> pytest.main(<${eligibleItemIds.length} eligibility-authorized-items>, -v, -p no:cacheprovider, --html=reports/backend-test.html, --self-contained-html)" >> "\${DIAG_FILE}"`,
1211
1350
  `echo "- eligibleItemCount: ${eligibleItemIds.length}" >> "\${DIAG_FILE}"`,
1212
1351
  `echo "- excludedItemCount: ${executionReadiness.excludedItems.length}" >> "\${DIAG_FILE}"`,
1213
- `PYTHONUTF8=1 PYTHONIOENCODING=utf-8 PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 "\${PYTHON_BIN}" -m pytest ${pytestTargetsArg} -v -p no:cacheprovider --html="\${HARNESS_DAG_RUN_DIR}/reports/backend-test.html" --self-contained-html`,
1352
+ 'rm -f "${HARNESS_DAG_RUN_DIR}/reports/backend-test.html" "${HARNESS_DAG_RUN_DIR}/reports/backend-test-pytest-native.html"',
1353
+ `PYTHONUTF8=1 PYTHONIOENCODING=utf-8 PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 "\${PYTHON_BIN}" "\${HARNESS_DAG_RUN_DIR}/${pytestLauncherRelative}" "\${HARNESS_DAG_RUN_DIR}/${pytestTargetsRelative}" "\${HARNESS_DAG_RUN_DIR}/reports/backend-test.html"`,
1214
1354
  "STATUS=$?",
1215
1355
  'printf "%s" "${STATUS}" > "${HARNESS_DAG_RUN_DIR}/reports/backend-test-pytest-exit.txt"',
1216
1356
  'echo "- pytestExitCode: ${STATUS}" >> "${DIAG_FILE}"',
@@ -1679,6 +1819,33 @@ async function executeBackendTestPipeline(input, meta) {
1679
1819
  }
1680
1820
  }
1681
1821
  async function executeBackendTestPipelineWithWriteGuard(input, meta) {
1822
+ if (meta.spec.backendTestWorkspaceControl === "filesystem-only") {
1823
+ const paths = input.task.writeSet ?? input.task.allowedPaths;
1824
+ let beforeSnapshot;
1825
+ try {
1826
+ beforeSnapshot = await captureWorkspaceWriteSnapshot({ rootCwd: input.cwd, paths });
1827
+ }
1828
+ catch (error) {
1829
+ return { ok: false, stdout: "", stderr: `workspace filesystem baseline unavailable: ${error instanceof Error ? error.message : String(error)}`, failureCategory: "write-guard", durationMs: 0 };
1830
+ }
1831
+ const result = await executeBackendTestPipeline(input, meta);
1832
+ try {
1833
+ const afterSnapshot = await captureWorkspaceWriteSnapshot({ rootCwd: input.cwd, paths });
1834
+ const guard = validateShellWriteGuard({
1835
+ changedPaths: diffWorkspaceWriteSnapshots(beforeSnapshot, afterSnapshot),
1836
+ writePolicy: input.task.writePolicy,
1837
+ writeSet: input.task.writeSet,
1838
+ allowedPaths: input.task.allowedPaths,
1839
+ forbiddenPaths: input.task.forbiddenPaths,
1840
+ });
1841
+ if (!guard.ok)
1842
+ return { ...result, ok: false, stderr: [result.stderr, `filesystem write guard failed: ${guard.violations.join(", ")}`].filter(Boolean).join("\n\n"), failureCategory: "write-guard" };
1843
+ return result;
1844
+ }
1845
+ catch (error) {
1846
+ return { ...result, ok: false, stderr: [result.stderr, `filesystem write guard failed: ${error instanceof Error ? error.message : String(error)}`].filter(Boolean).join("\n\n"), failureCategory: "write-guard" };
1847
+ }
1848
+ }
1682
1849
  let beforeStatus;
1683
1850
  try {
1684
1851
  beforeStatus = await readGitStatusPorcelain(input.cwd);
@@ -1741,6 +1908,44 @@ async function executePipelineCommands(input, meta, overrideCommands) {
1741
1908
  }
1742
1909
  return results;
1743
1910
  }
1911
+ /** A+B (AC-008): derive unresolved verification entrypoints from committed plan
1912
+ * facts. A verification target is unresolved when its commandId does not
1913
+ * match any frozen command directory entry derived from the verify shell
1914
+ * evidence bundle. Returns `{ ref, digest }` entries; a missing/unreadable
1915
+ * plan ledger fails closed to [] so the router restarts the contract instead
1916
+ * of inventing refs. */
1917
+ async function deriveUnresolvedVerificationEntrypointRefs(runDir, frozenCommandIds) {
1918
+ try {
1919
+ const { restorePlanPatchFromCommittedFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
1920
+ const records = await readTypedEventStoreFromJsonl(path.join(runDir, "frontend-plan-pi", "plan-typed-facts.jsonl"));
1921
+ const patch = restorePlanPatchFromCommittedFacts(records);
1922
+ const targets = patch
1923
+ ?.verificationTargets;
1924
+ if (!Array.isArray(targets))
1925
+ return [];
1926
+ const frozen = new Set(frozenCommandIds.filter(Boolean));
1927
+ const refs = [];
1928
+ for (const item of targets) {
1929
+ const target = item;
1930
+ // v2 plan facts carry commandId as the stable directory key.
1931
+ const commandId = typeof target.commandId === "string" ? target.commandId : "";
1932
+ if (commandId && frozen.has(commandId)) {
1933
+ continue;
1934
+ }
1935
+ const file = typeof target.file === "string" ? target.file : "";
1936
+ const symbol = typeof target.symbol === "string" ? target.symbol : "";
1937
+ const id = typeof target.id === "string" ? target.id : "";
1938
+ const ref = file || symbol || id;
1939
+ if (!ref)
1940
+ continue;
1941
+ refs.push({ ref, digest: sha256Hex(ref) });
1942
+ }
1943
+ return refs;
1944
+ }
1945
+ catch {
1946
+ return [];
1947
+ }
1948
+ }
1744
1949
  async function executeFrontendVerificationBundle(input, meta) {
1745
1950
  const started = Date.now();
1746
1951
  const shell = input.task.shell;
@@ -1895,75 +2100,540 @@ async function executeFrontendVerificationBundle(input, meta) {
1895
2100
  catch (error) {
1896
2101
  traceError = error instanceof Error ? error : new Error(String(error));
1897
2102
  }
1898
- if (bundle.mode === "repair") {
1899
- if (firstFailure || lintSyntheticFailure || traceError) {
1900
- return {
1901
- ok: false,
1902
- stdout: summarizeCommandResults(results).stdout,
1903
- stderr: firstFailure?.stderr ||
1904
- lintSyntheticFailure?.stderr ||
1905
- traceError?.message ||
1906
- "frontend reverify failed",
1907
- failureCategory: firstFailure?.failureCategory ??
1908
- lintSyntheticFailure?.failureCategory ??
1909
- "invalid-output",
1910
- durationMs: Date.now() - started,
1911
- ...{ commandResults },
1912
- };
2103
+ const verifyFailed = firstFailure !== undefined || lintSyntheticFailure !== undefined || traceError !== undefined;
2104
+ if (verifyFailed) {
2105
+ // M8: verify failure is TERMINAL. There is no same-run repair branch and
2106
+ // no frontend-repair-assessment.json; we only materialize failure
2107
+ // ownership facts (frontend-repair classification + recovery capsule
2108
+ // ownership) for the operation controller / recovery run.
2109
+ const failedNodeId = input.task.id;
2110
+ const failureCategory = firstFailure?.failureCategory ??
2111
+ lintSyntheticFailure?.failureCategory ??
2112
+ (traceError ? "invalid-output" : undefined) ??
2113
+ "invalid-output";
2114
+ const failureClass = classifyFrontendFailure({
2115
+ nodeId: failedNodeId,
2116
+ failureCategory,
2117
+ stdout: firstFailure?.stdout,
2118
+ stderr: firstFailure?.stderr ?? traceError?.message,
2119
+ });
2120
+ // A verify failure means the writer's candidate failed verification, so
2121
+ // the recovery ownership maps to the implement phase (frontend-recovery
2122
+ // capsule classification, fail-closed to implement-pi).
2123
+ const classifiedOwner = classifyFailureOwner({
2124
+ failureSource: "frontend-verify-shell",
2125
+ nodeId: failedNodeId,
2126
+ rawFailureCategory: failureCategory,
2127
+ });
2128
+ const failureOwner = classifiedOwner === "unknown" ? "implement-pi" : classifiedOwner;
2129
+ const restartPhase = classifyRestartPhase(failureOwner);
2130
+ // A+B (AC-008): verification-config routing. Produce structured
2131
+ // unresolved entrypoint refs from committed plan facts and the frozen
2132
+ // command labels; a non-empty unresolved set routes to
2133
+ // verification-config-decision and materializes the frozen
2134
+ // verification-config envelope. An empty/untyped signal fails closed to
2135
+ // contract-restart. The decision is recorded so the recovery controller
2136
+ // never re-classifies the same signal twice.
2137
+ let verificationConfigRoute;
2138
+ if (failureOwner === "verification-config") {
2139
+ const verifyDirectory = buildFrontendVerifyCommandDirectory({
2140
+ staticLabels: bundle.staticEvidence.commandLabels ?? [],
2141
+ behaviorLabels: bundle.behaviorEvidence.commandLabels ?? [],
2142
+ mockLabels: bundle.mockEvidence?.commandLabels ?? [],
2143
+ lintLabels: bundle.lintEvidence?.commandLabels ?? [],
2144
+ staticCommandTexts: bundle.staticEvidence.commandTexts ?? [],
2145
+ behaviorCommandTexts: bundle.behaviorEvidence.commandTexts ?? [],
2146
+ mockCommandTexts: bundle.mockEvidence?.commandTexts ?? [],
2147
+ lintCommandTexts: bundle.lintEvidence?.commandTexts ?? [],
2148
+ });
2149
+ const frozenCommandLabels = verifyDirectory.map((entry) => entry.label);
2150
+ const unresolvedEntrypointRefs = await deriveUnresolvedVerificationEntrypointRefs(meta.runDir, verifyDirectory.map((entry) => entry.commandId));
2151
+ verificationConfigRoute = routeVerificationConfig({
2152
+ unresolvedEntrypointRefs: unresolvedEntrypointRefs.map((ref) => ref.ref),
2153
+ });
2154
+ const allowlistedResolvers = [
2155
+ ...new Set(frozenCommandLabels
2156
+ .map((label) => label.trim())
2157
+ .filter(Boolean)),
2158
+ ].sort();
2159
+ if (verificationConfigRoute.decision ===
2160
+ "verification-config-decision" &&
2161
+ unresolvedEntrypointRefs.length > 0 &&
2162
+ allowlistedResolvers.length > 0) {
2163
+ const envelope = buildFrontendHumanDecisionEnvelope({
2164
+ operationId: input.task.id,
2165
+ runId: meta.runId,
2166
+ operationRevision: 1,
2167
+ targetDigest: sha256Hex(frozenCommandLabels.slice().sort().join("\n")),
2168
+ staleOnTargetDigestChange: true,
2169
+ kind: "verification-config",
2170
+ resumeAction: "select-verification-config",
2171
+ payload: {
2172
+ unresolvedEntrypointRefs,
2173
+ allowlistedResolvers,
2174
+ },
2175
+ });
2176
+ await writeDagRunJsonArtifact(meta.runDir, "contracts/frontend-verification-config-envelope.json", envelope);
2177
+ }
1913
2178
  }
2179
+ const verifyFailure = {
2180
+ schemaVersion: 1,
2181
+ schemaId: "frontend-verify-failure-v1",
2182
+ nodeId: failedNodeId,
2183
+ failureCategory,
2184
+ failureClass,
2185
+ failureOwner,
2186
+ restartPhase,
2187
+ ...(verificationConfigRoute
2188
+ ? { verificationConfigRoute }
2189
+ : {}),
2190
+ commandResults,
2191
+ failedAt: new Date().toISOString(),
2192
+ };
2193
+ await writeDagRunJsonArtifact(meta.runDir, "contracts/frontend-verify-failure.json", verifyFailure);
1914
2194
  return {
1915
- ok: true,
1916
- stdout: lintAssessment?.status === "baseline-debt"
1917
- ? "Frontend reverify bundle: pass with lint baseline-debt"
1918
- : "Frontend reverify bundle: pass",
1919
- stderr: "",
1920
- failureCategory: "success",
2195
+ ok: false,
2196
+ stdout: summarizeCommandResults(results).stdout,
2197
+ stderr: firstFailure?.stderr ||
2198
+ lintSyntheticFailure?.stderr ||
2199
+ traceError?.message ||
2200
+ "frontend verification failed",
2201
+ failureCategory,
1921
2202
  durationMs: Date.now() - started,
1922
2203
  ...{ commandResults },
1923
2204
  };
1924
2205
  }
1925
- const failureFacts = [];
1926
- if (firstFailure || lintSyntheticFailure) {
1927
- const failureStdout = firstFailure
1928
- ? [firstFailure.command, firstFailure.stdout].filter(Boolean).join("\n")
1929
- : "";
1930
- failureFacts.push({
1931
- nodeId: input.task.id,
1932
- record: {
1933
- status: "FINISHED",
1934
- failureCategory: firstFailure?.failureCategory ??
1935
- lintSyntheticFailure?.failureCategory,
1936
- // Keep classification scoped to the failed command. Aggregate
1937
- // successful output may contain unrelated writeSet-like JSON.
1938
- stdout: failureStdout,
1939
- stderr: firstFailure?.stderr ?? lintSyntheticFailure?.stderr,
1940
- commandResults,
1941
- },
1942
- });
2206
+ // A+B (AC-008): when lint is `require-clean` but the assessment proves
2207
+ // baseline-debt, materialize the frozen `baseline-debt-acceptance` envelope
2208
+ // whose only positive resume is `accept-baseline-debt`. Evidence stays
2209
+ // `baseline-debt` and is never rewritten to `passed`.
2210
+ if (lintAssessment?.status === "baseline-debt") {
2211
+ const baselineEvidenceRefs = (lintAssessment.rawEvidenceRefs ?? [])
2212
+ .filter((ref) => ref?.path && ref?.sha256)
2213
+ .map((ref) => ({ ref: ref.path, digest: ref.sha256 }));
2214
+ if (baselineEvidenceRefs.length > 0) {
2215
+ const envelope = buildFrontendHumanDecisionEnvelope({
2216
+ operationId: input.task.id,
2217
+ runId: meta.runId,
2218
+ operationRevision: 1,
2219
+ targetDigest: lintAssessment.commandIdentity.sha256,
2220
+ staleOnTargetDigestChange: true,
2221
+ kind: "baseline-debt-acceptance",
2222
+ resumeAction: "accept-baseline-debt",
2223
+ payload: {
2224
+ baselineEvidenceRefs,
2225
+ candidateDigest: lintAssessment.commandIdentity.sha256,
2226
+ commandDigest: lintAssessment.commandIdentity.sha256,
2227
+ resultingPolicy: "allow-non-regression",
2228
+ },
2229
+ });
2230
+ await writeDagRunJsonArtifact(meta.runDir, "contracts/frontend-baseline-debt-acceptance-envelope.json", envelope);
2231
+ }
1943
2232
  }
1944
- if (traceError) {
1945
- failureFacts.push({
1946
- nodeId: "frontend-verification-trace-shell",
1947
- record: {
1948
- status: "FINISHED",
1949
- failureCategory: "invalid-output",
1950
- stderr: traceError.message,
1951
- },
1952
- });
2233
+ return {
2234
+ ok: true,
2235
+ stdout: lintAssessment?.status === "baseline-debt"
2236
+ ? "Frontend verification bundle: pass with lint baseline-debt"
2237
+ : "Frontend verification bundle: pass",
2238
+ stderr: "",
2239
+ failureCategory: "success",
2240
+ durationMs: Date.now() - started,
2241
+ ...{ commandResults },
2242
+ };
2243
+ }
2244
+ /* ------------------------------------------------------------------ *
2245
+ * M8 deterministic frontend shell nodes: design policy, writer *
2246
+ * admission, closeout. These replace the prewrite-gate authorization *
2247
+ * path and the Pi closeout node. *
2248
+ * ------------------------------------------------------------------ */
2249
+ async function readRunDirJson(runDir, relativePath) {
2250
+ return JSON.parse(await readFile(path.join(runDir, relativePath), "utf8"));
2251
+ }
2252
+ /** Committed typed review terminal kinds from the review node's typed event
2253
+ * store (AC-003: typed terminal tools are the only authoritative verdict). */
2254
+ async function collectReviewTerminalKinds(runDir, reviewNodeId) {
2255
+ try {
2256
+ const records = await readTypedEventStoreFromJsonl(path.join(runDir, reviewNodeId, "review-typed-facts.jsonl"));
2257
+ return records
2258
+ .filter((record) => record.phase === "committed")
2259
+ .map((record) => {
2260
+ const kind = record.fact.kind;
2261
+ return typeof kind === "string" ? kind : "";
2262
+ })
2263
+ .filter(Boolean);
2264
+ }
2265
+ catch {
2266
+ return [];
2267
+ }
2268
+ }
2269
+ /** Committed typed design terminal kinds from the design review node's typed
2270
+ * event store (M8: the committed approve_design / request_design_changes fact
2271
+ * is the only authoritative verdict; the legacy first-line VERDICT text is
2272
+ * never read for writer admission). Fail-closed on a missing/unreadable store. */
2273
+ async function collectDesignTerminalKinds(runDir, designNodeId) {
2274
+ try {
2275
+ const records = await readTypedEventStoreFromJsonl(path.join(runDir, designNodeId, "design-typed-facts.jsonl"));
2276
+ return records
2277
+ .filter((record) => record.phase === "committed")
2278
+ .map((record) => {
2279
+ const kind = record.fact.kind;
2280
+ return typeof kind === "string" ? kind : "";
2281
+ })
2282
+ .filter(Boolean);
2283
+ }
2284
+ catch {
2285
+ return [];
2286
+ }
2287
+ }
2288
+ /** A+B (AC-009): deterministic §4.10 restart phase for a committed
2289
+ * `request_review_changes` fact. The typed issueCategory is mapped through the
2290
+ * frozen classifier; `unknown` (or an unreadable store) fails closed to
2291
+ * `undefined` so the runtime never trusts an untyped category. */
2292
+ async function collectReviewRestartPhase(runDir, reviewNodeId) {
2293
+ try {
2294
+ const records = await readTypedEventStoreFromJsonl(path.join(runDir, reviewNodeId, "review-typed-facts.jsonl"));
2295
+ const request = records.find((record) => record.phase === "committed" &&
2296
+ record.fact.kind === "request_review_changes");
2297
+ const issueCategory = request?.fact
2298
+ ?.issueCategory;
2299
+ return typeof issueCategory === "string"
2300
+ ? (classifyIssueCategoryRestartPhase(issueCategory) ?? undefined)
2301
+ : undefined;
2302
+ }
2303
+ catch {
2304
+ return undefined;
2305
+ }
2306
+ }
2307
+ /** A+B (AC-009): deterministic §4.10 restart phase for a committed
2308
+ * `request_design_changes` fact. Mirrors the review collector. */
2309
+ /** Read the committed design request as a bounded structured capsule. */
2310
+ async function collectDesignReviewFindings(runDir, designNodeId) {
2311
+ try {
2312
+ const records = await readTypedEventStoreFromJsonl(path.join(runDir, designNodeId, "design-typed-facts.jsonl"));
2313
+ const request = records.find((record) => record.phase === "committed" &&
2314
+ record.fact.kind ===
2315
+ "request_design_changes");
2316
+ const fact = request?.fact;
2317
+ const findings = Array.isArray(fact?.findings)
2318
+ ? fact.findings.flatMap((finding) => {
2319
+ if (!finding || typeof finding !== "object")
2320
+ return [];
2321
+ const value = finding;
2322
+ if (!(["Critical", "Important", "Minor", "Info"].includes(value.severity) &&
2323
+ typeof value.issue === "string" && value.issue.trim().length > 0))
2324
+ return [];
2325
+ return [{
2326
+ severity: value.severity,
2327
+ ...(typeof value.file === "string" && value.file.trim() ? { file: value.file } : {}),
2328
+ ...(typeof value.line === "number" && Number.isInteger(value.line) && value.line > 0 ? { line: value.line } : {}),
2329
+ issue: value.issue,
2330
+ ...(typeof value.requiredChange === "string" && value.requiredChange.trim() ? { requiredChange: value.requiredChange } : {}),
2331
+ }];
2332
+ }).slice(0, 16)
2333
+ : [];
2334
+ const evidenceRefs = Array.isArray(fact?.evidenceRefs)
2335
+ ? fact.evidenceRefs.filter((ref) => typeof ref === "string" && ref.trim().length > 0).slice(0, 16)
2336
+ : [];
2337
+ return { findings, evidenceRefs };
2338
+ }
2339
+ catch {
2340
+ return { findings: [], evidenceRefs: [] };
2341
+ }
2342
+ }
2343
+ async function collectDesignRestartPhase(runDir, designNodeId) {
2344
+ try {
2345
+ const records = await readTypedEventStoreFromJsonl(path.join(runDir, designNodeId, "design-typed-facts.jsonl"));
2346
+ const request = records.find((record) => record.phase === "committed" &&
2347
+ record.fact.kind === "request_design_changes");
2348
+ const issueCategory = request?.fact
2349
+ ?.issueCategory;
2350
+ return typeof issueCategory === "string"
2351
+ ? (classifyIssueCategoryRestartPhase(issueCategory) ?? undefined)
2352
+ : undefined;
2353
+ }
2354
+ catch {
2355
+ return undefined;
2356
+ }
2357
+ }
2358
+ /**
2359
+ * Resolve the deterministic runtime skeleton for the frontend plan patch from
2360
+ * the DAG spec. The plan task carries it via `structuredContractOutput.skeleton`
2361
+ * (the only schema-recognized persistent channel); absence is a fail-closed
2362
+ * generation/configuration defect, never a reason to fall back to text.
2363
+ */
2364
+ function resolveFrontendContractSkeleton(spec, planNodeId) {
2365
+ const planTask = spec.tasks.find((task) => task.id === planNodeId);
2366
+ const skeleton = planTask?.structuredContractOutput?.skeleton;
2367
+ if (!skeleton || Object.keys(skeleton).length === 0) {
2368
+ throw new Error(`frontend design policy blocked: missing runtime contract skeleton for ${planNodeId}`);
2369
+ }
2370
+ return skeleton;
2371
+ }
2372
+ async function collectFrontendSourceFreshness(input) {
2373
+ const entries = [];
2374
+ for (const source of input.sourceBinding?.sources ?? []) {
2375
+ entries.push({ path: source.path, sha256: source.sha256, fresh: true });
2376
+ }
2377
+ for (const evidencePath of input.contract.designEvidence.paths) {
2378
+ if (entries.some((entry) => entry.path === evidencePath))
2379
+ continue;
2380
+ try {
2381
+ const bytes = await readFile(path.join(input.workspaceRoot, evidencePath));
2382
+ entries.push({
2383
+ path: evidencePath,
2384
+ sha256: createHash("sha256").update(bytes).digest("hex"),
2385
+ fresh: true,
2386
+ });
2387
+ }
2388
+ catch {
2389
+ entries.push({
2390
+ path: evidencePath,
2391
+ sha256: "0".repeat(64),
2392
+ fresh: false,
2393
+ });
2394
+ }
2395
+ }
2396
+ return entries;
2397
+ }
2398
+ /** R3/R4 openspec invariants: frozen candidates must exist and content
2399
+ * snapshots must not have drifted. Citation is enforced upstream by the
2400
+ * prewrite gate read-event evidence and ledger specReference conformance. */
2401
+ async function checkFrontendOpenspecFacts(input) {
2402
+ const frozenCandidatePaths = input.config.openspecCandidatePaths ?? [];
2403
+ const candidateRoot = input.workspaceRoot;
2404
+ const missingCandidates = [];
2405
+ for (const candidate of frozenCandidatePaths) {
2406
+ try {
2407
+ await stat(path.join(candidateRoot, candidate));
2408
+ }
2409
+ catch {
2410
+ missingCandidates.push(candidate);
2411
+ }
2412
+ }
2413
+ if (missingCandidates.length > 0) {
2414
+ throw new Error(`frontend design policy blocked: openspec candidate paths frozen at generation time no longer exist on disk: ${missingCandidates.join(", ")}`);
2415
+ }
2416
+ const snapshots = input.config.openspecCandidateSnapshots;
2417
+ if (snapshots && snapshots.length > 0) {
2418
+ for (const snapshot of snapshots) {
2419
+ try {
2420
+ const bytes = await readFile(path.join(candidateRoot, snapshot.path));
2421
+ const actual = createHash("sha256").update(bytes).digest("hex");
2422
+ if (actual !== snapshot.sha256) {
2423
+ throw new Error(`frontend design policy blocked: openspec candidate content hash drifted: ${snapshot.path}`);
2424
+ }
2425
+ }
2426
+ catch (error) {
2427
+ if (error instanceof Error &&
2428
+ error.message.startsWith("frontend design policy blocked")) {
2429
+ throw error;
2430
+ }
2431
+ throw new Error(`frontend design policy blocked: openspec candidate unreadable: ${snapshot.path}`);
2432
+ }
2433
+ }
1953
2434
  }
2435
+ }
2436
+ async function executeFrontendDesignPolicy(input, meta) {
2437
+ const started = Date.now();
2438
+ const shell = input.task.shell;
2439
+ const config = shell.frontendDesignPolicy;
1954
2440
  try {
1955
- const assessment = await runFrontendFailureAssessGate({
2441
+ // 1. Materialize the canonical contract from committed typed facts. After
2442
+ // M9a the plan node's assistantText is a pure Markdown narrative; the
2443
+ // compile authority is the committed plan ledger ⊕ runtime skeleton.
2444
+ // Fail closed on missing committed facts — never fall back to text.
2445
+ const { readCommittedOriginFacts, checkCommittedOriginFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
2446
+ // A+B (AC-001/003): fail-closed committed contract/scout typed facts.
2447
+ // Missing/uncommitted facts block here; never fall back to text parsing.
2448
+ const committedContractFacts = await readCommittedOriginFacts(meta.runDir, "frontend-contract-pi", "contract-typed-facts.jsonl");
2449
+ const contractCheck = checkCommittedOriginFacts({
2450
+ records: committedContractFacts,
2451
+ origin: "contract",
2452
+ });
2453
+ if (!contractCheck.ok) {
2454
+ return {
2455
+ ok: false,
2456
+ stdout: "",
2457
+ stderr: `frontend design policy blocked: ${contractCheck.reason}`,
2458
+ failureCategory: "invalid-output",
2459
+ durationMs: Date.now() - started,
2460
+ };
2461
+ }
2462
+ const committedScoutFacts = await readCommittedOriginFacts(meta.runDir, "frontend-scout-pi", "scout-typed-facts.jsonl");
2463
+ const scoutCheck = checkCommittedOriginFacts({
2464
+ records: committedScoutFacts,
2465
+ origin: "scout",
2466
+ });
2467
+ if (!scoutCheck.ok) {
2468
+ return {
2469
+ ok: false,
2470
+ stdout: "",
2471
+ stderr: `frontend design policy blocked: ${scoutCheck.reason}`,
2472
+ failureCategory: "invalid-output",
2473
+ durationMs: Date.now() - started,
2474
+ };
2475
+ }
2476
+ const skeleton = resolveFrontendContractSkeleton(meta.spec, config.planFromNodeId);
2477
+ const assembled = await buildContractFromCommittedFacts({
2478
+ runDir: meta.runDir,
2479
+ planNodeId: config.planFromNodeId,
2480
+ contractNodeId: "frontend-contract-pi",
2481
+ sourceBinding: meta.spec.sourceBinding,
2482
+ skeleton,
2483
+ });
2484
+ if (!assembled.ok) {
2485
+ return {
2486
+ ok: false,
2487
+ stdout: "",
2488
+ stderr: `frontend design policy blocked: ${assembled.reason}`,
2489
+ failureCategory: "invalid-output",
2490
+ durationMs: Date.now() - started,
2491
+ };
2492
+ }
2493
+ const contract = assembled.canonical;
2494
+ // 2. Requirement id retention (R11): search the canonical contract
2495
+ // serialization instead of the plan node narrative.
2496
+ const contractText = serializeCompactDeterministicJson(contract);
2497
+ const missingIds = config.requiredRequirementIds.filter((id) => !contractText.includes(id));
2498
+ if (missingIds.length > 0) {
2499
+ return {
2500
+ ok: false,
2501
+ stdout: "",
2502
+ stderr: `frontend design policy blocked: missing requirement ids: ${missingIds.join(", ")}`,
2503
+ failureCategory: "invalid-output",
2504
+ durationMs: Date.now() - started,
2505
+ };
2506
+ }
2507
+ // 3. Mock strategy allowed + frozen command binding (R1).
2508
+ const mockStrategy = contract.mockApi.strategy;
2509
+ if (!config.allowedMockStrategies.includes(mockStrategy)) {
2510
+ return {
2511
+ ok: false,
2512
+ stdout: "",
2513
+ stderr: `frontend contract mock strategy "${mockStrategy}" is incompatible with the generated allowed strategies [${config.allowedMockStrategies.join(", ")}]`,
2514
+ failureCategory: "invalid-output",
2515
+ durationMs: Date.now() - started,
2516
+ };
2517
+ }
2518
+ if (mockStrategy !== "not-needed" && config.mockCommandLabels.length === 0) {
2519
+ return {
2520
+ ok: false,
2521
+ stdout: "",
2522
+ stderr: `frontend design policy blocked: contract selected Mock strategy ${mockStrategy} but the DAG has no authorized Mock verification commands`,
2523
+ failureCategory: "invalid-output",
2524
+ durationMs: Date.now() - started,
2525
+ };
2526
+ }
2527
+ // 4. writeSet containment.
2528
+ if (config.implementationWriteSet) {
2529
+ const writeSet = new Set(config.implementationWriteSet);
2530
+ const uncoveredTargets = contract.targets.files.filter((target) => ![...writeSet].some((pattern) => pathMatchesPattern(target, pattern) || target === pattern));
2531
+ if (uncoveredTargets.length > 0) {
2532
+ return {
2533
+ ok: false,
2534
+ stdout: "",
2535
+ stderr: `frontend design policy blocked: contract target is outside implementation writeSet: ${uncoveredTargets.join(", ")}`,
2536
+ failureCategory: "invalid-output",
2537
+ durationMs: Date.now() - started,
2538
+ };
2539
+ }
2540
+ const uncoveredVTs = contract.verificationTargets
2541
+ .filter((vt) => vt.mode !== "static")
2542
+ .filter((vt) => ![...writeSet].some((pattern) => pathMatchesPattern(vt.file, pattern) || vt.file === pattern));
2543
+ if (uncoveredVTs.length > 0) {
2544
+ return {
2545
+ ok: false,
2546
+ stdout: "",
2547
+ stderr: `frontend design policy blocked: verification target is outside implementation writeSet: ${uncoveredVTs.map((vt) => vt.file).join(", ")}`,
2548
+ failureCategory: "invalid-output",
2549
+ durationMs: Date.now() - started,
2550
+ };
2551
+ }
2552
+ }
2553
+ // 5. Source freshness (R4) + freshness entries.
2554
+ if (config.requireSourceFreshness) {
2555
+ if (!meta.spec.sourceBinding) {
2556
+ throw new Error("frontend design policy requires sourceBinding for freshness check");
2557
+ }
2558
+ await assertFrontendSourceBindingFresh({
2559
+ workspaceRoot: input.cwd,
2560
+ binding: meta.spec.sourceBinding,
2561
+ });
2562
+ }
2563
+ // Byte freshness is necessary but not sufficient: require the same ledger
2564
+ // semantic checks as the shadow prewrite gate before production writer
2565
+ // admission can be materialized.
2566
+ if (meta.spec.sourceBinding) {
2567
+ const ledgerCheck = await checkFrontendSourceFidelityLedger({
2568
+ workspaceRoot: input.cwd,
2569
+ binding: meta.spec.sourceBinding,
2570
+ contractRequirements: contract.requirements.map((requirement) => ({
2571
+ id: requirement.id,
2572
+ sourceFragmentIds: requirement.sourceFragmentIds,
2573
+ sourceRefs: requirement.sourceRefs,
2574
+ })),
2575
+ });
2576
+ if (!ledgerCheck.ok) {
2577
+ return {
2578
+ ok: false,
2579
+ stdout: "",
2580
+ stderr: `frontend design policy blocked: ${ledgerCheck.failureReason ?? "source fidelity ledger validation failed"}`,
2581
+ failureCategory: "invalid-output",
2582
+ durationMs: Date.now() - started,
2583
+ };
2584
+ }
2585
+ }
2586
+ const sourceFreshness = await collectFrontendSourceFreshness({
2587
+ workspaceRoot: input.cwd,
2588
+ sourceBinding: meta.spec.sourceBinding,
2589
+ contract,
2590
+ });
2591
+ // 6. Openspec invariants (R3): frozen candidates exist and snapshots have
2592
+ // not drifted. Citation is superseded by prewrite-gate read evidence.
2593
+ await checkFrontendOpenspecFacts({
2594
+ workspaceRoot: input.cwd,
2595
+ config,
2596
+ });
2597
+ // 7. Deterministic design policy (M8 D2: designApproval is optional here;
2598
+ // the design verdict is enforced by the writer-admission shell).
2599
+ const policyResult = evaluateFrontendDesignPolicy({
2600
+ contract,
2601
+ allowedMockStrategies: config.allowedMockStrategies,
2602
+ sourceFreshness,
2603
+ componentSpecCandidatePaths: config.openspecCandidatePaths ??
2604
+ config.componentSpecCandidatePaths ??
2605
+ [],
2606
+ allowedDependencies: config.allowedDependencies,
2607
+ writeSetPatterns: config.implementationWriteSet ?? [],
2608
+ });
2609
+ // 8. Write canonical contract + policy result.
2610
+ const contractArtifact = await writeFrontendImplementationContractArtifact({
1956
2611
  runDir: meta.runDir,
1957
- failureFacts,
2612
+ outputDir: config.outputDir,
2613
+ artifactName: config.artifactName,
2614
+ canonical: contract,
1958
2615
  });
1959
- await runFrontendRepairContractGate({ runDir: meta.runDir });
2616
+ await writeDagRunJsonArtifact(meta.runDir, "contracts/frontend-design-policy-result.json", policyResult);
2617
+ if (policyResult.classification === "blocked") {
2618
+ return {
2619
+ ok: false,
2620
+ stdout: "",
2621
+ stderr: `frontend design policy blocked: ${policyResult.findings.map((finding) => `${finding.code}: ${finding.message}`).join("; ")}`,
2622
+ failureCategory: "invalid-output",
2623
+ durationMs: Date.now() - started,
2624
+ };
2625
+ }
1960
2626
  return {
1961
2627
  ok: true,
1962
- stdout: formatFrontendFailureAssessStdout(assessment),
2628
+ stdout: [
2629
+ "Frontend design policy: approved findings=0",
2630
+ `Contract: ${contractArtifact.path}`,
2631
+ `Contract index: ${contractArtifact.reviewIndexPath}`,
2632
+ `Capacity diagnostic: ${contractArtifact.capacityDiagnosticPath} (non-blocking)`,
2633
+ ].join("\n"),
1963
2634
  stderr: "",
1964
2635
  failureCategory: "success",
1965
2636
  durationMs: Date.now() - started,
1966
- ...{ commandResults },
1967
2637
  };
1968
2638
  }
1969
2639
  catch (error) {
@@ -1973,30 +2643,180 @@ async function executeFrontendVerificationBundle(input, meta) {
1973
2643
  stderr: error instanceof Error ? error.message : String(error),
1974
2644
  failureCategory: "invalid-output",
1975
2645
  durationMs: Date.now() - started,
1976
- ...{ commandResults },
1977
2646
  };
1978
2647
  }
1979
2648
  }
1980
- async function executeFrontendTestCaseChecklist(input, meta) {
2649
+ async function executeFrontendWriterAdmission(input, meta) {
1981
2650
  const started = Date.now();
2651
+ const shell = input.task.shell;
2652
+ const config = shell.frontendWriterAdmission;
1982
2653
  try {
1983
- const declaredAcIds = (meta.spec.sourceBinding?.requirementIds ?? []).filter((id) => /^AC(?:-[A-Z0-9]+)+$/i.test(id));
1984
- const result = await validateFrontendCaseChecklist({
2654
+ // 1. Design verdict handling. The typed terminal
2655
+ // verdict is read from the committed typed design terminal fact, not
2656
+ // from the legacy first-line VERDICT text protocol (AC-003/AC-004).
2657
+ // A request_design_changes verdict blocks writer admission and is copied
2658
+ // into the receipt as a bounded advisory capsule for recovery. A missing
2659
+ // typed terminal verdict still fails closed. In small topology the design
2660
+ // review node is absent and the check is vacuous.
2661
+ let verdictPass = true;
2662
+ let designRequested = false;
2663
+ let designAdvisory;
2664
+ if (config.designReviewFromNodeId) {
2665
+ const designKinds = await collectDesignTerminalKinds(meta.runDir, config.designReviewFromNodeId);
2666
+ if (designKinds.length !== 1) {
2667
+ verdictPass = false;
2668
+ }
2669
+ else if (designKinds[0] !== "approve_design") {
2670
+ designRequested = true;
2671
+ const designFindings = await collectDesignReviewFindings(meta.runDir, config.designReviewFromNodeId);
2672
+ designAdvisory = {
2673
+ verdict: "request_design_changes",
2674
+ restartPhase: await collectDesignRestartPhase(meta.runDir, config.designReviewFromNodeId),
2675
+ findingCount: designFindings.findings.length,
2676
+ findings: designFindings.findings,
2677
+ evidenceRefs: designFindings.evidenceRefs,
2678
+ };
2679
+ verdictPass = false;
2680
+ }
2681
+ }
2682
+ // 2. Read the canonical contract + design-policy result.
2683
+ const contractRaw = await readRunDirJson(meta.runDir, "contracts/frontend-implementation-contract.json");
2684
+ const contract = frontendImplementationContractSchema.parse(contractRaw);
2685
+ const policyRaw = (await readRunDirJson(meta.runDir, "contracts/frontend-design-policy-result.json"));
2686
+ if (policyRaw.schemaId !== "frontend-design-policy-v1") {
2687
+ throw new Error("frontend writer admission: design policy result artifact invalid");
2688
+ }
2689
+ const designPolicyResult = {
2690
+ schemaId: "frontend-design-policy-v1",
2691
+ classification: policyRaw.classification === "approved" ? "approved" : "blocked",
2692
+ findings: policyRaw.findings ?? [],
2693
+ digest: "",
2694
+ };
2695
+ // 3. Freeze the pre-writer worktree baseline (cumulative diff baseline).
2696
+ await captureFrontendWorktreeBaseline({
2697
+ runDir: meta.runDir,
1985
2698
  workspaceRoot: input.cwd,
1986
- declaredAcIds,
1987
2699
  });
1988
- if (result.issues.length) {
2700
+ const baselineRaw = (await readRunDirJson(meta.runDir, "contracts/frontend-worktree-baseline.json"));
2701
+ const baseline = (baselineRaw.files ?? [])
2702
+ .map((file) => ({
2703
+ path: file,
2704
+ sha256: baselineRaw.hashes?.[file] ?? null,
2705
+ }))
2706
+ .filter((entry) => entry.sha256 !== null);
2707
+ // 4. Writer-preceding lint baseline (R5) when lint is configured.
2708
+ let lintResults = [];
2709
+ if ((config.lintCommands?.length ?? 0) > 0) {
2710
+ for (const command of config.lintCommands) {
2711
+ const commandNumber = lintResults.length + 1;
2712
+ const result = await executeShellCommand({
2713
+ command,
2714
+ cwd: input.cwd,
2715
+ timeoutMs: shell.timeoutMs ?? DEFAULT_SHELL_TIMEOUT_MS,
2716
+ envAllowlist: shell.envAllowlist,
2717
+ dagRunMeta: { runDir: meta.runDir, runId: meta.runId },
2718
+ reportActivity: input.reportActivity,
2719
+ outputArtifacts: {
2720
+ stdoutPath: path.join(meta.runDir, input.task.id, "commands", `${commandNumber}.stdout.txt`),
2721
+ stderrPath: path.join(meta.runDir, input.task.id, "commands", `${commandNumber}.stderr.txt`),
2722
+ },
2723
+ });
2724
+ lintResults.push(result);
2725
+ }
2726
+ await materializeFrontendLintBaseline({
2727
+ runDir: meta.runDir,
2728
+ workspaceRoot: input.cwd,
2729
+ commands: config.lintCommands,
2730
+ results: lintResults,
2731
+ worktreeChanged: false,
2732
+ });
2733
+ }
2734
+ // 5. Derive admission (writeSet + digests + findings). Glob entries in
2735
+ // the contract targets (e.g. `src/**` inherited from the skeleton) are
2736
+ // expanded against the concrete workspace files so the derived writeSet
2737
+ // contains only real paths the writer can touch.
2738
+ const workspaceFiles = await collectWorkspaceFiles(input.cwd);
2739
+ const admission = deriveFrontendWriterAdmissionShell({
2740
+ contract,
2741
+ designPolicyResult,
2742
+ baseline,
2743
+ frozenCommandLabels: config.frozenCommandLabels,
2744
+ allowedMockStrategies: config.allowedMockStrategies,
2745
+ workspaceFiles,
2746
+ });
2747
+ // 6. Design verdict enforcement: request_design_changes is a blocked
2748
+ // admission. This keeps the writer fail-closed until the recovery plan
2749
+ // has incorporated the reviewer's concrete findings.
2750
+ const failureSource = policyRaw.classification === "blocked"
2751
+ ? "frontend-design-policy-shell"
2752
+ : "frontend-writer-admission-shell";
2753
+ const findings = verdictPass
2754
+ ? admission.findings
2755
+ : [
2756
+ ...admission.findings,
2757
+ {
2758
+ code: designRequested
2759
+ ? "design-review-requested"
2760
+ : "design-approval-missing",
2761
+ message: designRequested
2762
+ ? "design review requested changes; writer admission is blocked until recovery incorporates the committed findings"
2763
+ : "design review typed terminal verdict missing or ambiguous (fail closed)",
2764
+ },
2765
+ ];
2766
+ const classification = findings.length === 0 && admission.classification === "accepted"
2767
+ ? admission.classification
2768
+ : findings.length === 0 &&
2769
+ admission.classification === "requires-human-approval"
2770
+ ? "requires-human-approval"
2771
+ : "blocked";
2772
+ const result = frontendWriterAdmissionResultV1Schema.parse({
2773
+ schemaVersion: 1,
2774
+ schemaId: "frontend-writer-admission-shell-v1",
2775
+ classification,
2776
+ writeSet: admission.writeSet,
2777
+ writeSetDigest: admission.writeSetDigest,
2778
+ baselineDigest: admission.baselineDigest,
2779
+ admissionDigest: admission.admissionDigest,
2780
+ ...(admission.baselineDebtPolicy !== undefined
2781
+ ? { baselineDebtPolicy: admission.baselineDebtPolicy }
2782
+ : {}),
2783
+ findings,
2784
+ ...(designAdvisory ? { designReviewAdvisory: designAdvisory } : {}),
2785
+ failureSource,
2786
+ });
2787
+ await writeDagRunJsonArtifact(meta.runDir, FRONTEND_WRITER_ADMISSION_RESULT_ARTIFACT, result);
2788
+ // A+B (AC-007): High topology materializes a `high-admission-receipt-v1`
2789
+ // catalog whose candidate digest must match the admission digest before
2790
+ // the gate can transition from `requires-human-approval` to `accepted`.
2791
+ // Any digest drift resolves to `stale` (never silently accepted).
2792
+ if (classification === "requires-human-approval") {
2793
+ const receipt = evaluateHighAdmissionReceipt({
2794
+ candidateDigest: result.admissionDigest,
2795
+ admissionDigest: result.admissionDigest,
2796
+ });
2797
+ await writeDagRunJsonArtifact(meta.runDir, "contracts/frontend-high-admission-receipt.json", receipt);
2798
+ if (receipt.status !== "accepted") {
2799
+ return {
2800
+ ok: false,
2801
+ stdout: "",
2802
+ stderr: `frontend writer admission stale: high-admission receipt candidate digest drifted from admission digest`,
2803
+ failureCategory: "invalid-output",
2804
+ durationMs: Date.now() - started,
2805
+ };
2806
+ }
2807
+ }
2808
+ if (classification === "blocked") {
1989
2809
  return {
1990
2810
  ok: false,
1991
2811
  stdout: "",
1992
- stderr: `frontend-test checklist blocked: ${JSON.stringify(result.issues)}`,
2812
+ stderr: `frontend writer admission ${classification}: ${findings.map((finding) => `${finding.code}: ${finding.message}`).join("; ")}`,
1993
2813
  failureCategory: "invalid-output",
1994
2814
  durationMs: Date.now() - started,
1995
2815
  };
1996
2816
  }
1997
2817
  return {
1998
2818
  ok: true,
1999
- stdout: `frontend-test checklist ok cases=${result.caseCount} source=${path.basename(result.manifestPath)}`,
2819
+ stdout: `Frontend writer admission: ${classification} writeSet=${result.writeSet.length} writeSetDigest=${result.writeSetDigest}`,
2000
2820
  stderr: "",
2001
2821
  failureCategory: "success",
2002
2822
  durationMs: Date.now() - started,
@@ -2012,12 +2832,219 @@ async function executeFrontendTestCaseChecklist(input, meta) {
2012
2832
  };
2013
2833
  }
2014
2834
  }
2015
- async function executeFrontendTestL5Report(input, meta) {
2835
+ async function executeFrontendContractImport(input, meta) {
2836
+ const started = Date.now();
2837
+ const shell = input.task.shell;
2838
+ const config = shell.frontendContractImport;
2839
+ try {
2840
+ const binding = meta.spec.sourceBinding;
2841
+ if (!binding) {
2842
+ throw new Error("frontend contract-import requires a DAG sourceBinding to re-validate freshness");
2843
+ }
2844
+ if (config.requireSourceFreshness) {
2845
+ await assertFrontendSourceBindingFresh({
2846
+ workspaceRoot: input.cwd,
2847
+ binding,
2848
+ });
2849
+ }
2850
+ const digest = createHash("sha256")
2851
+ .update(JSON.stringify({
2852
+ taskId: binding.taskId,
2853
+ sources: binding.sources,
2854
+ artifactName: config.artifactName,
2855
+ }))
2856
+ .digest("hex");
2857
+ const facts = {
2858
+ schemaVersion: 1,
2859
+ schemaId: "frontend-contract-import-v1",
2860
+ artifactName: config.artifactName,
2861
+ sourceBindingTaskId: binding.taskId,
2862
+ sourceCount: binding.sources.length,
2863
+ fresh: true,
2864
+ digest,
2865
+ };
2866
+ return {
2867
+ ok: true,
2868
+ stdout: JSON.stringify(facts, null, 2),
2869
+ stderr: "",
2870
+ failureCategory: "success",
2871
+ durationMs: Date.now() - started,
2872
+ };
2873
+ }
2874
+ catch (error) {
2875
+ return {
2876
+ ok: false,
2877
+ stdout: "",
2878
+ stderr: error instanceof Error ? error.message : String(error),
2879
+ failureCategory: "invalid-output",
2880
+ durationMs: Date.now() - started,
2881
+ };
2882
+ }
2883
+ }
2884
+ async function executeFrontendCloseout(input, meta) {
2885
+ const started = Date.now();
2886
+ const shell = input.task.shell;
2887
+ const config = shell.frontendCloseout;
2888
+ try {
2889
+ const context = (await readRunDirJson(meta.runDir, "contracts/frontend-review-context.json"));
2890
+ if (context.contractRef?.path !==
2891
+ "contracts/frontend-implementation-contract.json") {
2892
+ throw new Error("frontend closeout missing canonical contract reference");
2893
+ }
2894
+ const contractRaw = await readFile(path.join(meta.runDir, context.contractRef.path), "utf8");
2895
+ const contractSha256 = createHash("sha256")
2896
+ .update(contractRaw)
2897
+ .digest("hex");
2898
+ if (contractSha256 !== context.contractRef.sha256) {
2899
+ throw new Error("frontend closeout canonical contract hash mismatch");
2900
+ }
2901
+ const contract = frontendImplementationContractSchema.parse(JSON.parse(contractRaw));
2902
+ const trace = context.verificationTrace;
2903
+ const verificationTargets = (trace?.targets ?? []).map((target) => ({
2904
+ status: target.status === "ok" ? "ok" : "failed",
2905
+ }));
2906
+ const mockEvidenceBound = contract.mockApi.strategy !== "not-needed" &&
2907
+ typeof trace?.mockCommandNodeId === "string" &&
2908
+ trace.mockCommandNodeId.length > 0 &&
2909
+ Array.isArray(trace?.mockCommandLabels) &&
2910
+ trace.mockCommandLabels.length > 0 &&
2911
+ Array.isArray(trace?.mockCommandTexts) &&
2912
+ trace.mockCommandTexts.length === trace.mockCommandLabels.length;
2913
+ const integrationFacts = deriveFrontendIntegrationFacts({
2914
+ mockStrategy: contract.mockApi.strategy,
2915
+ realApiEvidence: { present: false, passed: false },
2916
+ mockEvidenceBound,
2917
+ verificationTargets,
2918
+ });
2919
+ // Typed review terminal (AC-003) from the committed typed event store.
2920
+ const typedKinds = await collectReviewTerminalKinds(meta.runDir, config.reviewFromNodeId);
2921
+ const typedVerdict = typedKinds.length === 1 &&
2922
+ (typedKinds[0] === "approve_review" || typedKinds[0] === "request_review_changes")
2923
+ ? typedKinds[0]
2924
+ : null;
2925
+ // A+B (AC-009): request_review_changes issueCategory maps to the
2926
+ // deterministic §4.10 restart phase. Recorded as a run-owned audit
2927
+ // artifact so the frozen closeout schema is never widened; `unknown`
2928
+ // fails closed to no restart phase.
2929
+ const reviewRestartPhase = typedVerdict === "request_review_changes"
2930
+ ? await collectReviewRestartPhase(meta.runDir, config.reviewFromNodeId)
2931
+ : undefined;
2932
+ if (reviewRestartPhase !== undefined) {
2933
+ await writeDagRunJsonArtifact(meta.runDir, "contracts/frontend-review-restart-phase.json", {
2934
+ schemaVersion: 1,
2935
+ nodeId: config.reviewFromNodeId,
2936
+ restartPhase: reviewRestartPhase,
2937
+ });
2938
+ }
2939
+ const facts = frontendCloseoutFactsSchema.parse({
2940
+ schemaVersion: 1,
2941
+ schemaId: "frontend-closeout-facts-v1",
2942
+ coverageMatrix: verificationTargets.map((target, index) => ({
2943
+ verificationTargetId: trace?.targets?.[index]?.id ?? `vt-${index}`,
2944
+ status: target.status === "ok" ? "passed" : "failed",
2945
+ })),
2946
+ lintStatus: "unavailable",
2947
+ integrationFacts,
2948
+ reviewApproval: {
2949
+ typedVerdict,
2950
+ legacyVerdict: null,
2951
+ match: true,
2952
+ },
2953
+ cumulativeDiff: {
2954
+ cumulativeDigest: (typeof context.verificationTrace === "object" &&
2955
+ context.verificationTrace !== null &&
2956
+ "schemaId" in context.verificationTrace
2957
+ ? deterministicSha256({ verificationTrace: context.verificationTrace })
2958
+ : deterministicSha256({})),
2959
+ empty: false,
2960
+ },
2961
+ notRun: { browser: "not-run", visual: "not-run" },
2962
+ pendingRealIntegration: integrationFacts !== "real-api",
2963
+ });
2964
+ const rendered = renderFrontendCloseout(facts);
2965
+ await writeDagRunJsonArtifact(meta.runDir, "contracts/frontend-closeout-facts.json", facts);
2966
+ // A+B (AC-010): materialize the deterministic frontend-test handoff.
2967
+ // browser/visual/runtime-a11y are always `not-run` and the handoff is
2968
+ // always `deferred-to-frontend-test`, so it never blocks implementation
2969
+ // and can never be rewritten into a passed result.
2970
+ const handoffTaskId = meta.spec.sourceBinding?.taskId ?? input.task.id;
2971
+ const sourceDigest = meta.spec.sourceBinding
2972
+ ? createHash("sha256")
2973
+ .update(JSON.stringify({
2974
+ taskId: meta.spec.sourceBinding.taskId,
2975
+ sources: meta.spec.sourceBinding.sources,
2976
+ }))
2977
+ .digest("hex")
2978
+ : deterministicSha256({});
2979
+ const handoff = buildFrontendTestHandoff({
2980
+ taskId: handoffTaskId,
2981
+ sourceDigest,
2982
+ candidateHash: facts.cumulativeDiff.cumulativeDigest,
2983
+ });
2984
+ await writeDagRunJsonArtifact(meta.runDir, "contracts/frontend-test-handoff.json", handoff);
2985
+ await writeDagNodeTextArtifact(meta.runDir, input.task.id, "frontend-closeout.md", rendered);
2986
+ return {
2987
+ ok: true,
2988
+ stdout: `Frontend closeout rendered\n${rendered.split("\n").slice(0, 8).join("\n")}`,
2989
+ stderr: "",
2990
+ failureCategory: "success",
2991
+ durationMs: Date.now() - started,
2992
+ };
2993
+ }
2994
+ catch (error) {
2995
+ return {
2996
+ ok: false,
2997
+ stdout: "",
2998
+ stderr: error instanceof Error ? error.message : String(error),
2999
+ failureCategory: "invalid-output",
3000
+ durationMs: Date.now() - started,
3001
+ };
3002
+ }
3003
+ }
3004
+ async function executeFrontendTestCaseChecklist(input, meta) {
3005
+ const started = Date.now();
3006
+ try {
3007
+ const layout = frontendTestLayoutFromSpec(meta.spec);
3008
+ const declaredAcIds = (meta.spec.sourceBinding?.requirementIds ?? []).filter((id) => /^AC(?:-[A-Z0-9]+)+$/i.test(id));
3009
+ const result = await validateFrontendCaseChecklist({
3010
+ workspaceRoot: input.cwd,
3011
+ declaredAcIds,
3012
+ layout,
3013
+ });
3014
+ if (result.issues.length) {
3015
+ return {
3016
+ ok: false,
3017
+ stdout: "",
3018
+ stderr: `frontend-test checklist blocked: ${JSON.stringify(result.issues)}`,
3019
+ failureCategory: "invalid-output",
3020
+ durationMs: Date.now() - started,
3021
+ };
3022
+ }
3023
+ return {
3024
+ ok: true,
3025
+ stdout: `frontend-test checklist ok cases=${result.caseCount} source=${path.basename(result.manifestPath)}`,
3026
+ stderr: "",
3027
+ failureCategory: "success",
3028
+ durationMs: Date.now() - started,
3029
+ };
3030
+ }
3031
+ catch (error) {
3032
+ return {
3033
+ ok: false,
3034
+ stdout: "",
3035
+ stderr: error instanceof Error ? error.message : String(error),
3036
+ failureCategory: "invalid-output",
3037
+ durationMs: Date.now() - started,
3038
+ };
3039
+ }
3040
+ }
3041
+ async function executeFrontendTestL5Report(input, meta) {
2016
3042
  const started = Date.now();
2017
3043
  try {
2018
3044
  const output = await renderFrontendTestL5Report({
2019
3045
  workspaceRoot: input.cwd,
2020
3046
  runDir: meta.runDir,
3047
+ layout: frontendTestLayoutFromSpec(meta.spec),
2021
3048
  });
2022
3049
  return {
2023
3050
  ok: true,
@@ -2043,6 +3070,7 @@ async function executeFrontendTestHtmlReport(input, meta) {
2043
3070
  const output = await renderFrontendTestHtmlReport({
2044
3071
  workspaceRoot: input.cwd,
2045
3072
  runDir: meta.runDir,
3073
+ layout: frontendTestLayoutFromSpec(meta.spec),
2046
3074
  });
2047
3075
  return {
2048
3076
  ok: true,
@@ -2062,11 +3090,60 @@ async function executeFrontendTestHtmlReport(input, meta) {
2062
3090
  };
2063
3091
  }
2064
3092
  }
2065
- async function executeFrontendTestEvidenceValidation(input) {
3093
+ async function executeFrontendTestStandardScenarios(input, meta) {
3094
+ const started = Date.now();
3095
+ try {
3096
+ const result = await copyFrontendTestStandardScenarios({
3097
+ workspaceRoot: input.cwd,
3098
+ layout: frontendTestLayoutFromSpec(meta.spec),
3099
+ });
3100
+ return {
3101
+ ok: true,
3102
+ stdout: JSON.stringify(result),
3103
+ stderr: "",
3104
+ failureCategory: "success",
3105
+ durationMs: Date.now() - started,
3106
+ };
3107
+ }
3108
+ catch (error) {
3109
+ return {
3110
+ ok: false,
3111
+ stdout: "",
3112
+ stderr: error instanceof Error ? error.message : String(error),
3113
+ failureCategory: "invalid-output",
3114
+ durationMs: Date.now() - started,
3115
+ };
3116
+ }
3117
+ }
3118
+ async function executeFrontendTestEnvironmentProbe(input, meta) {
3119
+ const started = Date.now();
3120
+ const result = await probeFrontendTestEnvironment({
3121
+ workspaceRoot: input.cwd,
3122
+ layout: frontendTestLayoutFromSpec(meta.spec),
3123
+ });
3124
+ if (result.ok) {
3125
+ return {
3126
+ ok: true,
3127
+ stdout: result.stdout,
3128
+ stderr: "",
3129
+ failureCategory: "success",
3130
+ durationMs: Date.now() - started,
3131
+ };
3132
+ }
3133
+ return {
3134
+ ok: false,
3135
+ stdout: "",
3136
+ stderr: result.stderr,
3137
+ failureCategory: "nonzero-exit",
3138
+ durationMs: Date.now() - started,
3139
+ };
3140
+ }
3141
+ async function executeFrontendTestEvidenceValidation(input, meta) {
2066
3142
  const started = Date.now();
2067
3143
  try {
2068
3144
  const result = await validateFrontendCaseEvidence({
2069
3145
  workspaceRoot: input.cwd,
3146
+ layout: frontendTestLayoutFromSpec(meta.spec),
2070
3147
  });
2071
3148
  const output = `frontend case evidence validation cases=${result.cases} findings=${result.issues.length}${result.issues.length ? ` issues=${JSON.stringify(result.issues)}` : ""}`;
2072
3149
  if (result.hardFail) {
@@ -2096,6 +3173,31 @@ async function executeFrontendTestEvidenceValidation(input) {
2096
3173
  };
2097
3174
  }
2098
3175
  }
3176
+ async function executeFrontendTestCaseGenerationAssessment(input, meta) {
3177
+ const started = Date.now();
3178
+ try {
3179
+ const gate = input.task.shell?.frontendTestCaseGenerationAssessment;
3180
+ const state = JSON.parse(await readFile(path.join(meta.runDir, "state.json"), "utf8"));
3181
+ const raw = state.nodes?.[gate.plannerNodeId]?.stdout;
3182
+ if (!raw)
3183
+ throw new Error(`frontend-test planner output missing: ${gate.plannerNodeId}`);
3184
+ const match = raw.match(/\{[\s\S]*\}/);
3185
+ if (!match)
3186
+ throw new Error("frontend-test planner output is not JSON");
3187
+ const planned = JSON.parse(match[0]);
3188
+ if (!Array.isArray(planned.cases))
3189
+ throw new Error("frontend-test planner output must contain cases");
3190
+ const assessment = await assessFrontendCaseGeneration({
3191
+ workspaceRoot: input.cwd,
3192
+ plannerCases: planned.cases,
3193
+ declaredAcIds: gate.declaredAcIds ?? [],
3194
+ });
3195
+ return { ok: true, stdout: `${JSON.stringify(assessment)}\n`, stderr: "", failureCategory: "success", durationMs: Date.now() - started };
3196
+ }
3197
+ catch (error) {
3198
+ return { ok: false, stdout: "", stderr: error instanceof Error ? error.message : String(error), failureCategory: "invalid-output", durationMs: Date.now() - started };
3199
+ }
3200
+ }
2099
3201
  async function executeFrontendTestCasePackageFinalize(input, meta) {
2100
3202
  const started = Date.now();
2101
3203
  try {
@@ -2143,6 +3245,22 @@ async function executeFrontendTestCasePackageFinalize(input, meta) {
2143
3245
  const index = ["# 前端功能测试用例索引", "", ...cases.map((c) => `- ${c.caseId}: ${c.title}(${c.dimension}) | AC: ${c.acIds.join(", ") || "无"} | 数据策略: ${c.dataStrategy}`), ""].join("\n");
2144
3246
  await writeFile(path.join(root, "index.md"), index, "utf8");
2145
3247
  await writeFile(path.join(root, "manifest.draft.json"), JSON.stringify(manifest, null, 2) + "\n", "utf8");
3248
+ const generationAssessment = await assessFrontendCaseGeneration({
3249
+ workspaceRoot: input.cwd,
3250
+ plannerCases: cases,
3251
+ declaredAcIds: gate.declaredAcIds ?? [],
3252
+ });
3253
+ await writeFile(path.join(root, "generation-assessment.json"), JSON.stringify(generationAssessment, null, 2) + "\n", "utf8");
3254
+ if (generationAssessment.repairCases.length > 0) {
3255
+ for (const repair of generationAssessment.repairCases) {
3256
+ const entry = manifest.cases.find((candidate) => candidate.caseId === repair.caseId);
3257
+ if (entry) {
3258
+ entry.generationStatus = "blocked";
3259
+ entry.generationBlockedReason = `generation-repair-required:${repair.reasons.join(",")}`;
3260
+ }
3261
+ }
3262
+ await writeFile(path.join(root, "manifest.draft.json"), JSON.stringify(manifest, null, 2) + "\n", "utf8");
3263
+ }
2146
3264
  const checklist = await validateFrontendCaseChecklist({ workspaceRoot: input.cwd, declaredAcIds: gate.declaredAcIds ?? [] });
2147
3265
  if (checklist.issues.length)
2148
3266
  throw new Error(`frontend-test checklist blocked: ${JSON.stringify(checklist.issues)}`);
@@ -2190,6 +3308,7 @@ async function executeFrontendTestCaseManifest(input, meta) {
2190
3308
  const checklist = await validateFrontendCaseChecklist({
2191
3309
  workspaceRoot: input.cwd,
2192
3310
  declaredAcIds,
3311
+ layout: frontendTestLayoutFromSpec(meta.spec),
2193
3312
  });
2194
3313
  if (checklist.issues.length) {
2195
3314
  return {
@@ -2204,6 +3323,7 @@ async function executeFrontendTestCaseManifest(input, meta) {
2204
3323
  workspaceRoot: input.cwd,
2205
3324
  maxCases: gate.maxCases,
2206
3325
  declaredAcIds,
3326
+ layout: frontendTestLayoutFromSpec(meta.spec),
2207
3327
  });
2208
3328
  return {
2209
3329
  ok: true,
@@ -2241,6 +3361,7 @@ async function executeFrontendTestResultFinalize(input, meta) {
2241
3361
  try {
2242
3362
  const evidence = await validateFrontendCaseEvidence({
2243
3363
  workspaceRoot: input.cwd,
3364
+ layout: frontendTestLayoutFromSpec(meta.spec),
2244
3365
  });
2245
3366
  advisoryStdout = `frontend case evidence validation cases=${evidence.cases} findings=${evidence.issues.length}${evidence.issues.length ? ` issues=${JSON.stringify(evidence.issues)}` : ""}`;
2246
3367
  // Advisory findings must not block materialize; only hardFail (path escape) does.
@@ -2259,6 +3380,7 @@ async function executeFrontendTestResultFinalize(input, meta) {
2259
3380
  artifactName: "frontend-test-result.json",
2260
3381
  outputDir: "contracts",
2261
3382
  sourceBinding: meta.spec.sourceBinding,
3383
+ layout: frontendTestLayoutFromSpec(meta.spec),
2262
3384
  });
2263
3385
  return {
2264
3386
  ok: true,
@@ -2297,12 +3419,14 @@ async function executeFrontendTestReports(input, meta) {
2297
3419
  const l5 = await renderFrontendTestL5Report({
2298
3420
  workspaceRoot: input.cwd,
2299
3421
  runDir: meta.runDir,
3422
+ layout: frontendTestLayoutFromSpec(meta.spec),
2300
3423
  });
2301
3424
  lines.push(`Frontend L-5 report: ${l5.htmlPath}\nMarkdown: ${l5.markdownPath}\nStatus: ${l5.metrics.status}`);
2302
3425
  }
2303
3426
  const report = await renderFrontendTestHtmlReport({
2304
3427
  workspaceRoot: input.cwd,
2305
3428
  runDir: meta.runDir,
3429
+ layout: frontendTestLayoutFromSpec(meta.spec),
2306
3430
  });
2307
3431
  lines.push(`Frontend test report: ${report.htmlPath}\nMarkdown: ${report.markdownPath}\nOutcome: ${report.outcome}\nCases: ${report.caseCount}`);
2308
3432
  return {
@@ -2323,69 +3447,76 @@ async function executeFrontendTestReports(input, meta) {
2323
3447
  };
2324
3448
  }
2325
3449
  }
2326
- async function executeFrontendLintBaseline(input, meta) {
2327
- const started = Date.now();
2328
- const shell = input.task.shell;
2329
- const baseline = shell.frontendLintBaseline;
2330
- const cwd = resolveShellCwd(input.cwd, shell.cwd);
2331
- let beforeStatus;
2332
- try {
2333
- beforeStatus = await readGitStatusPorcelain(input.cwd);
2334
- }
2335
- catch {
2336
- beforeStatus = undefined;
3450
+ async function writeShellPresetProcessReceipt(input) {
3451
+ await writeDagNodeJsonArtifact(input.runDir, input.nodeId, "process-receipt.json", {
3452
+ schemaVersion: 1,
3453
+ kind: "shell-preset",
3454
+ preset: input.preset,
3455
+ ok: input.ok,
3456
+ durationMs: input.durationMs,
3457
+ steps: input.steps,
3458
+ });
3459
+ }
3460
+ async function ensureShellPresetProcessReceipt(input) {
3461
+ const receiptPath = path.join(input.runDir, input.nodeId, "process-receipt.json");
3462
+ if (existsSync(receiptPath))
3463
+ return;
3464
+ if (existsSync(path.join(input.runDir, input.nodeId, "shell-command-receipt.json"))) {
3465
+ return;
2337
3466
  }
2338
- const results = [];
2339
- for (const command of baseline.lintCommands) {
2340
- const commandNumber = results.length + 1;
2341
- results.push(await executeShellCommand({
2342
- command,
2343
- cwd,
2344
- timeoutMs: shell.timeoutMs ?? DEFAULT_SHELL_TIMEOUT_MS,
2345
- envAllowlist: shell.envAllowlist,
2346
- dagRunMeta: { runDir: meta.runDir, runId: meta.runId },
2347
- outputArtifacts: {
2348
- stdoutPath: path.join(meta.runDir, input.task.id, "commands", `${commandNumber}.stdout.txt`),
2349
- stderrPath: path.join(meta.runDir, input.task.id, "commands", `${commandNumber}.stderr.txt`),
3467
+ const detail = input.result.ok ? input.result.stdout : input.result.stderr;
3468
+ await writeShellPresetProcessReceipt({
3469
+ runDir: input.runDir,
3470
+ nodeId: input.nodeId,
3471
+ preset: input.preset,
3472
+ ok: input.result.ok,
3473
+ durationMs: input.result.durationMs,
3474
+ steps: [
3475
+ {
3476
+ id: "run",
3477
+ label: input.preset,
3478
+ ok: input.result.ok,
3479
+ detail: detail?.slice(0, 8 * 1024),
3480
+ durationMs: input.result.durationMs,
2350
3481
  },
2351
- }));
2352
- }
2353
- let afterStatus;
2354
- try {
2355
- afterStatus = await readGitStatusPorcelain(input.cwd);
2356
- }
2357
- catch {
2358
- afterStatus = undefined;
2359
- }
2360
- try {
2361
- const materialized = await materializeFrontendLintBaseline({
2362
- runDir: meta.runDir,
2363
- workspaceRoot: input.cwd,
2364
- commands: baseline.lintCommands,
2365
- results,
2366
- worktreeChanged: beforeStatus === undefined ||
2367
- afterStatus === undefined ||
2368
- beforeStatus !== afterStatus,
2369
- });
2370
- return {
2371
- ok: true,
2372
- stdout: `Frontend lint baseline: ${materialized.artifact.status}\nArtifact: ${materialized.ref.path}\nDiagnostics: ${materialized.artifact.diagnostics.length}`,
2373
- stderr: materialized.artifact.reason ?? "",
2374
- failureCategory: "success",
2375
- durationMs: Date.now() - started,
2376
- };
2377
- }
2378
- catch (error) {
2379
- return {
2380
- ok: false,
2381
- stdout: "",
2382
- stderr: error instanceof Error ? error.message : String(error),
2383
- failureCategory: "invalid-output",
2384
- durationMs: Date.now() - started,
2385
- };
3482
+ ],
3483
+ });
3484
+ }
3485
+ function namedShellHandler(shell) {
3486
+ if (!shell)
3487
+ return null;
3488
+ const record = shell;
3489
+ for (const key of [
3490
+ "finalWriteSetApprovalGate",
3491
+ "frontendTestStandardScenarios",
3492
+ "frontendTestEnvironmentProbe",
3493
+ "frontendBrowserToolPreflight",
3494
+ "frontendPrewriteGate",
3495
+ "frontendLintBaseline",
3496
+ "frontendVerificationBundle",
3497
+ "frontendReviewContext",
3498
+ "frontendTestCaseChecklist",
3499
+ "frontendTestCaseManifest",
3500
+ "frontendTestEvidenceValidation",
3501
+ "frontendTestResultFinalize",
3502
+ "frontendTestL5Report",
3503
+ "frontendTestHtmlReport",
3504
+ "frontendTestReports",
3505
+ "backendTestPipeline",
3506
+ "jsonArtifactGate",
3507
+ "projectGovernanceGate",
3508
+ "requirementCoverageGate",
3509
+ "verdictGate",
3510
+ "verifyEvidence",
3511
+ "repairArtifactGate",
3512
+ "jacocoCoverage",
3513
+ ]) {
3514
+ if (record[key] != null)
3515
+ return key;
2386
3516
  }
3517
+ return null;
2387
3518
  }
2388
- export async function executeDagShellNode(input, meta) {
3519
+ async function executeDagShellNodeInner(input, meta) {
2389
3520
  const shell = input.task.shell;
2390
3521
  if (shell?.finalWriteSetApprovalGate) {
2391
3522
  const started = Date.now();
@@ -2424,30 +3555,91 @@ export async function executeDagShellNode(input, meta) {
2424
3555
  };
2425
3556
  }
2426
3557
  }
3558
+ if (shell?.frontendTestStandardScenarios) {
3559
+ return executeFrontendTestStandardScenarios(input, meta);
3560
+ }
3561
+ if (shell?.frontendTestEnvironmentProbe) {
3562
+ return executeFrontendTestEnvironmentProbe(input, meta);
3563
+ }
2427
3564
  if (shell?.frontendBrowserToolPreflight) {
2428
3565
  const started = Date.now();
3566
+ const steps = [];
3567
+ const finish = async (result) => {
3568
+ await writeShellPresetProcessReceipt({
3569
+ runDir: meta.runDir,
3570
+ nodeId: input.task.id,
3571
+ preset: "frontendBrowserToolPreflight",
3572
+ ok: result.ok,
3573
+ durationMs: result.durationMs,
3574
+ steps: steps.length > 0
3575
+ ? steps
3576
+ : [
3577
+ {
3578
+ id: "run",
3579
+ label: "浏览器工具能力探测",
3580
+ ok: result.ok,
3581
+ detail: result.ok ? result.stdout : result.stderr,
3582
+ durationMs: result.durationMs,
3583
+ },
3584
+ ],
3585
+ });
3586
+ return result;
3587
+ };
2429
3588
  try {
2430
3589
  if (resolvePiBackend() === "cli-only") {
3590
+ steps.push({
3591
+ id: "pi-backend",
3592
+ label: "Pi SDK 后端可用",
3593
+ ok: false,
3594
+ detail: "CODE_AGENT_PI_BACKEND=cli-only",
3595
+ });
2431
3596
  throw new Error("browser-command-capability-unavailable: CODE_AGENT_PI_BACKEND=cli-only rejects SDK-only playwright_cli");
2432
3597
  }
3598
+ steps.push({
3599
+ id: "pi-backend",
3600
+ label: "Pi SDK 后端可用",
3601
+ ok: true,
3602
+ });
2433
3603
  const sdkCapability = await checkPiSdkCustomToolCapability(input.cwd);
2434
3604
  if (!sdkCapability.ok) {
3605
+ steps.push({
3606
+ id: "sdk-custom-tool",
3607
+ label: "Pi SDK custom-tool 能力",
3608
+ ok: false,
3609
+ detail: sdkCapability.detail,
3610
+ });
2435
3611
  throw new Error(`browser-command-capability-unavailable: ${sdkCapability.detail}`);
2436
3612
  }
3613
+ steps.push({
3614
+ id: "sdk-custom-tool",
3615
+ label: "Pi SDK custom-tool 能力",
3616
+ ok: true,
3617
+ });
3618
+ const layout = frontendTestLayoutFromSpec(meta.spec);
2437
3619
  const toolProbe = await createPlaywrightCliTool({
2438
3620
  repoRoot: input.cwd,
2439
3621
  runDir: meta.runDir,
2440
3622
  nodeId: input.task.id,
2441
3623
  caseId: "frontend-browser-preflight",
2442
- evidenceDir: "testcase/frontend/evidence/frontend-browser-preflight",
2443
- // Capability-only registration probe. The tested URL is selected later by
2444
- // retrieve-frontend-test-context-pi and validated by the environment shell.
3624
+ evidenceDir: `${layout.evidenceDir}/frontend-browser-preflight`,
2445
3625
  baseUrl: "http://localhost:5173/",
2446
- inputRoot: "testcase/frontend/fixtures",
3626
+ inputRoot: layout.fixturesDir,
3627
+ layout,
2447
3628
  });
2448
3629
  if (toolProbe.name !== "playwright_cli") {
3630
+ steps.push({
3631
+ id: "structured-tool",
3632
+ label: "注册 playwright_cli",
3633
+ ok: false,
3634
+ detail: toolProbe.name,
3635
+ });
2449
3636
  throw new Error("browser-command-capability-unavailable: structured playwright_cli tool registration failed");
2450
3637
  }
3638
+ steps.push({
3639
+ id: "structured-tool",
3640
+ label: "注册 playwright_cli",
3641
+ ok: true,
3642
+ });
2451
3643
  const launcher = resolvePlaywrightCliLauncher(input.cwd);
2452
3644
  const result = await defaultPlaywrightCliCommandRunner({
2453
3645
  executable: launcher.executable,
@@ -2460,8 +3652,19 @@ export async function executeDagShellNode(input, meta) {
2460
3652
  if (result.exitCode !== 0 ||
2461
3653
  result.timedOut ||
2462
3654
  !["open", "close", "find", "snapshot", "click"].every((command) => new RegExp(`\\b${command}\\b`, "i").test(help))) {
3655
+ steps.push({
3656
+ id: "playwright-cli-help",
3657
+ label: "playwright-cli --help 合同",
3658
+ ok: false,
3659
+ detail: help.slice(0, 8 * 1024),
3660
+ });
2463
3661
  throw new Error("playwright-cli-contract-incompatible");
2464
3662
  }
3663
+ steps.push({
3664
+ id: "playwright-cli-help",
3665
+ label: "playwright-cli --help 合同",
3666
+ ok: true,
3667
+ });
2465
3668
  const capability = {
2466
3669
  schemaVersion: 1,
2467
3670
  status: "ready",
@@ -2472,54 +3675,35 @@ export async function executeDagShellNode(input, meta) {
2472
3675
  targetUrlAuthority: "retrieve-context-and-environment-probe",
2473
3676
  };
2474
3677
  await writeDagNodeJsonArtifact(meta.runDir, input.task.id, "frontend-browser-capability.json", capability);
2475
- return {
3678
+ steps.push({
3679
+ id: "capability-artifact",
3680
+ label: "写出 frontend-browser-capability.json",
3681
+ ok: true,
3682
+ detail: JSON.stringify(capability, null, 2),
3683
+ });
3684
+ return await finish({
2476
3685
  ok: true,
2477
3686
  stdout: JSON.stringify(capability),
2478
3687
  stderr: "",
2479
3688
  failureCategory: "success",
2480
3689
  durationMs: Date.now() - started,
2481
- };
3690
+ });
2482
3691
  }
2483
3692
  catch (error) {
2484
- return {
3693
+ return await finish({
2485
3694
  ok: false,
2486
3695
  stdout: "",
2487
3696
  stderr: `playwright-cli-unavailable: ${error instanceof Error ? error.message : String(error)}`,
2488
3697
  failureCategory: "tool-policy",
2489
3698
  durationMs: Date.now() - started,
2490
- };
2491
- }
2492
- }
2493
- if (shell?.frontendPrewriteGate) {
2494
- const started = Date.now();
2495
- try {
2496
- const result = await runFrontendPrewriteGate({
2497
- runDir: meta.runDir,
2498
- config: shell.frontendPrewriteGate,
2499
- sourceBinding: meta.spec.sourceBinding,
2500
- workspaceRoot: input.cwd,
2501
- repoRoot: input.cwd,
2502
3699
  });
2503
- return {
2504
- ok: true,
2505
- stdout: formatFrontendPrewriteGateStdout(result),
2506
- stderr: "",
2507
- failureCategory: "success",
2508
- durationMs: Date.now() - started,
2509
- };
2510
- }
2511
- catch (error) {
2512
- return {
2513
- ok: false,
2514
- stdout: "",
2515
- stderr: error instanceof Error ? error.message : String(error),
2516
- failureCategory: "invalid-output",
2517
- durationMs: Date.now() - started,
2518
- };
2519
3700
  }
2520
3701
  }
2521
- if (shell?.frontendLintBaseline) {
2522
- return executeFrontendLintBaseline(input, meta);
3702
+ if (shell?.frontendDesignPolicy) {
3703
+ return executeFrontendDesignPolicy(input, meta);
3704
+ }
3705
+ if (shell?.frontendWriterAdmission) {
3706
+ return executeFrontendWriterAdmission(input, meta);
2523
3707
  }
2524
3708
  if (shell?.frontendVerificationBundle) {
2525
3709
  return executeFrontendVerificationBundle(input, meta);
@@ -2550,12 +3734,21 @@ export async function executeDagShellNode(input, meta) {
2550
3734
  };
2551
3735
  }
2552
3736
  }
3737
+ if (shell?.frontendContractImport) {
3738
+ return executeFrontendContractImport(input, meta);
3739
+ }
3740
+ if (shell?.frontendCloseout) {
3741
+ return executeFrontendCloseout(input, meta);
3742
+ }
2553
3743
  if (shell?.frontendTestCaseChecklist) {
2554
3744
  return executeFrontendTestCaseChecklist(input, meta);
2555
3745
  }
2556
3746
  if (shell?.frontendTestCaseManifest) {
2557
3747
  return executeFrontendTestCaseManifest(input, meta);
2558
3748
  }
3749
+ if (shell?.frontendTestCaseGenerationAssessment) {
3750
+ return executeFrontendTestCaseGenerationAssessment(input, meta);
3751
+ }
2559
3752
  if (shell?.frontendTestCasePackageFinalize) {
2560
3753
  return executeFrontendTestCasePackageFinalize(input, meta);
2561
3754
  }
@@ -2563,7 +3756,7 @@ export async function executeDagShellNode(input, meta) {
2563
3756
  return executeFrontendTestRerunCandidates(input, meta);
2564
3757
  }
2565
3758
  if (shell?.frontendTestEvidenceValidation) {
2566
- return executeFrontendTestEvidenceValidation(input);
3759
+ return executeFrontendTestEvidenceValidation(input, meta);
2567
3760
  }
2568
3761
  if (shell?.frontendTestResultFinalize) {
2569
3762
  return executeFrontendTestResultFinalize(input, meta);
@@ -2670,6 +3863,7 @@ export async function executeDagShellNode(input, meta) {
2670
3863
  artifactName: gate.artifactName,
2671
3864
  outputDir: gate.outputDir,
2672
3865
  sourceBinding: meta.spec.sourceBinding,
3866
+ layout: frontendTestLayoutFromSpec(meta.spec),
2673
3867
  });
2674
3868
  break;
2675
3869
  default:
@@ -2777,53 +3971,23 @@ export async function executeDagShellNode(input, meta) {
2777
3971
  }
2778
3972
  if (shell?.commands?.length === 1 &&
2779
3973
  shell.commands[0] === "frontend-failure-assess-gate") {
2780
- const started = Date.now();
2781
- try {
2782
- const result = await runFrontendFailureAssessGate({
2783
- runDir: meta.runDir,
2784
- });
2785
- return {
2786
- ok: true,
2787
- stdout: formatFrontendFailureAssessStdout(result),
2788
- stderr: "",
2789
- failureCategory: "success",
2790
- durationMs: Date.now() - started,
2791
- };
2792
- }
2793
- catch (error) {
2794
- return {
2795
- ok: false,
2796
- stdout: "",
2797
- stderr: error instanceof Error ? error.message : String(error),
2798
- failureCategory: "invalid-output",
2799
- durationMs: Date.now() - started,
2800
- };
2801
- }
3974
+ return {
3975
+ ok: false,
3976
+ stdout: "",
3977
+ stderr: "frontend-failure-assess-gate legacy command removed in M8: verify failure is terminal and materializes failure ownership facts in the verification bundle itself",
3978
+ failureCategory: "invalid-output",
3979
+ durationMs: 0,
3980
+ };
2802
3981
  }
2803
3982
  if (shell?.commands?.length === 1 &&
2804
3983
  shell.commands[0] === "frontend-repair-contract-gate") {
2805
- const started = Date.now();
2806
- try {
2807
- const result = await runFrontendRepairContractGate({
2808
- runDir: meta.runDir,
2809
- });
2810
- return {
2811
- ok: true,
2812
- stdout: formatFrontendRepairContractStdout(result.assessment),
2813
- stderr: "",
2814
- failureCategory: "success",
2815
- durationMs: Date.now() - started,
2816
- };
2817
- }
2818
- catch (error) {
2819
- return {
2820
- ok: false,
2821
- stdout: "",
2822
- stderr: error instanceof Error ? error.message : String(error),
2823
- failureCategory: "invalid-output",
2824
- durationMs: Date.now() - started,
2825
- };
2826
- }
3984
+ return {
3985
+ ok: false,
3986
+ stdout: "",
3987
+ stderr: "frontend-repair-contract-gate legacy command removed in M8: no same-run repair branch exists in the new topology",
3988
+ failureCategory: "invalid-output",
3989
+ durationMs: 0,
3990
+ };
2827
3991
  }
2828
3992
  if (shell?.projectGovernanceGate) {
2829
3993
  const started = Date.now();
@@ -2915,6 +4079,7 @@ export async function executeDagShellNode(input, meta) {
2915
4079
  const cwd = resolveShellCwd(input.cwd, shell.cwd);
2916
4080
  const timeoutMs = shell.timeoutMs ?? DEFAULT_SHELL_TIMEOUT_MS;
2917
4081
  const failFast = shell.failFast !== false;
4082
+ const attemptNumber = input.attempt ?? 1;
2918
4083
  const results = [];
2919
4084
  const executedCommandKeys = new Set();
2920
4085
  let beforeStatus;
@@ -3010,8 +4175,8 @@ export async function executeDagShellNode(input, meta) {
3010
4175
  dagRunMeta: { runDir: meta.runDir, runId: meta.runId },
3011
4176
  reportActivity: input.reportActivity,
3012
4177
  outputArtifacts: {
3013
- stdoutPath: path.join(meta.runDir, input.task.id, "commands", `${commandNumber}.stdout.txt`),
3014
- stderrPath: path.join(meta.runDir, input.task.id, "commands", `${commandNumber}.stderr.txt`),
4178
+ stdoutPath: path.join(meta.runDir, input.task.id, `attempt-${attemptNumber}`, "commands", `${commandNumber}.stdout.txt`),
4179
+ stderrPath: path.join(meta.runDir, input.task.id, `attempt-${attemptNumber}`, "commands", `${commandNumber}.stderr.txt`),
3015
4180
  },
3016
4181
  });
3017
4182
  results.push(result);
@@ -3070,6 +4235,7 @@ export async function executeDagShellNode(input, meta) {
3070
4235
  schemaVersion: 1,
3071
4236
  runId: meta.runId,
3072
4237
  nodeId: input.task.id,
4238
+ attempt: attemptNumber,
3073
4239
  workspaceFingerprint: workspaceFingerprint ?? null,
3074
4240
  failFast,
3075
4241
  commands: results.map((result) => ({
@@ -3088,6 +4254,7 @@ export async function executeDagShellNode(input, meta) {
3088
4254
  subchecks: parseCheckRepoSubcheckDurations(result),
3089
4255
  })),
3090
4256
  };
4257
+ await writeDagNodeJsonArtifact(meta.runDir, input.task.id, path.posix.join(`attempt-${attemptNumber}`, "shell-command-receipt.json"), receipt);
3091
4258
  await writeDagNodeJsonArtifact(meta.runDir, input.task.id, "shell-command-receipt.json", receipt);
3092
4259
  const summaryMarkdown = buildShellResultSummaryMarkdown({
3093
4260
  nodeId: input.task.id,
@@ -3139,8 +4306,57 @@ export async function executeDagShellNode(input, meta) {
3139
4306
  stdout: `${recordPrefix}${reuseNote}${aggregate.stdout}`,
3140
4307
  stderr: stderrParts.filter(Boolean).join("\n\n"),
3141
4308
  failureCategory,
4309
+ ...(firstFailure?.failureCategory
4310
+ ? { rawFailureCategory: firstFailure.failureCategory }
4311
+ : {}),
3142
4312
  durationMs: Date.now() - started,
3143
4313
  // extra field consumed by node-execution if supported; also embedded in stdout marker
3144
4314
  ...{ commandResults },
3145
4315
  };
3146
4316
  }
4317
+ /**
4318
+ * Enumerate the workspace's concrete file paths for glob writeSet expansion.
4319
+ *
4320
+ * Uses `git ls-files -co --exclude-standard` (tracked + untracked, excluding
4321
+ * gitignored) so the expanded writeSet reflects real files the writer can
4322
+ * touch. Falls back to [] when the workspace is not a git repository or git
4323
+ * fails — in that case glob entries fail closed as non-concrete paths.
4324
+ */
4325
+ async function collectWorkspaceFiles(workspaceRoot) {
4326
+ try {
4327
+ const files = await new Promise((resolve, reject) => {
4328
+ const child = spawn("git", ["ls-files", "-co", "--exclude-standard", "-z"], { cwd: workspaceRoot, stdio: ["ignore", "pipe", "ignore"] });
4329
+ const chunks = [];
4330
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
4331
+ child.on("error", reject);
4332
+ child.on("close", (code) => {
4333
+ if (code === 0) {
4334
+ resolve(Buffer.concat(chunks)
4335
+ .toString("utf8")
4336
+ .split("\0")
4337
+ .filter(Boolean));
4338
+ }
4339
+ else {
4340
+ reject(new Error(`git ls-files exited ${String(code)}`));
4341
+ }
4342
+ });
4343
+ });
4344
+ return files.map((file) => file.replace(/\\/g, "/")).sort();
4345
+ }
4346
+ catch {
4347
+ return [];
4348
+ }
4349
+ }
4350
+ export async function executeDagShellNode(input, meta) {
4351
+ const handler = namedShellHandler(input.task.shell);
4352
+ const result = await executeDagShellNodeInner(input, meta);
4353
+ if (handler) {
4354
+ await ensureShellPresetProcessReceipt({
4355
+ runDir: meta.runDir,
4356
+ nodeId: input.task.id,
4357
+ preset: handler,
4358
+ result,
4359
+ });
4360
+ }
4361
+ return result;
4362
+ }